ModelComponent.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. namespace anki {
  13. ModelComponent::ModelComponent(SceneNode* node)
  14. : SceneComponent(node, getStaticClassId())
  15. , m_node(node)
  16. , m_spatial(this)
  17. {
  18. m_gpuSceneIndexTransforms =
  19. AllGpuSceneContiguousArrays::getSingleton().allocate(GpuSceneContiguousArrayType::kTransformPairs);
  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. AllGpuSceneContiguousArrays& arr = AllGpuSceneContiguousArrays::getSingleton();
  29. for(PatchInfo& patch : m_patchInfos)
  30. {
  31. arr.deferredFree(patch.m_gpuSceneIndexMeshLods);
  32. arr.deferredFree(patch.m_gpuSceneIndexRenderable);
  33. for(GpuSceneContiguousArrayIndex& idx : patch.m_gpuSceneIndexRenderableAabbs)
  34. {
  35. arr.deferredFree(idx);
  36. }
  37. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  38. {
  39. RenderStateBucketContainer::getSingleton().removeUser(patch.m_renderStateBucketIndices[t]);
  40. }
  41. }
  42. }
  43. void ModelComponent::loadModelResource(CString filename)
  44. {
  45. ModelResourcePtr rsrc;
  46. const Error err = ResourceManager::getSingleton().loadResource(filename, rsrc);
  47. if(err)
  48. {
  49. ANKI_SCENE_LOGE("Failed to load model resource");
  50. return;
  51. }
  52. m_resourceChanged = true;
  53. m_model = std::move(rsrc);
  54. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  55. // Init
  56. freeGpuScene();
  57. m_patchInfos.resize(modelPatchCount);
  58. m_presentRenderingTechniques = RenderingTechniqueBit::kNone;
  59. // Allocate all uniforms so you can make one allocation
  60. U32 uniformsSize = 0;
  61. for(U32 i = 0; i < modelPatchCount; ++i)
  62. {
  63. const U32 size = U32(m_model->getModelPatches()[i].getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  64. ANKI_ASSERT((size % 4) == 0);
  65. uniformsSize += size;
  66. }
  67. GpuSceneBuffer::getSingleton().allocate(uniformsSize, 4, m_gpuSceneUniforms);
  68. uniformsSize = 0;
  69. // Init the patches
  70. for(U32 i = 0; i < modelPatchCount; ++i)
  71. {
  72. PatchInfo& out = m_patchInfos[i];
  73. const ModelPatch& in = m_model->getModelPatches()[i];
  74. out.m_techniques = in.getMaterial()->getRenderingTechniques();
  75. m_castsShadow = m_castsShadow || in.getMaterial()->castsShadow();
  76. m_presentRenderingTechniques |= in.getMaterial()->getRenderingTechniques();
  77. out.m_gpuSceneUniformsOffset = m_gpuSceneUniforms.getOffset() + uniformsSize;
  78. uniformsSize += U32(in.getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  79. out.m_gpuSceneIndexMeshLods =
  80. AllGpuSceneContiguousArrays::getSingleton().allocate(GpuSceneContiguousArrayType::kMeshLods);
  81. out.m_gpuSceneIndexRenderable =
  82. AllGpuSceneContiguousArrays::getSingleton().allocate(GpuSceneContiguousArrayType::kRenderables);
  83. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  84. {
  85. if(!(RenderingTechniqueBit(1 << t) & out.m_techniques)
  86. || !!(RenderingTechniqueBit(1 << t) & RenderingTechniqueBit::kAllRt))
  87. {
  88. continue;
  89. }
  90. GpuSceneContiguousArrayType allocType = GpuSceneContiguousArrayType::kCount;
  91. switch(t)
  92. {
  93. case RenderingTechnique::kGBuffer:
  94. allocType = GpuSceneContiguousArrayType::kRenderableBoundingVolumesGBuffer;
  95. break;
  96. case RenderingTechnique::kForward:
  97. allocType = GpuSceneContiguousArrayType::kRenderableBoundingVolumesForward;
  98. break;
  99. case RenderingTechnique::kDepth:
  100. allocType = GpuSceneContiguousArrayType::kRenderableBoundingVolumesDepth;
  101. break;
  102. default:
  103. ANKI_ASSERT(0);
  104. }
  105. out.m_gpuSceneIndexRenderableAabbs[t] = AllGpuSceneContiguousArrays::getSingleton().allocate(allocType);
  106. }
  107. }
  108. }
  109. Error ModelComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  110. {
  111. if(!isEnabled()) [[unlikely]]
  112. {
  113. updated = false;
  114. return Error::kNone;
  115. }
  116. const Bool resourceUpdated = m_resourceChanged;
  117. m_resourceChanged = false;
  118. const Bool moved = info.m_node->movedThisFrame() || m_firstTimeUpdate;
  119. const Bool movedLastFrame = m_movedLastFrame || m_firstTimeUpdate;
  120. m_firstTimeUpdate = false;
  121. m_movedLastFrame = moved;
  122. const Bool hasSkin = m_skinComponent != nullptr && m_skinComponent->isEnabled();
  123. updated = resourceUpdated || moved || movedLastFrame;
  124. // Upload GpuSceneMeshLod, uniforms and GpuSceneRenderable
  125. if(resourceUpdated) [[unlikely]]
  126. {
  127. // Upload the mesh views
  128. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  129. for(U32 i = 0; i < modelPatchCount; ++i)
  130. {
  131. const ModelPatch& patch = m_model->getModelPatches()[i];
  132. const MeshResource& mesh = *patch.getMesh();
  133. Array<GpuSceneMeshLod, kMaxLodCount> meshLods;
  134. for(U32 l = 0; l < mesh.getLodCount(); ++l)
  135. {
  136. GpuSceneMeshLod& meshLod = meshLods[l];
  137. meshLod = {};
  138. meshLod.m_positionScale = mesh.getPositionsScale();
  139. meshLod.m_positionTranslation = mesh.getPositionsTranslation();
  140. for(VertexStreamId stream = VertexStreamId::kPosition; stream <= VertexStreamId::kBoneWeights; ++stream)
  141. {
  142. if(!mesh.isVertexStreamPresent(stream))
  143. {
  144. continue;
  145. }
  146. PtrSize offset;
  147. U32 vertCount;
  148. mesh.getVertexStreamInfo(l, stream, offset, vertCount);
  149. const PtrSize elementSize = getFormatInfo(kMeshRelatedVertexStreamFormats[stream]).m_texelSize;
  150. ANKI_ASSERT((offset % elementSize) == 0);
  151. meshLod.m_vertexOffsets[U32(stream)] = U32(offset / elementSize);
  152. }
  153. U32 firstIndex;
  154. U32 indexCount;
  155. Aabb aabb;
  156. mesh.getSubMeshInfo(l, i, firstIndex, indexCount, aabb);
  157. PtrSize offset;
  158. IndexType indexType;
  159. mesh.getIndexBufferInfo(l, offset, indexCount, indexType);
  160. meshLod.m_indexBufferOffset = U32(offset) / getIndexSize(indexType) + firstIndex;
  161. meshLod.m_indexCount = indexCount;
  162. }
  163. // Copy the last LOD to the rest just in case
  164. for(U32 l = mesh.getLodCount(); l < kMaxLodCount; ++l)
  165. {
  166. meshLods[l] = meshLods[l - 1];
  167. }
  168. GpuSceneMicroPatcher::getSingleton().newCopy(
  169. *info.m_framePool, m_patchInfos[i].m_gpuSceneIndexMeshLods.getOffsetInGpuScene(), meshLods);
  170. // Upload the GpuSceneRenderable
  171. GpuSceneRenderable gpuRenderable;
  172. gpuRenderable.m_worldTransformsOffset = m_gpuSceneIndexTransforms.getOffsetInGpuScene();
  173. gpuRenderable.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  174. gpuRenderable.m_geometryOffset = m_patchInfos[i].m_gpuSceneIndexMeshLods.getOffsetInGpuScene();
  175. gpuRenderable.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  176. GpuSceneMicroPatcher::getSingleton().newCopy(
  177. *info.m_framePool, m_patchInfos[i].m_gpuSceneIndexRenderable.getOffsetInGpuScene(), gpuRenderable);
  178. }
  179. // Upload the uniforms
  180. DynamicArray<U32, MemoryPoolPtrWrapper<StackMemoryPool>> allUniforms(info.m_framePool);
  181. allUniforms.resize(m_gpuSceneUniforms.getAllocatedSize() / 4);
  182. U32 count = 0;
  183. for(U32 i = 0; i < modelPatchCount; ++i)
  184. {
  185. const ModelPatch& patch = m_model->getModelPatches()[i];
  186. const MaterialResource& mtl = *patch.getMaterial();
  187. memcpy(&allUniforms[count], mtl.getPrefilledLocalUniforms().getBegin(),
  188. mtl.getPrefilledLocalUniforms().getSizeInBytes());
  189. count += U32(mtl.getPrefilledLocalUniforms().getSizeInBytes() / 4);
  190. }
  191. ANKI_ASSERT(count * 4 == m_gpuSceneUniforms.getAllocatedSize());
  192. GpuSceneMicroPatcher::getSingleton().newCopy(*info.m_framePool, m_gpuSceneUniforms.getOffset(),
  193. m_gpuSceneUniforms.getAllocatedSize(), &allUniforms[0]);
  194. }
  195. // Upload transforms
  196. if(moved || movedLastFrame) [[unlikely]]
  197. {
  198. Array<Mat3x4, 2> trfs;
  199. trfs[0] = Mat3x4(info.m_node->getWorldTransform());
  200. trfs[1] = Mat3x4(info.m_node->getPreviousWorldTransform());
  201. GpuSceneMicroPatcher::getSingleton().newCopy(*info.m_framePool, m_gpuSceneIndexTransforms.getOffsetInGpuScene(),
  202. trfs);
  203. }
  204. // Spatial update
  205. const Bool spatialNeedsUpdate = moved || resourceUpdated || m_skinComponent;
  206. if(spatialNeedsUpdate) [[unlikely]]
  207. {
  208. Aabb aabbLocal;
  209. if(m_skinComponent == nullptr) [[likely]]
  210. {
  211. aabbLocal = m_model->getBoundingVolume();
  212. }
  213. else
  214. {
  215. aabbLocal =
  216. m_skinComponent->getBoneBoundingVolumeLocalSpace().getCompoundShape(m_model->getBoundingVolume());
  217. }
  218. const Aabb aabbWorld = aabbLocal.getTransformed(info.m_node->getWorldTransform());
  219. m_spatial.setBoundingShape(aabbWorld);
  220. }
  221. const Bool spatialUpdated = m_spatial.update(SceneGraph::getSingleton().getOctree());
  222. updated = updated || spatialUpdated;
  223. // Update the buckets
  224. const Bool bucketsNeedUpdate = resourceUpdated || moved != movedLastFrame;
  225. if(bucketsNeedUpdate)
  226. {
  227. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  228. for(U32 i = 0; i < modelPatchCount; ++i)
  229. {
  230. // Refresh the render state buckets
  231. for(RenderingTechnique t : EnumIterable<RenderingTechnique>())
  232. {
  233. RenderStateBucketContainer::getSingleton().removeUser(m_patchInfos[i].m_renderStateBucketIndices[t]);
  234. if(!(RenderingTechniqueBit(1 << t) & m_patchInfos[i].m_techniques))
  235. {
  236. continue;
  237. }
  238. // Fill the state
  239. RenderingKey key;
  240. key.setLod(0); // Materials don't care
  241. key.setRenderingTechnique(t);
  242. key.setSkinned(hasSkin);
  243. key.setVelocity(moved);
  244. const MaterialVariant& mvariant = m_model->getModelPatches()[i].getMaterial()->getOrCreateVariant(key);
  245. RenderStateInfo state;
  246. state.m_primitiveTopology = PrimitiveTopology::kTriangles;
  247. state.m_indexedDrawcall = true;
  248. state.m_program = mvariant.getShaderProgram();
  249. m_patchInfos[i].m_renderStateBucketIndices[t] =
  250. RenderStateBucketContainer::getSingleton().addUser(state, t);
  251. }
  252. }
  253. }
  254. // Upload the AABBs to the GPU scene
  255. const Bool gpuSceneAabbsNeedUpdate = spatialNeedsUpdate || bucketsNeedUpdate;
  256. if(gpuSceneAabbsNeedUpdate)
  257. {
  258. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  259. for(U32 i = 0; i < modelPatchCount; ++i)
  260. {
  261. GpuSceneRenderableAabb gpuVolume;
  262. gpuVolume.m_aabbMin = m_spatial.getAabbWorldSpace().getMin().xyz();
  263. gpuVolume.m_aabbMax = m_spatial.getAabbWorldSpace().getMax().xyz();
  264. gpuVolume.m_renderableIndex = m_patchInfos[i].m_gpuSceneIndexRenderable.get();
  265. for(RenderingTechnique t :
  266. EnumBitsIterable<RenderingTechnique, RenderingTechniqueBit>(m_patchInfos[i].m_techniques))
  267. {
  268. gpuVolume.m_renderStateBucket = 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