ModelComponent.cpp 12 KB

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