ModelComponent.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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, getStaticClassId())
  16. , m_node(node)
  17. , m_spatial(this)
  18. {
  19. m_gpuSceneTransforms.allocate();
  20. }
  21. ModelComponent::~ModelComponent()
  22. {
  23. m_spatial.removeFromOctree(SceneGraph::getSingleton().getOctree());
  24. }
  25. void ModelComponent::freeGpuScene()
  26. {
  27. GpuSceneBuffer::getSingleton().deferredFree(m_gpuSceneUniforms);
  28. for(PatchInfo& patch : m_patchInfos)
  29. {
  30. patch.m_gpuSceneMeshLods.free();
  31. patch.m_gpuSceneRenderable.free();
  32. patch.m_gpuSceneRenderableAabbDepth.free();
  33. patch.m_gpuSceneRenderableAabbForward.free();
  34. patch.m_gpuSceneRenderableAabbGBuffer.free();
  35. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  36. {
  37. RenderStateBucketContainer::getSingleton().removeUser(patch.m_renderStateBucketIndices[t]);
  38. }
  39. }
  40. }
  41. void ModelComponent::loadModelResource(CString filename)
  42. {
  43. ModelResourcePtr rsrc;
  44. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  45. if(err)
  46. {
  47. ANKI_SCENE_LOGE("Failed to load model resource");
  48. return;
  49. }
  50. m_resourceChanged = true;
  51. m_model = std::move(rsrc);
  52. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  53. // Init
  54. freeGpuScene();
  55. m_patchInfos.resize(modelPatchCount);
  56. m_presentRenderingTechniques = RenderingTechniqueBit::kNone;
  57. // Allocate all uniforms so you can make one allocation
  58. U32 uniformsSize = 0;
  59. for(U32 i = 0; i < modelPatchCount; ++i)
  60. {
  61. const U32 size = U32(m_model->getModelPatches()[i].getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  62. ANKI_ASSERT((size % 4) == 0);
  63. uniformsSize += size;
  64. }
  65. GpuSceneBuffer::getSingleton().allocate(uniformsSize, 4, m_gpuSceneUniforms);
  66. uniformsSize = 0;
  67. // Init the patches
  68. for(U32 i = 0; i < modelPatchCount; ++i)
  69. {
  70. PatchInfo& out = m_patchInfos[i];
  71. const ModelPatch& in = m_model->getModelPatches()[i];
  72. out.m_techniques = in.getMaterial()->getRenderingTechniques();
  73. m_castsShadow = m_castsShadow || in.getMaterial()->castsShadow();
  74. m_presentRenderingTechniques |= in.getMaterial()->getRenderingTechniques();
  75. out.m_gpuSceneUniformsOffset = m_gpuSceneUniforms.getOffset() + uniformsSize;
  76. uniformsSize += U32(in.getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  77. out.m_gpuSceneMeshLods.allocate();
  78. out.m_gpuSceneRenderable.allocate();
  79. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  80. {
  81. if(!(RenderingTechniqueBit(1 << t) & out.m_techniques) || !!(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt))
  82. {
  83. continue;
  84. }
  85. switch(t)
  86. {
  87. case RenderingTechnique::kGBuffer:
  88. out.m_gpuSceneRenderableAabbGBuffer.allocate();
  89. break;
  90. case RenderingTechnique::kForward:
  91. out.m_gpuSceneRenderableAabbForward.allocate();
  92. break;
  93. case RenderingTechnique::kDepth:
  94. out.m_gpuSceneRenderableAabbDepth.allocate();
  95. break;
  96. default:
  97. ANKI_ASSERT(0);
  98. }
  99. }
  100. }
  101. }
  102. Error ModelComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  103. {
  104. if(!isEnabled()) [[unlikely]]
  105. {
  106. updated = false;
  107. return Error::kNone;
  108. }
  109. const Bool resourceUpdated = m_resourceChanged;
  110. m_resourceChanged = false;
  111. const Bool moved = info.m_node->movedThisFrame() || m_firstTimeUpdate;
  112. const Bool movedLastFrame = m_movedLastFrame || m_firstTimeUpdate;
  113. m_firstTimeUpdate = false;
  114. m_movedLastFrame = moved;
  115. const Bool hasSkin = m_skinComponent != nullptr && m_skinComponent->isEnabled();
  116. updated = resourceUpdated || moved || movedLastFrame;
  117. // Upload GpuSceneMeshLod, uniforms and GpuSceneRenderable
  118. if(resourceUpdated) [[unlikely]]
  119. {
  120. // Upload the mesh views
  121. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  122. for(U32 i = 0; i < modelPatchCount; ++i)
  123. {
  124. const ModelPatch& patch = m_model->getModelPatches()[i];
  125. const MeshResource& mesh = *patch.getMesh();
  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_indexBufferOffset % getIndexSize(inf.m_indexType)) == 0);
  136. meshLod.m_firstIndex = U32(inf.m_indexBufferOffset / 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_vertexBufferOffsets[stream] % elementSize) == 0);
  144. meshLod.m_vertexOffsets[U32(stream)] = U32(inf.m_vertexBufferOffsets[stream] / elementSize);
  145. }
  146. else
  147. {
  148. meshLod.m_vertexOffsets[U32(stream)] = kMaxU32;
  149. }
  150. }
  151. }
  152. // Copy the last LOD to the rest just in case
  153. for(U32 l = mesh.getLodCount(); l < kMaxLodCount; ++l)
  154. {
  155. meshLods[l] = meshLods[l - 1];
  156. }
  157. m_patchInfos[i].m_gpuSceneMeshLods.uploadToGpuScene(meshLods);
  158. // Upload the GpuSceneRenderable
  159. GpuSceneRenderable gpuRenderable;
  160. gpuRenderable.m_worldTransformsOffset = m_gpuSceneTransforms.getGpuSceneOffset();
  161. gpuRenderable.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  162. gpuRenderable.m_geometryOffset = m_patchInfos[i].m_gpuSceneMeshLods.getGpuSceneOffset();
  163. gpuRenderable.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  164. m_patchInfos[i].m_gpuSceneRenderable.uploadToGpuScene(gpuRenderable);
  165. }
  166. // Upload the uniforms
  167. DynamicArray<U32, MemoryPoolPtrWrapper<StackMemoryPool>> allUniforms(info.m_framePool);
  168. allUniforms.resize(m_gpuSceneUniforms.getAllocatedSize() / 4);
  169. U32 count = 0;
  170. for(U32 i = 0; i < modelPatchCount; ++i)
  171. {
  172. const ModelPatch& patch = m_model->getModelPatches()[i];
  173. const MaterialResource& mtl = *patch.getMaterial();
  174. memcpy(&allUniforms[count], mtl.getPrefilledLocalUniforms().getBegin(), mtl.getPrefilledLocalUniforms().getSizeInBytes());
  175. count += U32(mtl.getPrefilledLocalUniforms().getSizeInBytes() / 4);
  176. }
  177. ANKI_ASSERT(count * 4 == m_gpuSceneUniforms.getAllocatedSize());
  178. GpuSceneMicroPatcher::getSingleton().newCopy(*info.m_framePool, m_gpuSceneUniforms.getOffset(), m_gpuSceneUniforms.getAllocatedSize(),
  179. &allUniforms[0]);
  180. }
  181. // Upload transforms
  182. if(moved || movedLastFrame) [[unlikely]]
  183. {
  184. Array<Mat3x4, 2> trfs;
  185. trfs[0] = Mat3x4(info.m_node->getWorldTransform());
  186. trfs[1] = Mat3x4(info.m_node->getPreviousWorldTransform());
  187. m_gpuSceneTransforms.uploadToGpuScene(trfs);
  188. }
  189. // Spatial update
  190. const Bool spatialNeedsUpdate = moved || resourceUpdated || m_skinComponent;
  191. if(spatialNeedsUpdate) [[unlikely]]
  192. {
  193. Aabb aabbLocal;
  194. if(m_skinComponent == nullptr) [[likely]]
  195. {
  196. aabbLocal = m_model->getBoundingVolume();
  197. }
  198. else
  199. {
  200. aabbLocal = m_skinComponent->getBoneBoundingVolumeLocalSpace().getCompoundShape(m_model->getBoundingVolume());
  201. }
  202. const Aabb aabbWorld = aabbLocal.getTransformed(info.m_node->getWorldTransform());
  203. m_spatial.setBoundingShape(aabbWorld);
  204. }
  205. const Bool spatialUpdated = m_spatial.update(SceneGraph::getSingleton().getOctree());
  206. updated = updated || spatialUpdated;
  207. // Update the buckets
  208. const Bool bucketsNeedUpdate = resourceUpdated || moved != movedLastFrame;
  209. if(bucketsNeedUpdate)
  210. {
  211. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  212. for(U32 i = 0; i < modelPatchCount; ++i)
  213. {
  214. // Refresh the render state buckets
  215. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  216. {
  217. RenderStateBucketContainer::getSingleton().removeUser(m_patchInfos[i].m_renderStateBucketIndices[t]);
  218. if(!(RenderingTechniqueBit(1 << t) & m_patchInfos[i].m_techniques))
  219. {
  220. continue;
  221. }
  222. // Fill the state
  223. RenderingKey key;
  224. key.setLod(0); // Materials don't care
  225. key.setRenderingTechnique(t);
  226. key.setSkinned(hasSkin);
  227. key.setVelocity(moved);
  228. const MaterialVariant& mvariant = m_model->getModelPatches()[i].getMaterial()->getOrCreateVariant(key);
  229. RenderStateInfo state;
  230. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  231. state.m_indexedDrawcall = true;
  232. state.m_program = mvariant.getShaderProgram();
  233. m_patchInfos[i].m_renderStateBucketIndices[t] = RenderStateBucketContainer::getSingleton().addUser(state, t);
  234. }
  235. }
  236. }
  237. // Upload the AABBs to the GPU scene
  238. const Bool gpuSceneAabbsNeedUpdate = spatialNeedsUpdate || bucketsNeedUpdate;
  239. if(gpuSceneAabbsNeedUpdate)
  240. {
  241. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  242. for(U32 i = 0; i < modelPatchCount; ++i)
  243. {
  244. for(RenderingTechnique t :
  245. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_patchInfos[i].m_techniques & ~RenderingTechniqueBit::kAllRt))
  246. {
  247. const Vec3 aabbMin = m_spatial.getAabbWorldSpace().getMin().xyz();
  248. const Vec3 aabbMax = m_spatial.getAabbWorldSpace().getMax().xyz();
  249. const GpuSceneRenderableAabb gpuVolume = initGpuSceneRenderableAabb(aabbMin, aabbMax, m_patchInfos[i].m_gpuSceneRenderable.getIndex(),
  250. m_patchInfos[i].m_renderStateBucketIndices[t].get());
  251. switch(t)
  252. {
  253. case RenderingTechnique::kGBuffer:
  254. m_patchInfos[i].m_gpuSceneRenderableAabbGBuffer.uploadToGpuScene(gpuVolume);
  255. break;
  256. case RenderingTechnique::kDepth:
  257. m_patchInfos[i].m_gpuSceneRenderableAabbDepth.uploadToGpuScene(gpuVolume);
  258. break;
  259. case RenderingTechnique::kForward:
  260. m_patchInfos[i].m_gpuSceneRenderableAabbForward.uploadToGpuScene(gpuVolume);
  261. break;
  262. default:
  263. ANKI_ASSERT(0);
  264. }
  265. }
  266. }
  267. }
  268. return Error::kNone;
  269. }
  270. void ModelComponent::setupRenderableQueueElements(U32 lod, RenderingTechnique technique, WeakArray<RenderableQueueElement>& outRenderables) const
  271. {
  272. ANKI_ASSERT(isEnabled());
  273. outRenderables.setArray(nullptr, 0);
  274. const RenderingTechniqueBit requestedRenderingTechniqueMask = RenderingTechniqueBit(1 << technique);
  275. if(!(m_presentRenderingTechniques & requestedRenderingTechniqueMask))
  276. {
  277. return;
  278. }
  279. // Allocate renderables
  280. U32 renderableCount = 0;
  281. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  282. {
  283. renderableCount += !!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask);
  284. }
  285. if(renderableCount == 0)
  286. {
  287. return;
  288. }
  289. RenderableQueueElement* renderables = static_cast<RenderableQueueElement*>(
  290. SceneGraph::getSingleton().getFrameMemoryPool().allocate(sizeof(RenderableQueueElement) * renderableCount, alignof(RenderableQueueElement)));
  291. outRenderables.setArray(renderables, renderableCount);
  292. // Fill renderables
  293. const Bool moved = m_node->movedThisFrame() && technique == RenderingTechnique::kGBuffer;
  294. const Bool hasSkin = m_skinComponent != nullptr && m_skinComponent->isEnabled();
  295. RenderingKey key;
  296. key.setLod(lod);
  297. key.setRenderingTechnique(technique);
  298. key.setVelocity(moved);
  299. key.setSkinned(hasSkin);
  300. renderableCount = 0;
  301. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  302. {
  303. if(!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask))
  304. {
  305. continue;
  306. }
  307. RenderableQueueElement& queueElem = renderables[renderableCount];
  308. const ModelPatch& patch = m_model->getModelPatches()[i];
  309. ModelRenderingInfo modelInf;
  310. patch.getRenderingInfo(key, modelInf);
  311. queueElem.m_program = modelInf.m_program.get();
  312. queueElem.m_worldTransformsOffset = m_gpuSceneTransforms.getGpuSceneOffset();
  313. queueElem.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  314. queueElem.m_geometryOffset = m_patchInfos[i].m_gpuSceneMeshLods.getGpuSceneOffset() + lod * sizeof(GpuSceneMeshLod);
  315. queueElem.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  316. queueElem.m_indexCount = modelInf.m_indexCount;
  317. queueElem.m_firstIndex = U32(modelInf.m_indexBufferOffset / 2 + modelInf.m_firstIndex);
  318. queueElem.m_indexed = true;
  319. queueElem.m_primitiveTopology = PrimitiveTopology::kTriangles;
  320. queueElem.m_aabbMin = m_spatial.getAabbWorldSpace().getMin().xyz();
  321. queueElem.m_aabbMax = m_spatial.getAabbWorldSpace().getMax().xyz();
  322. queueElem.computeMergeKey();
  323. ++renderableCount;
  324. }
  325. }
  326. void ModelComponent::setupRayTracingInstanceQueueElements(U32 lod, RenderingTechnique technique,
  327. WeakArray<RayTracingInstanceQueueElement>& outInstances) const
  328. {
  329. ANKI_ASSERT(isEnabled());
  330. outInstances.setArray(nullptr, 0);
  331. const RenderingTechniqueBit requestedRenderingTechniqueMask = RenderingTechniqueBit(1 << technique);
  332. if(!(m_presentRenderingTechniques & requestedRenderingTechniqueMask))
  333. {
  334. return;
  335. }
  336. // Allocate instances
  337. U32 instanceCount = 0;
  338. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  339. {
  340. instanceCount += !!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask);
  341. }
  342. if(instanceCount == 0)
  343. {
  344. return;
  345. }
  346. RayTracingInstanceQueueElement* instances = static_cast<RayTracingInstanceQueueElement*>(SceneGraph::getSingleton().getFrameMemoryPool().allocate(
  347. sizeof(RayTracingInstanceQueueElement) * instanceCount, alignof(RayTracingInstanceQueueElement)));
  348. outInstances.setArray(instances, instanceCount);
  349. RenderingKey key;
  350. key.setLod(lod);
  351. key.setRenderingTechnique(technique);
  352. instanceCount = 0;
  353. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  354. {
  355. if(!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask))
  356. {
  357. continue;
  358. }
  359. RayTracingInstanceQueueElement& queueElem = instances[instanceCount];
  360. const ModelPatch& patch = m_model->getModelPatches()[i];
  361. ModelRayTracingInfo modelInf;
  362. patch.getRayTracingInfo(key, modelInf);
  363. queueElem.m_bottomLevelAccelerationStructure = modelInf.m_bottomLevelAccelerationStructure.get();
  364. queueElem.m_shaderGroupHandleIndex = modelInf.m_shaderGroupHandleIndex;
  365. queueElem.m_worldTransformsOffset = m_gpuSceneTransforms.getGpuSceneOffset();
  366. queueElem.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  367. queueElem.m_geometryOffset =
  368. U32(m_patchInfos[i].m_gpuSceneMeshLods.getIndex() * sizeof(GpuSceneMeshLod) * kMaxLodCount + lod * sizeof(GpuSceneMeshLod));
  369. queueElem.m_geometryOffset += U32(GpuSceneArrays::MeshLod::getSingleton().getGpuSceneOffsetOfArrayBase());
  370. queueElem.m_indexBufferOffset = U32(modelInf.m_indexBufferOffset);
  371. const Transform positionTransform(patch.getMesh()->getPositionsTranslation().xyz0(), Mat3x4::getIdentity(),
  372. patch.getMesh()->getPositionsScale());
  373. queueElem.m_transform = Mat3x4(m_node->getWorldTransform()).combineTransformations(Mat3x4(positionTransform));
  374. ++instanceCount;
  375. }
  376. }
  377. void ModelComponent::onOtherComponentRemovedOrAdded(SceneComponent* other, Bool added)
  378. {
  379. ANKI_ASSERT(other);
  380. if(other->getClassId() != SkinComponent::getStaticClassId())
  381. {
  382. return;
  383. }
  384. const Bool alreadyHasSkinComponent = m_skinComponent != nullptr;
  385. if(added && !alreadyHasSkinComponent)
  386. {
  387. m_skinComponent = static_cast<SkinComponent*>(other);
  388. m_resourceChanged = true;
  389. }
  390. else if(!added && other == m_skinComponent)
  391. {
  392. m_skinComponent = nullptr;
  393. m_resourceChanged = true;
  394. }
  395. }
  396. } // end namespace anki