ModelComponent.cpp 16 KB

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