ModelComponent.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Copyright (C) 2009-2022, 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. getExternalSubsystems(*node).m_gpuSceneMemoryPool->allocate(sizeof(Mat3x4) * 2, alignof(F32), m_gpuSceneTransforms);
  19. }
  20. ModelComponent::~ModelComponent()
  21. {
  22. GpuSceneMemoryPool& gpuScene = *getExternalSubsystems(*m_node).m_gpuSceneMemoryPool;
  23. gpuScene.free(m_gpuSceneMeshLods);
  24. gpuScene.free(m_gpuSceneUniforms);
  25. gpuScene.free(m_gpuSceneTransforms);
  26. m_patchInfos.destroy(m_node->getMemoryPool());
  27. m_spatial.removeFromOctree(m_node->getSceneGraph().getOctree());
  28. }
  29. void ModelComponent::loadModelResource(CString filename)
  30. {
  31. ModelResourcePtr rsrc;
  32. const Error err = getExternalSubsystems(*m_node).m_resourceManager->loadResource(filename, rsrc);
  33. if(err)
  34. {
  35. ANKI_SCENE_LOGE("Failed to load model resource");
  36. return;
  37. }
  38. m_dirty = true;
  39. m_model = std::move(rsrc);
  40. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  41. // GPU scene allocations
  42. GpuSceneMemoryPool& gpuScene = *getExternalSubsystems(*m_node).m_gpuSceneMemoryPool;
  43. gpuScene.free(m_gpuSceneMeshLods);
  44. gpuScene.allocate(sizeof(GpuSceneMeshLod) * kMaxLodCount * modelPatchCount, 4, m_gpuSceneMeshLods);
  45. U32 uniformsSize = 0;
  46. m_patchInfos.resize(m_node->getMemoryPool(), modelPatchCount);
  47. for(U32 i = 0; i < modelPatchCount; ++i)
  48. {
  49. m_patchInfos[i].m_gpuSceneUniformsOffset = uniformsSize;
  50. const U32 size = U32(m_model->getModelPatches()[i].getMaterial()->getPrefilledLocalUniforms().getSizeInBytes());
  51. ANKI_ASSERT((size % 4) == 0);
  52. uniformsSize += size;
  53. }
  54. gpuScene.free(m_gpuSceneUniforms);
  55. gpuScene.allocate(uniformsSize, 4, m_gpuSceneUniforms);
  56. for(U32 i = 0; i < modelPatchCount; ++i)
  57. {
  58. m_patchInfos[i].m_gpuSceneUniformsOffset += U32(m_gpuSceneUniforms.m_offset);
  59. }
  60. // Some other per-patch init
  61. m_presentRenderingTechniques = RenderingTechniqueBit::kNone;
  62. m_castsShadow = false;
  63. for(U32 i = 0; i < modelPatchCount; ++i)
  64. {
  65. m_patchInfos[i].m_techniques = m_model->getModelPatches()[i].getMaterial()->getRenderingTechniques();
  66. m_castsShadow = m_castsShadow || m_model->getModelPatches()[i].getMaterial()->castsShadow();
  67. m_presentRenderingTechniques |= m_model->getModelPatches()[i].getMaterial()->getRenderingTechniques();
  68. }
  69. }
  70. Error ModelComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  71. {
  72. if(!isEnabled()) [[unlikely]]
  73. {
  74. updated = false;
  75. return Error::kNone;
  76. }
  77. const Bool resourceUpdated = m_dirty;
  78. m_dirty = false;
  79. const Bool moved = info.m_node->movedThisFrame() || m_firstTimeUpdate;
  80. const Bool movedLastFrame = m_movedLastFrame || m_firstTimeUpdate;
  81. m_firstTimeUpdate = false;
  82. m_movedLastFrame = moved;
  83. updated = resourceUpdated || moved || movedLastFrame;
  84. // Upload mesh LODs and uniforms
  85. if(resourceUpdated) [[unlikely]]
  86. {
  87. GpuSceneMicroPatcher& gpuScenePatcher = *getExternalSubsystems(*info.m_node).m_gpuSceneMicroPatcher;
  88. // Upload the mesh views
  89. const U32 modelPatchCount = m_model->getModelPatches().getSize();
  90. DynamicArrayRaii<GpuSceneMeshLod> meshLods(info.m_framePool, modelPatchCount * kMaxLodCount);
  91. for(U32 i = 0; i < modelPatchCount; ++i)
  92. {
  93. const ModelPatch& patch = m_model->getModelPatches()[i];
  94. const MeshResource& mesh = *patch.getMesh();
  95. for(U32 l = 0; l < mesh.getLodCount(); ++l)
  96. {
  97. GpuSceneMeshLod& meshLod = meshLods[i * kMaxLodCount + l];
  98. meshLod = {};
  99. meshLod.m_positionScale = mesh.getPositionsScale();
  100. meshLod.m_positionTranslation = mesh.getPositionsTranslation();
  101. for(VertexStreamId stream = VertexStreamId::kPosition; stream <= VertexStreamId::kBoneWeights; ++stream)
  102. {
  103. if(!mesh.isVertexStreamPresent(stream))
  104. {
  105. continue;
  106. }
  107. PtrSize offset;
  108. U32 vertCount;
  109. mesh.getVertexStreamInfo(l, stream, offset, vertCount);
  110. const PtrSize elementSize = getFormatInfo(kMeshRelatedVertexStreamFormats[stream]).m_texelSize;
  111. ANKI_ASSERT((offset % elementSize) == 0);
  112. meshLod.m_vertexOffsets[U32(stream)] = U32(offset / elementSize);
  113. }
  114. PtrSize offset;
  115. U32 indexCount;
  116. IndexType indexType;
  117. mesh.getIndexBufferInfo(l, offset, indexCount, indexType);
  118. meshLod.m_indexOffset = U32(offset);
  119. meshLod.m_indexCount = indexCount;
  120. }
  121. // Copy the last LOD to the rest just in case
  122. for(U32 l = mesh.getLodCount(); l < kMaxLodCount; ++l)
  123. {
  124. meshLods[i * kMaxLodCount + l] = meshLods[i * kMaxLodCount + (l - 1)];
  125. }
  126. }
  127. gpuScenePatcher.newCopy(*info.m_framePool, m_gpuSceneMeshLods.m_offset, meshLods.getSizeInBytes(),
  128. &meshLods[0]);
  129. // Upload the uniforms
  130. DynamicArrayRaii<U32> allUniforms(info.m_framePool, U32(m_gpuSceneUniforms.m_size / 4));
  131. U32 count = 0;
  132. for(U32 i = 0; i < modelPatchCount; ++i)
  133. {
  134. const ModelPatch& patch = m_model->getModelPatches()[i];
  135. const MaterialResource& mtl = *patch.getMaterial();
  136. memcpy(&allUniforms[count], mtl.getPrefilledLocalUniforms().getBegin(),
  137. mtl.getPrefilledLocalUniforms().getSizeInBytes());
  138. count += U32(mtl.getPrefilledLocalUniforms().getSizeInBytes() / 4);
  139. }
  140. ANKI_ASSERT(count * 4 == m_gpuSceneUniforms.m_size);
  141. gpuScenePatcher.newCopy(*info.m_framePool, m_gpuSceneUniforms.m_offset, m_gpuSceneUniforms.m_size,
  142. &allUniforms[0]);
  143. }
  144. // Upload transforms
  145. if(moved || movedLastFrame) [[unlikely]]
  146. {
  147. Array<Mat3x4, 2> trfs;
  148. trfs[0] = Mat3x4(info.m_node->getWorldTransform());
  149. trfs[1] = Mat3x4(info.m_node->getPreviousWorldTransform());
  150. getExternalSubsystems(*info.m_node)
  151. .m_gpuSceneMicroPatcher->newCopy(*info.m_framePool, m_gpuSceneTransforms.m_offset, sizeof(trfs), &trfs[0]);
  152. }
  153. // Spatial update
  154. if(moved || resourceUpdated || m_skinComponent) [[unlikely]]
  155. {
  156. Aabb aabbLocal;
  157. if(m_skinComponent == nullptr) [[likely]]
  158. {
  159. aabbLocal = m_model->getBoundingVolume();
  160. }
  161. else
  162. {
  163. aabbLocal = m_skinComponent->getBoneBoundingVolumeLocalSpace();
  164. }
  165. const Aabb aabbWorld = aabbLocal.getTransformed(info.m_node->getWorldTransform());
  166. m_spatial.setBoundingShape(aabbWorld);
  167. }
  168. const Bool spatialUpdated = m_spatial.update(info.m_node->getSceneGraph().getOctree());
  169. updated = updated || spatialUpdated;
  170. return Error::kNone;
  171. }
  172. void ModelComponent::setupRenderableQueueElements(U32 lod, RenderingTechnique technique, StackMemoryPool& tmpPool,
  173. WeakArray<RenderableQueueElement>& outRenderables) const
  174. {
  175. ANKI_ASSERT(isEnabled());
  176. outRenderables.setArray(nullptr, 0);
  177. const RenderingTechniqueBit requestedRenderingTechniqueMask = RenderingTechniqueBit(1 << technique);
  178. if(!(m_presentRenderingTechniques & requestedRenderingTechniqueMask))
  179. {
  180. return;
  181. }
  182. // Allocate renderables
  183. U32 renderableCount = 0;
  184. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  185. {
  186. renderableCount += !!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask);
  187. }
  188. if(renderableCount == 0)
  189. {
  190. return;
  191. }
  192. RenderableQueueElement* renderables = static_cast<RenderableQueueElement*>(
  193. tmpPool.allocate(sizeof(RenderableQueueElement) * renderableCount, alignof(RenderableQueueElement)));
  194. outRenderables.setArray(renderables, renderableCount);
  195. // Fill renderables
  196. const Bool moved = m_node->movedThisFrame() && technique == RenderingTechnique::kGBuffer;
  197. const Bool hasSkin = m_skinComponent != nullptr && m_skinComponent->isEnabled();
  198. RenderingKey key;
  199. key.setLod(lod);
  200. key.setRenderingTechnique(technique);
  201. key.setVelocity(moved);
  202. key.setSkinned(hasSkin);
  203. renderableCount = 0;
  204. for(U32 i = 0; i < m_patchInfos.getSize(); ++i)
  205. {
  206. if(!(m_patchInfos[i].m_techniques & requestedRenderingTechniqueMask))
  207. {
  208. continue;
  209. }
  210. RenderableQueueElement& queueElem = renderables[renderableCount];
  211. const ModelPatch& patch = m_model->getModelPatches()[i];
  212. ModelRenderingInfo modelInf;
  213. patch.getRenderingInfo(key, modelInf);
  214. queueElem.m_program = modelInf.m_program.get();
  215. queueElem.m_worldTransformsOffset = U32(m_gpuSceneTransforms.m_offset);
  216. queueElem.m_uniformsOffset = m_patchInfos[i].m_gpuSceneUniformsOffset;
  217. queueElem.m_geometryOffset =
  218. U32(m_gpuSceneMeshLods.m_offset + sizeof(GpuSceneMeshLod) * (kMaxLodCount * i + lod));
  219. queueElem.m_boneTransformsOffset = (hasSkin) ? m_skinComponent->getBoneTransformsGpuSceneOffset() : 0;
  220. queueElem.m_indexCount = modelInf.m_indexCount;
  221. queueElem.m_firstIndex = U32(modelInf.m_indexBufferOffset / 2 + modelInf.m_firstIndex);
  222. queueElem.m_indexed = true;
  223. queueElem.m_primitiveTopology = PrimitiveTopology::kTriangles;
  224. queueElem.m_aabbMin = m_spatial.getAabbWorldSpace().getMin().xyz();
  225. queueElem.m_aabbMax = m_spatial.getAabbWorldSpace().getMax().xyz();
  226. queueElem.computeMergeKey();
  227. ++renderableCount;
  228. }
  229. }
  230. void ModelComponent::onOtherComponentRemovedOrAdded(SceneComponent* other, Bool added)
  231. {
  232. ANKI_ASSERT(other);
  233. if(other->getClassId() != SkinComponent::getStaticClassId())
  234. {
  235. return;
  236. }
  237. if(added && m_skinComponent != nullptr)
  238. {
  239. m_skinComponent = static_cast<SkinComponent*>(other);
  240. m_dirty = true;
  241. }
  242. else if(other == m_skinComponent)
  243. {
  244. m_skinComponent = nullptr;
  245. m_dirty = true;
  246. }
  247. }
  248. } // end namespace anki