ModelComponent.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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/Scene/Components/ModelComponent.h>
  6. #include <AnKi/Scene/SceneNode.h>
  7. #include <AnKi/Scene/SceneGraph.h>
  8. #include <AnKi/Scene/Components/MoveComponent.h>
  9. #include <AnKi/Scene/Components/SkinComponent.h>
  10. #include <AnKi/Resource/ModelResource.h>
  11. #include <AnKi/Resource/ResourceManager.h>
  12. #include <AnKi/Shaders/Include/GpuSceneFunctions.h>
  13. #include <AnKi/Core/App.h>
  14. namespace anki {
  15. ModelComponent::ModelComponent(SceneNode* node)
  16. : SceneComponent(node, kClassType)
  17. {
  18. m_gpuSceneTransforms.allocate();
  19. }
  20. ModelComponent::~ModelComponent()
  21. {
  22. }
  23. void ModelComponent::freeGpuScene()
  24. {
  25. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneConstants);
  26. for(PatchInfo& patch : m_patchInfos)
  27. {
  28. patch.m_gpuSceneMeshLods.free();
  29. patch.m_gpuSceneRenderable.free();
  30. patch.m_gpuSceneRenderableAabbDepth.free();
  31. patch.m_gpuSceneRenderableAabbForward.free();
  32. patch.m_gpuSceneRenderableAabbGBuffer.free();
  33. patch.m_gpuSceneRenderableAabbRt.free();
  34. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  35. {
  36. RenderStateBucketContainer::getSingleton().removeUser(patch.m_renderStateBucketIndices[t]);
  37. }
  38. }
  39. }
  40. void ModelComponent::loadModelResource(CString filename)
  41. {
  42. ModelResourcePtr rsrc;
  43. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  44. if(err)
  45. {
  46. ANKI_SCENE_LOGE("Failed to load model resource");
  47. return;
  48. }
  49. m_resourceChanged = true;
  50. m_model = std::move(rsrc);
  51. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  52. // Init
  53. freeGpuScene();
  54. m_patchInfos.resize(modelPatchCount);
  55. m_presentRenderingTechniques = RenderingTechniqueBit::kNone;
  56. // Allocate all uniforms so you can make one allocation
  57. U32 uniformsSize = 0;
  58. for(U32 i = 0; i < modelPatchCount; ++i)
  59. {
  60. const U32 size = U32(m_model->getModelPatches()[i].getMaterial()->getPrefilledLocalConstants().getSizeInBytes());
  61. ANKI_ASSERT((size % 4) == 0);
  62. uniformsSize += size;
  63. }
  64. m_gpuSceneConstants = GpuSceneBuffer::getSingleton().allocate(uniformsSize, 4);
  65. uniformsSize = 0;
  66. // Init the patches
  67. for(U32 i = 0; i < modelPatchCount; ++i)
  68. {
  69. PatchInfo& out = m_patchInfos[i];
  70. const ModelPatch& in = m_model->getModelPatches()[i];
  71. out.m_techniques = in.getMaterial()->getRenderingTechniques();
  72. m_castsShadow = m_castsShadow || in.getMaterial()->castsShadow();
  73. m_presentRenderingTechniques |= in.getMaterial()->getRenderingTechniques();
  74. out.m_gpuSceneConstantsOffset = m_gpuSceneConstants.getOffset() + uniformsSize;
  75. uniformsSize += U32(in.getMaterial()->getPrefilledLocalConstants().getSizeInBytes());
  76. out.m_gpuSceneMeshLods.allocate();
  77. out.m_gpuSceneRenderable.allocate();
  78. for(RenderingTechnique t : EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(out.m_techniques))
  79. {
  80. switch(t)
  81. {
  82. case RenderingTechnique::kGBuffer:
  83. out.m_gpuSceneRenderableAabbGBuffer.allocate();
  84. break;
  85. case RenderingTechnique::kForward:
  86. out.m_gpuSceneRenderableAabbForward.allocate();
  87. break;
  88. case RenderingTechnique::kDepth:
  89. out.m_gpuSceneRenderableAabbDepth.allocate();
  90. break;
  91. case RenderingTechnique::kRtShadow:
  92. case RenderingTechnique::kRtMaterialFetch:
  93. out.m_gpuSceneRenderableAabbRt.allocate();
  94. break;
  95. default:
  96. ANKI_ASSERT(0);
  97. }
  98. }
  99. }
  100. }
  101. void ModelComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  102. {
  103. if(!isEnabled()) [[unlikely]]
  104. {
  105. updated = false;
  106. return;
  107. }
  108. const Bool resourceUpdated = m_resourceChanged;
  109. m_resourceChanged = false;
  110. const Bool moved = info.m_node->movedThisFrame() || m_firstTimeUpdate;
  111. const Bool movedLastFrame = m_movedLastFrame || m_firstTimeUpdate;
  112. m_firstTimeUpdate = false;
  113. m_movedLastFrame = moved;
  114. const Bool hasSkin = m_skinComponent != nullptr && m_skinComponent->isEnabled();
  115. updated = resourceUpdated || moved || movedLastFrame;
  116. // Upload GpuSceneMeshLod, uniforms and GpuSceneRenderable
  117. if(resourceUpdated) [[unlikely]]
  118. {
  119. // Upload the mesh views
  120. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  121. for(U32 i = 0; i < modelPatchCount; ++i)
  122. {
  123. const ModelPatch& patch = m_model->getModelPatches()[i];
  124. const MeshResource& mesh = *patch.getMesh();
  125. const MaterialResource& mtl = *patch.getMaterial();
  126. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  127. for(U32 l = 0; l < mesh.getLodCount(); ++l)
  128. {
  129. GpuSceneMeshLod& meshLod = meshLods[l];
  130. meshLod = {};
  131. meshLod.m_positionScale = mesh.getPositionsScale();
  132. meshLod.m_positionTranslation = mesh.getPositionsTranslation();
  133. ModelPatchGeometryInfo inf;
  134. patch.getGeometryInfo(l, inf);
  135. ANKI_ASSERT((inf.m_indexUgbOffset % getIndexSize(inf.m_indexType)) == 0);
  136. meshLod.m_firstIndex = U32(inf.m_indexUgbOffset / getIndexSize(inf.m_indexType));
  137. meshLod.m_indexCount = inf.m_indexCount;
  138. for(VertexStreamId stream = VertexStreamId::kMeshRelatedFirst; stream < VertexStreamId::kMeshRelatedCount; ++stream)
  139. {
  140. if(mesh.isVertexStreamPresent(stream))
  141. {
  142. const PtrSize elementSize = getFormatInfo(kMeshRelatedVertexStreamFormats[stream]).m_texelSize;
  143. ANKI_ASSERT((inf.m_vertexUgbOffsets[stream] % elementSize) == 0);
  144. meshLod.m_vertexOffsets[U32(stream)] = U32(inf.m_vertexUgbOffsets[stream] / elementSize);
  145. }
  146. else
  147. {
  148. meshLod.m_vertexOffsets[U32(stream)] = kMaxU32;
  149. }
  150. }
  151. if(inf.m_blas)
  152. {
  153. const U64 address = inf.m_blas->getGpuAddress();
  154. memcpy(&meshLod.m_blasAddress, &address, sizeof(meshLod.m_blasAddress));
  155. meshLod.m_tlasInstanceMask = 0xFFFFFFFF;
  156. }
  157. if(inf.m_meshletCount)
  158. {
  159. ANKI_ASSERT((inf.m_meshletBoundingVolumesUgbOffset % sizeof(MeshletBoundingVolume)) == 0);
  160. meshLod.m_firstMeshletBoundingVolume = U32(inf.m_meshletBoundingVolumesUgbOffset / sizeof(MeshletBoundingVolume));
  161. ANKI_ASSERT((inf.m_meshletGometryDescriptorsUgbOffset % sizeof(MeshletGeometryDescriptor)) == 0);
  162. meshLod.m_firstMeshletGeometryDescriptor = U32(inf.m_meshletGometryDescriptorsUgbOffset / sizeof(MeshletGeometryDescriptor));
  163. meshLod.m_meshletCount = inf.m_meshletCount;
  164. }
  165. meshLod.m_renderableIndex = m_patchInfos[i].m_gpuSceneRenderable.getIndex();
  166. meshLod.m_lod = l;
  167. }
  168. // Copy the last LOD to the rest just in case
  169. for(U32 l = mesh.getLodCount(); l < kMaxLodCount; ++l)
  170. {
  171. meshLods[l] = meshLods[l - 1];
  172. }
  173. m_patchInfos[i].m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  174. // Upload the GpuSceneRenderable
  175. GpuSceneRenderable gpuRenderable = {};
  176. gpuRenderable.m_worldTransformsIndex = m_gpuSceneTransforms.getIndex() * 2;
  177. gpuRenderable.m_constantsOffset = m_patchInfos[i].m_gpuSceneConstantsOffset;
  178. gpuRenderable.m_meshLodsIndex = m_patchInfos[i].m_gpuSceneMeshLods.getIndex() * kMaxLodCount;
  179. gpuRenderable.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  180. gpuRenderable.m_particleEmitterIndex = kMaxU32;
  181. if(!!(mtl.getRenderingTechniques() & RenderingTechniqueBit::kRtShadow))
  182. {
  183. const RenderingKey key(RenderingTechnique::kRtShadow, 0, false, false, false);
  184. const MaterialVariant& variant = mtl.getOrCreateVariant(key);
  185. gpuRenderable.m_rtShadowsShaderHandleIndex = variant.getRtShaderGroupHandleIndex();
  186. }
  187. if(!!(mtl.getRenderingTechniques() & RenderingTechniqueBit::kRtMaterialFetch))
  188. {
  189. const RenderingKey key(RenderingTechnique::kRtMaterialFetch, 0, false, false, false);
  190. const MaterialVariant& variant = mtl.getOrCreateVariant(key);
  191. gpuRenderable.m_rtMaterialFetchShaderHandleIndex = variant.getRtShaderGroupHandleIndex();
  192. }
  193. gpuRenderable.m_uuid = SceneGraph::getSingleton().getNewUuid();
  194. m_patchInfos[i].m_gpuSceneRenderable.uploadToGpuScene(gpuRenderable);
  195. }
  196. // Upload the uniforms
  197. DynamicArray<U32, MemoryPoolPtrWrapper<StackMemoryPool>> allConstants(info.m_framePool);
  198. allConstants.resize(m_gpuSceneConstants.getAllocatedSize() / 4);
  199. U32 count = 0;
  200. for(U32 i = 0; i < modelPatchCount; ++i)
  201. {
  202. const ModelPatch& patch = m_model->getModelPatches()[i];
  203. const MaterialResource& mtl = *patch.getMaterial();
  204. memcpy(&allConstants[count], mtl.getPrefilledLocalConstants().getBegin(), mtl.getPrefilledLocalConstants().getSizeInBytes());
  205. count += U32(mtl.getPrefilledLocalConstants().getSizeInBytes() / 4);
  206. }
  207. ANKI_ASSERT(count * 4 == m_gpuSceneConstants.getAllocatedSize());
  208. GpuSceneMicroPatcher::getSingleton().newCopy(*info.m_framePool, m_gpuSceneConstants.getOffset(), m_gpuSceneConstants.getAllocatedSize(),
  209. &allConstants[0]);
  210. }
  211. // Upload transforms
  212. if(moved || movedLastFrame) [[unlikely]]
  213. {
  214. Array<Mat3x4, 2> trfs;
  215. trfs[0] = Mat3x4(info.m_node->getWorldTransform());
  216. trfs[1] = Mat3x4(info.m_node->getPreviousWorldTransform());
  217. m_gpuSceneTransforms.uploadToGpuScene(trfs);
  218. }
  219. // Scene bounds update
  220. const Bool aabbUpdated = moved || resourceUpdated || m_skinComponent;
  221. if(aabbUpdated) [[unlikely]]
  222. {
  223. const Aabb aabbWorld = computeAabbWorldSpace(info.m_node->getWorldTransform());
  224. SceneGraph::getSingleton().updateSceneBounds(aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz());
  225. }
  226. // Update the buckets
  227. const Bool bucketsNeedUpdate = resourceUpdated || moved != movedLastFrame;
  228. if(bucketsNeedUpdate)
  229. {
  230. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  231. for(U32 i = 0; i < modelPatchCount; ++i)
  232. {
  233. // Refresh the render state buckets
  234. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  235. {
  236. RenderStateBucketContainer::getSingleton().removeUser(m_patchInfos[i].m_renderStateBucketIndices[t]);
  237. if(!(RenderingTechniqueBit(1 << t) & m_patchInfos[i].m_techniques))
  238. {
  239. continue;
  240. }
  241. // Fill the state
  242. RenderingKey key;
  243. key.setLod(0); // Materials don't care
  244. key.setRenderingTechnique(t);
  245. key.setSkinned(hasSkin);
  246. key.setVelocity(moved);
  247. key.setMeshletRendering(GrManager::getSingleton().getDeviceCapabilities().m_meshShaders || g_meshletRenderingCVar);
  248. const MaterialVariant& mvariant = m_model->getModelPatches()[i].getMaterial()->getOrCreateVariant(key);
  249. RenderStateInfo state;
  250. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  251. state.m_indexedDrawcall = true;
  252. state.m_program = mvariant.getShaderProgram();
  253. ModelPatchGeometryInfo inf;
  254. m_model->getModelPatches()[i].getGeometryInfo(0, inf);
  255. const Bool wantsMesletCount = key.getMeshletRendering() && !(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt);
  256. m_patchInfos[i].m_renderStateBucketIndices[t] =
  257. RenderStateBucketContainer::getSingleton().addUser(state, t, (wantsMesletCount) ? inf.m_meshletCount : 0);
  258. }
  259. }
  260. }
  261. // Upload the AABBs to the GPU scene
  262. const Bool gpuSceneAabbsNeedUpdate = aabbUpdated || bucketsNeedUpdate;
  263. if(gpuSceneAabbsNeedUpdate)
  264. {
  265. const Aabb aabbWorld = computeAabbWorldSpace(info.m_node->getWorldTransform());
  266. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  267. for(U32 i = 0; i < modelPatchCount; ++i)
  268. {
  269. // Do raster techniques
  270. for(RenderingTechnique t :
  271. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_patchInfos[i].m_techniques & ~RenderingTechniqueBit::kAllRt))
  272. {
  273. const GpuSceneRenderableBoundingVolume gpuVolume = initGpuSceneRenderableBoundingVolume(
  274. aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(), m_patchInfos[i].m_gpuSceneRenderable.getIndex(),
  275. m_patchInfos[i].m_renderStateBucketIndices[t].get());
  276. switch(t)
  277. {
  278. case RenderingTechnique::kGBuffer:
  279. m_patchInfos[i].m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  280. break;
  281. case RenderingTechnique::kDepth:
  282. m_patchInfos[i].m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  283. break;
  284. case RenderingTechnique::kForward:
  285. m_patchInfos[i].m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  286. break;
  287. default:
  288. ANKI_ASSERT(0);
  289. }
  290. }
  291. // Do RT techniques
  292. if(!!(m_patchInfos[i].m_techniques & RenderingTechniqueBit::kAllRt))
  293. {
  294. const U32 bucket = 0;
  295. const GpuSceneRenderableBoundingVolume gpuVolume = initGpuSceneRenderableBoundingVolume(
  296. aabbWorld.getMin().xyz(), aabbWorld.getMax().xyz(), m_patchInfos[i].m_gpuSceneRenderable.getIndex(), bucket);
  297. m_patchInfos[i].m_gpuSceneRenderableAabbRt.uploadToGpuScene(gpuVolume);
  298. }
  299. }
  300. }
  301. }
  302. void ModelComponent::onOtherComponentRemovedOrAdded(SceneComponent* other, Bool added)
  303. {
  304. ANKI_ASSERT(other);
  305. if(other->getType() != SceneComponentType::kSkin)
  306. {
  307. return;
  308. }
  309. const Bool alreadyHasSkinComponent = m_skinComponent != nullptr;
  310. if(added && !alreadyHasSkinComponent)
  311. {
  312. m_skinComponent = static_cast<SkinComponent*>(other);
  313. m_resourceChanged = true;
  314. }
  315. else if(!added && other == m_skinComponent)
  316. {
  317. m_skinComponent = nullptr;
  318. m_resourceChanged = true;
  319. }
  320. }
  321. Aabb ModelComponent::computeAabbWorldSpace(const Transform& worldTransform) const
  322. {
  323. Aabb aabbLocal;
  324. if(m_skinComponent == nullptr) [[likely]]
  325. {
  326. aabbLocal = m_model->getBoundingVolume();
  327. }
  328. else
  329. {
  330. aabbLocal = m_skinComponent->getBoneBoundingVolumeLocalSpace().getCompoundShape(m_model->getBoundingVolume());
  331. }
  332. return aabbLocal.getTransformed(worldTransform);
  333. }
  334. } // end namespace anki