Renderer.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Renderer/Renderer.h>
  6. #include <AnKi/Util/Tracer.h>
  7. #include <AnKi/Core/CVarSet.h>
  8. #include <AnKi/Util/HighRezTimer.h>
  9. #include <AnKi/Collision/Aabb.h>
  10. #include <AnKi/Collision/Plane.h>
  11. #include <AnKi/Collision/Functions.h>
  12. #include <AnKi/Shaders/Include/ClusteredShadingTypes.h>
  13. #include <AnKi/Core/GpuMemory/GpuSceneBuffer.h>
  14. #include <AnKi/Scene/Components/CameraComponent.h>
  15. #include <AnKi/Scene/Components/LightComponent.h>
  16. #include <AnKi/Core/StatsSet.h>
  17. #include <AnKi/Renderer/ProbeReflections.h>
  18. #include <AnKi/Renderer/GBuffer.h>
  19. #include <AnKi/Renderer/GBufferPost.h>
  20. #include <AnKi/Renderer/LightShading.h>
  21. #include <AnKi/Renderer/ShadowMapping.h>
  22. #include <AnKi/Renderer/FinalComposite.h>
  23. #include <AnKi/Renderer/Bloom.h>
  24. #include <AnKi/Renderer/Tonemapping.h>
  25. #include <AnKi/Renderer/ForwardShading.h>
  26. #include <AnKi/Renderer/LensFlare.h>
  27. #include <AnKi/Renderer/Dbg.h>
  28. #include <AnKi/Renderer/DownscaleBlur.h>
  29. #include <AnKi/Renderer/VolumetricFog.h>
  30. #include <AnKi/Renderer/DepthDownscale.h>
  31. #include <AnKi/Renderer/TemporalAA.h>
  32. #include <AnKi/Renderer/UiStage.h>
  33. #include <AnKi/Renderer/VolumetricLightingAccumulation.h>
  34. #include <AnKi/Renderer/IndirectDiffuseProbes.h>
  35. #include <AnKi/Renderer/ShadowmapsResolve.h>
  36. #include <AnKi/Renderer/RtShadows.h>
  37. #include <AnKi/Renderer/AccelerationStructureBuilder.h>
  38. #include <AnKi/Renderer/MotionVectors.h>
  39. #include <AnKi/Renderer/Scale.h>
  40. #include <AnKi/Renderer/VrsSriGeneration.h>
  41. #include <AnKi/Renderer/PrimaryNonRenderableVisibility.h>
  42. #include <AnKi/Renderer/ClusterBinning.h>
  43. #include <AnKi/Renderer/Ssao.h>
  44. #include <AnKi/Renderer/Ssr.h>
  45. #include <AnKi/Renderer/Sky.h>
  46. #include <AnKi/Renderer/Utils/Drawer.h>
  47. #include <AnKi/Renderer/Utils/GpuVisibility.h>
  48. #include <AnKi/Renderer/Utils/MipmapGenerator.h>
  49. #include <AnKi/Renderer/Utils/Readback.h>
  50. #include <AnKi/Renderer/Utils/HzbGenerator.h>
  51. namespace anki {
  52. static NumericCVar<F32> g_internalRenderScalingCVar(CVarSubsystem::kRenderer, "InternalRenderScaling", 1.0f, 0.5f, 1.0f,
  53. "A factor over the requested swapchain resolution. Applies to all passes up to TAA");
  54. NumericCVar<F32> g_renderScalingCVar(CVarSubsystem::kRenderer, "RenderScaling", 1.0f, 0.5f, 8.0f,
  55. "A factor over the requested swapchain resolution. Applies to post-processing and UI");
  56. static NumericCVar<U32> g_zSplitCountCVar(CVarSubsystem::kRenderer, "ZSplitCount", 64, 8, kMaxZsplitCount, "Clusterer number of Z splits");
  57. static NumericCVar<U8> g_textureAnisotropyCVar(CVarSubsystem::kRenderer, "TextureAnisotropy", (ANKI_PLATFORM_MOBILE) ? 1 : 16, 1, 16,
  58. "Texture anisotropy for the main passes");
  59. BoolCVar g_preferComputeCVar(CVarSubsystem::kRenderer, "PreferCompute", !ANKI_PLATFORM_MOBILE, "Prefer compute shaders");
  60. static BoolCVar g_highQualityHdrCVar(CVarSubsystem::kRenderer, "HighQualityHdr", !ANKI_PLATFORM_MOBILE,
  61. "If true use R16G16B16 for HDR images. Alternatively use B10G11R11");
  62. BoolCVar g_vrsLimitTo2x2CVar(CVarSubsystem::kRenderer, "VrsLimitTo2x2", false, "If true the max rate will be 2x2");
  63. BoolCVar g_vrsCVar(CVarSubsystem::kRenderer, "Vrs", true, "Enable VRS in multiple passes");
  64. BoolCVar g_rayTracedShadowsCVar(CVarSubsystem::kRenderer, "RayTracedShadows", true,
  65. "Enable or not ray traced shadows. Ignored if RT is not supported");
  66. NumericCVar<U8> g_shadowCascadeCountCVar(CVarSubsystem::kRenderer, "ShadowCascadeCount", (ANKI_PLATFORM_MOBILE) ? 3 : kMaxShadowCascades, 1,
  67. kMaxShadowCascades, "Max number of shadow cascades for directional lights");
  68. NumericCVar<F32> g_shadowCascade0DistanceCVar(CVarSubsystem::kRenderer, "ShadowCascade0Distance", 18.0, 1.0, kMaxF32,
  69. "The distance of the 1st cascade");
  70. NumericCVar<F32> g_shadowCascade1DistanceCVar(CVarSubsystem::kRenderer, "ShadowCascade1Distance", (ANKI_PLATFORM_MOBILE) ? 80.0f : 40.0, 1.0, kMaxF32,
  71. "The distance of the 2nd cascade");
  72. NumericCVar<F32> g_shadowCascade2DistanceCVar(CVarSubsystem::kRenderer, "ShadowCascade2Distance", (ANKI_PLATFORM_MOBILE) ? 150.0f : 80.0, 1.0,
  73. kMaxF32, "The distance of the 3rd cascade");
  74. NumericCVar<F32> g_shadowCascade3DistanceCVar(CVarSubsystem::kRenderer, "ShadowCascade3Distance", 200.0, 1.0, kMaxF32,
  75. "The distance of the 4th cascade");
  76. NumericCVar<F32> g_lod0MaxDistanceCVar(CVarSubsystem::kRenderer, "Lod0MaxDistance", 20.0f, 1.0f, kMaxF32,
  77. "Distance that will be used to calculate the LOD 0");
  78. NumericCVar<F32> g_lod1MaxDistanceCVar(CVarSubsystem::kRenderer, "Lod1MaxDistance", 40.0f, 2.0f, kMaxF32,
  79. "Distance that will be used to calculate the LOD 1");
  80. static StatCounter g_primitivesDrawnStatVar(StatCategory::kRenderer, "Primitives drawn", StatFlag::kMainThreadUpdates | StatFlag::kZeroEveryFrame);
  81. /// Generate a Halton jitter in [-0.5, 0.5]
  82. static Vec2 generateJitter(U32 frame)
  83. {
  84. // Halton jitter
  85. Vec2 result(0.0f);
  86. constexpr U32 baseX = 2;
  87. U32 index = frame + 1;
  88. F32 invBase = 1.0f / baseX;
  89. F32 fraction = invBase;
  90. while(index > 0)
  91. {
  92. result.x() += F32(index % baseX) * fraction;
  93. index /= baseX;
  94. fraction *= invBase;
  95. }
  96. constexpr U32 baseY = 3;
  97. index = frame + 1;
  98. invBase = 1.0f / baseY;
  99. fraction = invBase;
  100. while(index > 0)
  101. {
  102. result.y() += F32(index % baseY) * fraction;
  103. index /= baseY;
  104. fraction *= invBase;
  105. }
  106. result.x() -= 0.5f;
  107. result.y() -= 0.5f;
  108. return result;
  109. }
  110. Renderer::Renderer()
  111. {
  112. }
  113. Renderer::~Renderer()
  114. {
  115. }
  116. Error Renderer::init(UVec2 swapchainSize, StackMemoryPool* framePool)
  117. {
  118. ANKI_TRACE_SCOPED_EVENT(RInit);
  119. m_framePool = framePool;
  120. const Error err = initInternal(swapchainSize);
  121. if(err)
  122. {
  123. ANKI_R_LOGE("Failed to initialize the renderer");
  124. }
  125. return err;
  126. }
  127. Error Renderer::initInternal(UVec2 swapchainResolution)
  128. {
  129. m_frameCount = 0;
  130. // Set from the config
  131. m_postProcessResolution = UVec2(Vec2(swapchainResolution) * g_renderScalingCVar.get());
  132. alignRoundDown(2, m_postProcessResolution.x());
  133. alignRoundDown(2, m_postProcessResolution.y());
  134. m_internalResolution = UVec2(Vec2(m_postProcessResolution) * g_internalRenderScalingCVar.get());
  135. alignRoundDown(2, m_internalResolution.x());
  136. alignRoundDown(2, m_internalResolution.y());
  137. ANKI_R_LOGI("Initializing offscreen renderer. Resolution %ux%u. Internal resolution %ux%u", m_postProcessResolution.x(),
  138. m_postProcessResolution.y(), m_internalResolution.x(), m_internalResolution.y());
  139. m_tileCounts.x() = (m_internalResolution.x() + kClusteredShadingTileSize - 1) / kClusteredShadingTileSize;
  140. m_tileCounts.y() = (m_internalResolution.y() + kClusteredShadingTileSize - 1) / kClusteredShadingTileSize;
  141. m_zSplitCount = g_zSplitCountCVar.get();
  142. // A few sanity checks
  143. if(m_internalResolution.x() < 64 || m_internalResolution.y() < 64)
  144. {
  145. ANKI_R_LOGE("Incorrect sizes");
  146. return Error::kUserData;
  147. }
  148. ANKI_CHECK(ResourceManager::getSingleton().loadResource("ShaderBinaries/ClearTextureCompute.ankiprogbin", m_clearTexComputeProg));
  149. // Dummy resources
  150. {
  151. TextureInitInfo texinit("RendererDummy");
  152. texinit.m_width = texinit.m_height = 4;
  153. texinit.m_usage = TextureUsageBit::kAllSampled | TextureUsageBit::kStorageComputeWrite;
  154. texinit.m_format = Format::kR8G8B8A8_Unorm;
  155. m_dummyTex2d = createAndClearRenderTarget(texinit, TextureUsageBit::kAllSampled);
  156. texinit.m_depth = 4;
  157. texinit.m_type = TextureType::k3D;
  158. m_dummyTex3d = createAndClearRenderTarget(texinit, TextureUsageBit::kAllSampled);
  159. m_dummyBuff = GrManager::getSingleton().newBuffer(
  160. BufferInitInfo(1024, BufferUsageBit::kAllUniform | BufferUsageBit::kAllStorage, BufferMapAccessBit::kNone, "Dummy"));
  161. }
  162. // Init the stages
  163. #define ANKI_RENDERER_OBJECT_DEF(name, name2, initCondition) \
  164. if(initCondition) \
  165. { \
  166. m_##name2.reset(newInstance<name>(RendererMemoryPool::getSingleton())); \
  167. ANKI_CHECK(m_##name2->init()); \
  168. }
  169. #include <AnKi/Renderer/RendererObject.def.h>
  170. // Init samplers
  171. {
  172. SamplerInitInfo sinit("NearestNearestClamp");
  173. sinit.m_addressing = SamplingAddressing::kClamp;
  174. sinit.m_mipmapFilter = SamplingFilter::kNearest;
  175. sinit.m_minMagFilter = SamplingFilter::kNearest;
  176. m_samplers.m_nearestNearestClamp = GrManager::getSingleton().newSampler(sinit);
  177. sinit.setName("TrilinearClamp");
  178. sinit.m_minMagFilter = SamplingFilter::kLinear;
  179. sinit.m_mipmapFilter = SamplingFilter::kLinear;
  180. m_samplers.m_trilinearClamp = GrManager::getSingleton().newSampler(sinit);
  181. sinit.setName("TrilinearRepeat");
  182. sinit.m_addressing = SamplingAddressing::kRepeat;
  183. m_samplers.m_trilinearRepeat = GrManager::getSingleton().newSampler(sinit);
  184. if(g_textureAnisotropyCVar.get() <= 1u)
  185. {
  186. m_samplers.m_trilinearRepeatAniso = m_samplers.m_trilinearRepeat;
  187. }
  188. else
  189. {
  190. sinit.setName("TrilinearRepeatAniso");
  191. sinit.m_anisotropyLevel = g_textureAnisotropyCVar.get();
  192. m_samplers.m_trilinearRepeatAniso = GrManager::getSingleton().newSampler(sinit);
  193. }
  194. sinit.setName("TrilinearRepeatAnisoRezScalingBias");
  195. F32 scalingMipBias = log2(F32(m_internalResolution.x()) / F32(m_postProcessResolution.x()));
  196. if(getScale().getUsingGrUpscaler())
  197. {
  198. // DLSS wants more bias
  199. scalingMipBias -= 1.0f;
  200. }
  201. sinit.m_lodBias = scalingMipBias;
  202. m_samplers.m_trilinearRepeatAnisoResolutionScalingBias = GrManager::getSingleton().newSampler(sinit);
  203. sinit = {};
  204. sinit.setName("TrilinearClampShadow");
  205. sinit.m_minMagFilter = SamplingFilter::kLinear;
  206. sinit.m_mipmapFilter = SamplingFilter::kLinear;
  207. sinit.m_compareOperation = CompareOperation::kLessEqual;
  208. m_samplers.m_trilinearClampShadow = GrManager::getSingleton().newSampler(sinit);
  209. }
  210. for(U32 i = 0; i < m_jitterOffsets.getSize(); ++i)
  211. {
  212. m_jitterOffsets[i] = generateJitter(i);
  213. }
  214. return Error::kNone;
  215. }
  216. Error Renderer::populateRenderGraph(RenderingContext& ctx)
  217. {
  218. #if ANKI_STATS_ENABLED
  219. updatePipelineStats();
  220. #endif
  221. const CameraComponent& cam = SceneGraph::getSingleton().getActiveCameraNode().getFirstComponentOfType<CameraComponent>();
  222. ctx.m_prevMatrices = m_prevMatrices;
  223. ctx.m_matrices.m_cameraTransform = Mat3x4(cam.getFrustum().getWorldTransform());
  224. ctx.m_matrices.m_view = cam.getFrustum().getViewMatrix();
  225. ctx.m_matrices.m_projection = cam.getFrustum().getProjectionMatrix();
  226. ctx.m_matrices.m_viewProjection = cam.getFrustum().getViewProjectionMatrix();
  227. Vec2 jitter = m_jitterOffsets[m_frameCount & (m_jitterOffsets.getSize() - 1)]; // In [-0.5, 0.5]
  228. jitter *= 2.0f; // In [-1, 1]
  229. const Vec2 ndcPixelSize = 1.0f / Vec2(m_internalResolution);
  230. jitter *= ndcPixelSize;
  231. ctx.m_matrices.m_jitter = Mat4::getIdentity();
  232. ctx.m_matrices.m_jitter.setTranslationPart(Vec3(jitter, 0.0f));
  233. ctx.m_matrices.m_jitterOffsetNdc = jitter;
  234. ctx.m_matrices.m_projectionJitter = ctx.m_matrices.m_jitter * ctx.m_matrices.m_projection;
  235. ctx.m_matrices.m_viewProjectionJitter = ctx.m_matrices.m_projectionJitter * Mat4(ctx.m_matrices.m_view, Vec4(0.0f, 0.0f, 0.0f, 1.0f));
  236. ctx.m_matrices.m_invertedViewProjectionJitter = ctx.m_matrices.m_viewProjectionJitter.getInverse();
  237. ctx.m_matrices.m_invertedViewProjection = ctx.m_matrices.m_viewProjection.getInverse();
  238. ctx.m_matrices.m_invertedProjectionJitter = ctx.m_matrices.m_projectionJitter.getInverse();
  239. ctx.m_matrices.m_reprojection = ctx.m_prevMatrices.m_viewProjection * ctx.m_matrices.m_invertedViewProjection;
  240. ctx.m_matrices.m_unprojectionParameters = ctx.m_matrices.m_projection.extractPerspectiveUnprojectionParams();
  241. ctx.m_cameraNear = cam.getNear();
  242. ctx.m_cameraFar = cam.getFar();
  243. // Allocate global constants
  244. GlobalRendererUniforms* globalUnis;
  245. ctx.m_globalRenderingUniformsBuffer = RebarTransientMemoryPool::getSingleton().allocateFrame(1, globalUnis);
  246. // Import RTs first
  247. m_downscaleBlur->importRenderTargets(ctx);
  248. m_tonemapping->importRenderTargets(ctx);
  249. m_vrsSriGeneration->importRenderTargets(ctx);
  250. m_gbuffer->importRenderTargets(ctx);
  251. // Populate render graph. WARNING Watch the order
  252. gpuSceneCopy(ctx);
  253. m_primaryNonRenderableVisibility->populateRenderGraph(ctx);
  254. if(m_accelerationStructureBuilder)
  255. {
  256. m_accelerationStructureBuilder->populateRenderGraph(ctx);
  257. }
  258. m_gbuffer->populateRenderGraph(ctx);
  259. m_shadowMapping->populateRenderGraph(ctx);
  260. m_clusterBinning2->populateRenderGraph(ctx);
  261. m_sky->populateRenderGraph(ctx);
  262. m_indirectDiffuseProbes->populateRenderGraph(ctx);
  263. m_probeReflections->populateRenderGraph(ctx);
  264. m_volumetricLightingAccumulation->populateRenderGraph(ctx);
  265. m_motionVectors->populateRenderGraph(ctx);
  266. m_gbufferPost->populateRenderGraph(ctx);
  267. m_depthDownscale->populateRenderGraph(ctx);
  268. m_ssr->populateRenderGraph(ctx);
  269. if(m_rtShadows)
  270. {
  271. m_rtShadows->populateRenderGraph(ctx);
  272. }
  273. m_shadowmapsResolve->populateRenderGraph(ctx);
  274. m_volumetricFog->populateRenderGraph(ctx);
  275. m_lensFlare->populateRenderGraph(ctx);
  276. m_ssao->populateRenderGraph(ctx);
  277. m_forwardShading->populateRenderGraph(ctx); // This may feel out of place but it's only visibility. Keep it just before light shading
  278. m_lightShading->populateRenderGraph(ctx);
  279. if(!getScale().getUsingGrUpscaler())
  280. {
  281. m_temporalAA->populateRenderGraph(ctx);
  282. }
  283. m_vrsSriGeneration->populateRenderGraph(ctx);
  284. m_scale->populateRenderGraph(ctx);
  285. m_downscaleBlur->populateRenderGraph(ctx);
  286. m_tonemapping->populateRenderGraph(ctx);
  287. m_bloom->populateRenderGraph(ctx);
  288. m_dbg->populateRenderGraph(ctx);
  289. m_finalComposite->populateRenderGraph(ctx);
  290. writeGlobalRendererConstants(ctx, *globalUnis);
  291. return Error::kNone;
  292. }
  293. void Renderer::writeGlobalRendererConstants(RenderingContext& ctx, GlobalRendererUniforms& unis)
  294. {
  295. ANKI_TRACE_SCOPED_EVENT(RWriteGlobalRendererConstants);
  296. unis.m_renderingSize = Vec2(F32(m_internalResolution.x()), F32(m_internalResolution.y()));
  297. unis.m_time = F32(HighRezTimer::getCurrentTime());
  298. unis.m_frame = m_frameCount & kMaxU32;
  299. Plane nearPlane;
  300. extractClipPlane(ctx.m_matrices.m_viewProjection, FrustumPlaneType::kNear, nearPlane);
  301. unis.m_nearPlaneWSpace = Vec4(nearPlane.getNormal().xyz(), nearPlane.getOffset());
  302. unis.m_near = ctx.m_cameraNear;
  303. unis.m_far = ctx.m_cameraFar;
  304. unis.m_cameraPosition = ctx.m_matrices.m_cameraTransform.getTranslationPart().xyz();
  305. unis.m_tileCounts = m_tileCounts;
  306. unis.m_zSplitCount = m_zSplitCount;
  307. unis.m_zSplitCountOverFrustumLength = F32(m_zSplitCount) / (ctx.m_cameraFar - ctx.m_cameraNear);
  308. unis.m_zSplitMagic.x() = (ctx.m_cameraNear - ctx.m_cameraFar) / (ctx.m_cameraNear * F32(m_zSplitCount));
  309. unis.m_zSplitMagic.y() = ctx.m_cameraFar / (ctx.m_cameraNear * F32(m_zSplitCount));
  310. unis.m_lightVolumeLastZSplit = min(g_volumetricLightingAccumulationFinalZSplitCVar.get() - 1, m_zSplitCount);
  311. unis.m_reflectionProbesMipCount = F32(m_probeReflections->getReflectionTextureMipmapCount());
  312. unis.m_matrices = ctx.m_matrices;
  313. unis.m_previousMatrices = ctx.m_prevMatrices;
  314. // Directional light
  315. const LightComponent* dirLight = SceneGraph::getSingleton().getDirectionalLight();
  316. if(dirLight)
  317. {
  318. DirectionalLight& out = unis.m_directionalLight;
  319. const U32 shadowCascadeCount = (dirLight->getShadowEnabled()) ? g_shadowCascadeCountCVar.get() : 0;
  320. out.m_diffuseColor = dirLight->getDiffuseColor().xyz();
  321. out.m_power = dirLight->getLightPower();
  322. out.m_shadowCascadeCount_31bit_active_1bit = shadowCascadeCount << 1u;
  323. out.m_shadowCascadeCount_31bit_active_1bit |= 1;
  324. out.m_direction = dirLight->getDirection();
  325. out.m_shadowCascadeDistances = Vec4(g_shadowCascade0DistanceCVar.get(), g_shadowCascade1DistanceCVar.get(),
  326. g_shadowCascade2DistanceCVar.get(), g_shadowCascade3DistanceCVar.get());
  327. for(U cascade = 0; cascade < shadowCascadeCount; ++cascade)
  328. {
  329. ANKI_ASSERT(ctx.m_dirLightTextureMatrices[cascade] != Mat4::getZero());
  330. out.m_textureMatrices[cascade] = ctx.m_dirLightTextureMatrices[cascade];
  331. }
  332. }
  333. else
  334. {
  335. unis.m_directionalLight.m_shadowCascadeCount_31bit_active_1bit = 0;
  336. }
  337. }
  338. void Renderer::finalize(const RenderingContext& ctx, Fence* fence)
  339. {
  340. ++m_frameCount;
  341. m_prevMatrices = ctx.m_matrices;
  342. m_readbackManager->endFrame(fence);
  343. }
  344. TextureInitInfo Renderer::create2DRenderTargetInitInfo(U32 w, U32 h, Format format, TextureUsageBit usage, CString name)
  345. {
  346. ANKI_ASSERT(!!(usage & TextureUsageBit::kFramebufferWrite) || !!(usage & TextureUsageBit::kStorageComputeWrite));
  347. TextureInitInfo init(name);
  348. init.m_width = w;
  349. init.m_height = h;
  350. init.m_depth = 1;
  351. init.m_layerCount = 1;
  352. init.m_type = TextureType::k2D;
  353. init.m_format = format;
  354. init.m_mipmapCount = 1;
  355. init.m_samples = 1;
  356. init.m_usage = usage;
  357. return init;
  358. }
  359. RenderTargetDesc Renderer::create2DRenderTargetDescription(U32 w, U32 h, Format format, CString name)
  360. {
  361. RenderTargetDesc init(name);
  362. init.m_width = w;
  363. init.m_height = h;
  364. init.m_depth = 1;
  365. init.m_layerCount = 1;
  366. init.m_type = TextureType::k2D;
  367. init.m_format = format;
  368. init.m_mipmapCount = 1;
  369. init.m_samples = 1;
  370. init.m_usage = TextureUsageBit::kNone;
  371. return init;
  372. }
  373. TexturePtr Renderer::createAndClearRenderTarget(const TextureInitInfo& inf, TextureUsageBit initialUsage, const ClearValue& clearVal)
  374. {
  375. ANKI_ASSERT(!!(inf.m_usage & TextureUsageBit::kFramebufferWrite) || !!(inf.m_usage & TextureUsageBit::kStorageComputeWrite));
  376. const U faceCount = textureTypeIsCube(inf.m_type) ? 6 : 1;
  377. Bool useCompute = false;
  378. if(!!(inf.m_usage & TextureUsageBit::kFramebufferWrite))
  379. {
  380. useCompute = false;
  381. }
  382. else if(!!(inf.m_usage & TextureUsageBit::kStorageComputeWrite))
  383. {
  384. useCompute = true;
  385. }
  386. else
  387. {
  388. ANKI_ASSERT(!"Can't handle that");
  389. }
  390. // Create tex
  391. TexturePtr tex = GrManager::getSingleton().newTexture(inf);
  392. // Clear all surfaces
  393. CommandBufferInitInfo cmdbinit;
  394. cmdbinit.m_flags = CommandBufferFlag::kGeneralWork;
  395. if((inf.m_mipmapCount * faceCount * inf.m_layerCount * 4) < kCommandBufferSmallBatchMaxCommands)
  396. {
  397. cmdbinit.m_flags |= CommandBufferFlag::kSmallBatch;
  398. }
  399. CommandBufferPtr cmdb = GrManager::getSingleton().newCommandBuffer(cmdbinit);
  400. for(U32 mip = 0; mip < inf.m_mipmapCount; ++mip)
  401. {
  402. for(U32 face = 0; face < faceCount; ++face)
  403. {
  404. for(U32 layer = 0; layer < inf.m_layerCount; ++layer)
  405. {
  406. if(!useCompute)
  407. {
  408. RenderTarget rt;
  409. rt.m_clearValue = clearVal;
  410. if(getFormatInfo(inf.m_format).isDepthStencil())
  411. {
  412. DepthStencilAspectBit aspect = DepthStencilAspectBit::kNone;
  413. if(getFormatInfo(inf.m_format).isDepth())
  414. {
  415. aspect |= DepthStencilAspectBit::kDepth;
  416. }
  417. if(getFormatInfo(inf.m_format).isStencil())
  418. {
  419. aspect |= DepthStencilAspectBit::kStencil;
  420. }
  421. rt.m_textureView = TextureView(tex.get(), TextureSubresourceDesc::surface(mip, face, layer, aspect));
  422. }
  423. else
  424. {
  425. rt.m_textureView = TextureView(tex.get(), TextureSubresourceDesc::surface(mip, face, layer));
  426. }
  427. TextureBarrierInfo barrier = {rt.m_textureView, TextureUsageBit::kNone, TextureUsageBit::kFramebufferWrite};
  428. cmdb->setPipelineBarrier({&barrier, 1}, {}, {});
  429. if(getFormatInfo(inf.m_format).isDepthStencil())
  430. {
  431. cmdb->beginRenderPass({}, &rt);
  432. }
  433. else
  434. {
  435. cmdb->beginRenderPass({rt});
  436. }
  437. cmdb->endRenderPass();
  438. if(!!initialUsage)
  439. {
  440. barrier.m_previousUsage = TextureUsageBit::kFramebufferWrite;
  441. barrier.m_nextUsage = initialUsage;
  442. cmdb->setPipelineBarrier({&barrier, 1}, {}, {});
  443. }
  444. }
  445. else
  446. {
  447. // Compute
  448. ShaderProgramResourceVariantInitInfo variantInitInfo(m_clearTexComputeProg);
  449. variantInitInfo.addMutation("TEXTURE_DIMENSIONS", I32((inf.m_type == TextureType::k3D) ? 3 : 2));
  450. const FormatInfo formatInfo = getFormatInfo(inf.m_format);
  451. I32 componentType = 0;
  452. if(formatInfo.m_shaderType == 0)
  453. {
  454. componentType = 0;
  455. }
  456. else if(formatInfo.m_shaderType == 1)
  457. {
  458. componentType = 1;
  459. }
  460. else
  461. {
  462. ANKI_ASSERT(!"Not supported");
  463. }
  464. variantInitInfo.addMutation("COMPONENT_TYPE", componentType);
  465. const ShaderProgramResourceVariant* variant;
  466. m_clearTexComputeProg->getOrCreateVariant(variantInitInfo, variant);
  467. cmdb->bindShaderProgram(&variant->getProgram());
  468. cmdb->setPushConstants(&clearVal.m_colorf[0], sizeof(clearVal.m_colorf));
  469. const TextureView view(tex.get(), TextureSubresourceDesc::surface(mip, face, layer));
  470. cmdb->bindTexture(ANKI_REG(u0), view);
  471. const TextureBarrierInfo barrier = {view, TextureUsageBit::kNone, TextureUsageBit::kStorageComputeWrite};
  472. cmdb->setPipelineBarrier({&barrier, 1}, {}, {});
  473. UVec3 wgSize;
  474. wgSize.x() = (8 - 1 + (tex->getWidth() >> mip)) / 8;
  475. wgSize.y() = (8 - 1 + (tex->getHeight() >> mip)) / 8;
  476. wgSize.z() = (inf.m_type == TextureType::k3D) ? ((8 - 1 + (tex->getDepth() >> mip)) / 8) : 1;
  477. cmdb->dispatchCompute(wgSize.x(), wgSize.y(), wgSize.z());
  478. if(!!initialUsage)
  479. {
  480. const TextureBarrierInfo barrier = {view, TextureUsageBit::kStorageComputeWrite, initialUsage};
  481. cmdb->setPipelineBarrier({&barrier, 1}, {}, {});
  482. }
  483. }
  484. }
  485. }
  486. }
  487. cmdb->endRecording();
  488. FencePtr fence;
  489. GrManager::getSingleton().submit(cmdb.get(), {}, &fence);
  490. fence->clientWait(10.0_sec);
  491. return tex;
  492. }
  493. void Renderer::registerDebugRenderTarget(RendererObject* obj, CString rtName)
  494. {
  495. #if ANKI_ASSERTIONS_ENABLED
  496. for(const DebugRtInfo& inf : m_debugRts)
  497. {
  498. ANKI_ASSERT(inf.m_rtName != rtName && "Choose different name");
  499. }
  500. #endif
  501. ANKI_ASSERT(obj);
  502. DebugRtInfo inf;
  503. inf.m_obj = obj;
  504. inf.m_rtName = rtName;
  505. m_debugRts.emplaceBack(std::move(inf));
  506. }
  507. Bool Renderer::getCurrentDebugRenderTarget(Array<RenderTargetHandle, kMaxDebugRenderTargets>& handles, ShaderProgramPtr& optionalShaderProgram)
  508. {
  509. if(m_currentDebugRtName.isEmpty()) [[likely]]
  510. {
  511. return false;
  512. }
  513. RendererObject* obj = nullptr;
  514. for(const DebugRtInfo& inf : m_debugRts)
  515. {
  516. if(inf.m_rtName == m_currentDebugRtName)
  517. {
  518. obj = inf.m_obj;
  519. }
  520. }
  521. if(obj)
  522. {
  523. obj->getDebugRenderTarget(m_currentDebugRtName, handles, optionalShaderProgram);
  524. return true;
  525. }
  526. else
  527. {
  528. ANKI_R_LOGE("Debug rendertarget doesn't exist: %s", m_currentDebugRtName.cstr());
  529. m_currentDebugRtName = {};
  530. return false;
  531. }
  532. }
  533. void Renderer::setCurrentDebugRenderTarget(CString rtName)
  534. {
  535. m_currentDebugRtName.destroy();
  536. if(!rtName.isEmpty() && rtName.getLength() > 0)
  537. {
  538. m_currentDebugRtName = rtName;
  539. }
  540. }
  541. Format Renderer::getHdrFormat() const
  542. {
  543. Format out;
  544. if(!g_highQualityHdrCVar.get())
  545. {
  546. out = Format::kB10G11R11_Ufloat_Pack32;
  547. }
  548. else if(GrManager::getSingleton().getDeviceCapabilities().m_unalignedBbpTextureFormats)
  549. {
  550. out = Format::kR16G16B16_Sfloat;
  551. }
  552. else
  553. {
  554. out = Format::kR16G16B16A16_Sfloat;
  555. }
  556. return out;
  557. }
  558. Format Renderer::getDepthNoStencilFormat() const
  559. {
  560. if(ANKI_PLATFORM_MOBILE)
  561. {
  562. return Format::kX8D24_Unorm_Pack32;
  563. }
  564. else
  565. {
  566. return Format::kD32_Sfloat;
  567. }
  568. }
  569. void Renderer::gpuSceneCopy(RenderingContext& ctx)
  570. {
  571. RenderGraphBuilder& rgraph = ctx.m_renderGraphDescr;
  572. m_runCtx.m_gpuSceneHandle =
  573. rgraph.importBuffer(GpuSceneBuffer::getSingleton().getBufferView(), GpuSceneBuffer::getSingleton().getBuffer().getBufferUsage());
  574. if(GpuSceneMicroPatcher::getSingleton().patchingIsNeeded())
  575. {
  576. NonGraphicsRenderPass& rpass = rgraph.newNonGraphicsRenderPass("GPU scene patching");
  577. rpass.newBufferDependency(m_runCtx.m_gpuSceneHandle, BufferUsageBit::kStorageComputeWrite);
  578. rpass.setWork([](RenderPassWorkContext& rgraphCtx) {
  579. GpuSceneMicroPatcher::getSingleton().patchGpuScene(*rgraphCtx.m_commandBuffer);
  580. });
  581. }
  582. }
  583. #if ANKI_STATS_ENABLED
  584. void Renderer::updatePipelineStats()
  585. {
  586. RendererDynamicArray<PipelineQueryPtr>& arr = m_pipelineQueries[m_frameCount % kMaxFramesInFlight];
  587. U64 sum = 0;
  588. for(PipelineQueryPtr& q : arr)
  589. {
  590. U64 value;
  591. const PipelineQueryResult res = q->getResult(value);
  592. if(res == PipelineQueryResult::kNotAvailable)
  593. {
  594. ANKI_R_LOGW("Pipeline query result is not available");
  595. }
  596. else
  597. {
  598. sum += value;
  599. }
  600. }
  601. arr.destroy();
  602. g_primitivesDrawnStatVar.set(sum);
  603. }
  604. #endif
  605. } // end namespace anki