ModelNode.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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/ModelNode.h>
  6. #include <AnKi/Scene/SceneGraph.h>
  7. #include <AnKi/Scene/DebugDrawer.h>
  8. #include <AnKi/Scene/Components/MoveComponent.h>
  9. #include <AnKi/Scene/Components/SkinComponent.h>
  10. #include <AnKi/Scene/Components/SpatialComponent.h>
  11. #include <AnKi/Scene/Components/RenderComponent.h>
  12. #include <AnKi/Scene/Components/ModelComponent.h>
  13. #include <AnKi/Resource/ModelResource.h>
  14. #include <AnKi/Resource/ResourceManager.h>
  15. #include <AnKi/Resource/SkeletonResource.h>
  16. #include <AnKi/Physics/PhysicsWorld.h>
  17. namespace anki {
  18. /// Feedback component.
  19. class ModelNode::FeedbackComponent : public SceneComponent
  20. {
  21. ANKI_SCENE_COMPONENT(ModelNode::FeedbackComponent)
  22. public:
  23. FeedbackComponent(SceneNode* node)
  24. : SceneComponent(node, getStaticClassId(), true)
  25. {
  26. }
  27. Error update(SceneComponentUpdateInfo& info, Bool& updated) override
  28. {
  29. updated = false;
  30. static_cast<ModelNode&>(*info.m_node).feedbackUpdate();
  31. return Error::NONE;
  32. }
  33. };
  34. ANKI_SCENE_COMPONENT_STATICS(ModelNode::FeedbackComponent)
  35. class ModelNode::RenderProxy
  36. {
  37. public:
  38. ModelNode* m_node = nullptr;
  39. };
  40. ModelNode::ModelNode(SceneGraph* scene, CString name)
  41. : SceneNode(scene, name)
  42. {
  43. newComponent<ModelComponent>();
  44. newComponent<SkinComponent>();
  45. newComponent<MoveComponent>();
  46. newComponent<FeedbackComponent>();
  47. newComponent<SpatialComponent>();
  48. newComponent<RenderComponent>(); // One of many
  49. m_renderProxies.create(getAllocator(), 1);
  50. }
  51. ModelNode::~ModelNode()
  52. {
  53. m_renderProxies.destroy(getAllocator());
  54. }
  55. void ModelNode::feedbackUpdate()
  56. {
  57. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  58. const SkinComponent& skinc = getFirstComponentOfType<SkinComponent>();
  59. const MoveComponent& movec = getFirstComponentOfType<MoveComponent>();
  60. if(!modelc.isEnabled())
  61. {
  62. // Disable everything
  63. ANKI_ASSERT(!"TODO");
  64. return;
  65. }
  66. const Timestamp globTimestamp = getGlobalTimestamp();
  67. Bool updateSpatial = false;
  68. // Model update
  69. if(modelc.getTimestamp() == globTimestamp)
  70. {
  71. m_aabbLocal = modelc.getModelResource()->getBoundingVolume();
  72. updateSpatial = true;
  73. if(modelc.getModelResource()->getModelPatches().getSize() == countComponentsOfType<RenderComponent>())
  74. {
  75. // Easy, just re-init the render components
  76. initRenderComponents();
  77. }
  78. else
  79. {
  80. // Need to create more render components, can't do it at the moment, deffer it
  81. m_deferredRenderComponentUpdate = true;
  82. }
  83. }
  84. // Skin update
  85. if(skinc.isEnabled() && skinc.getTimestamp() == globTimestamp)
  86. {
  87. m_aabbLocal = skinc.getBoneBoundingVolumeLocalSpace();
  88. updateSpatial = true;
  89. }
  90. // Move update
  91. if(movec.getTimestamp() == globTimestamp)
  92. {
  93. getFirstComponentOfType<SpatialComponent>().setSpatialOrigin(movec.getWorldTransform().getOrigin().xyz());
  94. updateSpatial = true;
  95. }
  96. // Spatial update
  97. if(updateSpatial)
  98. {
  99. const Aabb aabbWorld = m_aabbLocal.getTransformed(movec.getWorldTransform());
  100. getFirstComponentOfType<SpatialComponent>().setAabbWorldSpace(aabbWorld);
  101. }
  102. }
  103. Error ModelNode::frameUpdate([[maybe_unused]] Second prevUpdateTime, [[maybe_unused]] Second crntTime)
  104. {
  105. if(ANKI_LIKELY(!m_deferredRenderComponentUpdate))
  106. {
  107. return Error::NONE;
  108. }
  109. m_deferredRenderComponentUpdate = false;
  110. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  111. const U32 modelPatchCount = modelc.getModelResource()->getModelPatches().getSize();
  112. const U32 renderComponentCount = countComponentsOfType<RenderComponent>();
  113. if(modelPatchCount > renderComponentCount)
  114. {
  115. const U32 diff = modelPatchCount - renderComponentCount;
  116. for(U32 i = 0; i < diff; ++i)
  117. {
  118. newComponent<RenderComponent>();
  119. }
  120. m_renderProxies.resize(getAllocator(), modelPatchCount);
  121. }
  122. else
  123. {
  124. ANKI_ASSERT(!"TODO");
  125. }
  126. ANKI_ASSERT(countComponentsOfType<RenderComponent>() == modelPatchCount);
  127. // Now you can init the render components
  128. initRenderComponents();
  129. return Error::NONE;
  130. }
  131. void ModelNode::initRenderComponents()
  132. {
  133. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  134. const ModelResourcePtr& model = modelc.getModelResource();
  135. ANKI_ASSERT(modelc.getModelResource()->getModelPatches().getSize() == countComponentsOfType<RenderComponent>());
  136. ANKI_ASSERT(modelc.getModelResource()->getModelPatches().getSize() == m_renderProxies.getSize());
  137. for(U32 patchIdx = 0; patchIdx < model->getModelPatches().getSize(); ++patchIdx)
  138. {
  139. RenderComponent& rc = getNthComponentOfType<RenderComponent>(patchIdx);
  140. rc.initRaster(
  141. [](RenderQueueDrawContext& ctx, ConstWeakArray<void*> userData) {
  142. const RenderProxy& proxy = *static_cast<const RenderProxy*>(userData[0]);
  143. const U32 modelPatchIdx = U32(&proxy - &proxy.m_node->m_renderProxies[0]);
  144. proxy.m_node->draw(ctx, userData, modelPatchIdx);
  145. },
  146. &m_renderProxies[patchIdx], modelc.getRenderMergeKeys()[patchIdx]);
  147. rc.setFlagsFromMaterial(model->getModelPatches()[patchIdx].getMaterial());
  148. if(!!(model->getModelPatches()[patchIdx].getMaterial()->getRenderingTechniques()
  149. & RenderingTechniqueBit::ALL_RT))
  150. {
  151. rc.initRayTracing(
  152. [](U32 lod, const void* userData, RayTracingInstanceQueueElement& el) {
  153. const RenderProxy& proxy = *static_cast<const RenderProxy*>(userData);
  154. const U32 modelPatchIdx = U32(&proxy - &proxy.m_node->m_renderProxies[0]);
  155. proxy.m_node->setupRayTracingInstanceQueueElement(lod, modelPatchIdx, el);
  156. },
  157. &m_renderProxies[patchIdx]);
  158. }
  159. m_renderProxies[patchIdx].m_node = this;
  160. }
  161. }
  162. void ModelNode::draw(RenderQueueDrawContext& ctx, ConstWeakArray<void*> userData, U32 modelPatchIdx) const
  163. {
  164. const U32 instanceCount = userData.getSize();
  165. ANKI_ASSERT(instanceCount > 0 && instanceCount <= MAX_INSTANCE_COUNT);
  166. ANKI_ASSERT(ctx.m_key.getInstanceCount() == instanceCount);
  167. CommandBufferPtr& cmdb = ctx.m_commandBuffer;
  168. if(ANKI_LIKELY(!ctx.m_debugDraw))
  169. {
  170. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  171. const ModelPatch& patch = modelc.getModelResource()->getModelPatches()[modelPatchIdx];
  172. const SkinComponent& skinc = getFirstComponentOfType<SkinComponent>();
  173. // Transforms
  174. Array<Mat3x4, MAX_INSTANCE_COUNT> trfs;
  175. Array<Mat3x4, MAX_INSTANCE_COUNT> prevTrfs;
  176. const MoveComponent& movec = getFirstComponentOfType<MoveComponent>();
  177. trfs[0] = Mat3x4(movec.getWorldTransform());
  178. prevTrfs[0] = Mat3x4(movec.getPreviousWorldTransform());
  179. Bool moved = trfs[0] != prevTrfs[0];
  180. for(U32 i = 1; i < instanceCount; ++i)
  181. {
  182. const ModelNode& otherNode = *static_cast<const RenderProxy*>(userData[i])->m_node;
  183. [[maybe_unused]] const U32 otherNodeModelPatchIdx =
  184. U32(static_cast<const RenderProxy*>(userData[i]) - &otherNode.m_renderProxies[0]);
  185. ANKI_ASSERT(otherNodeModelPatchIdx == modelPatchIdx);
  186. const MoveComponent& otherNodeMovec = otherNode.getFirstComponentOfType<MoveComponent>();
  187. trfs[i] = Mat3x4(otherNodeMovec.getWorldTransform());
  188. prevTrfs[i] = Mat3x4(otherNodeMovec.getPreviousWorldTransform());
  189. moved = moved || (trfs[i] != prevTrfs[i]);
  190. }
  191. ctx.m_key.setVelocity(moved && ctx.m_key.getRenderingTechnique() == RenderingTechnique::GBUFFER);
  192. ctx.m_key.setSkinned(skinc.isEnabled());
  193. ModelRenderingInfo modelInf;
  194. patch.getRenderingInfo(ctx.m_key, modelInf);
  195. // Bones storage
  196. if(skinc.isEnabled())
  197. {
  198. const U32 boneCount = skinc.getBoneTransforms().getSize();
  199. StagingGpuMemoryToken token, tokenPrev;
  200. void* trfs = ctx.m_stagingGpuAllocator->allocateFrame(boneCount * sizeof(Mat4),
  201. StagingGpuMemoryType::STORAGE, token);
  202. memcpy(trfs, &skinc.getBoneTransforms()[0], boneCount * sizeof(Mat4));
  203. trfs = ctx.m_stagingGpuAllocator->allocateFrame(boneCount * sizeof(Mat4), StagingGpuMemoryType::STORAGE,
  204. tokenPrev);
  205. memcpy(trfs, &skinc.getPreviousFrameBoneTransforms()[0], boneCount * sizeof(Mat4));
  206. cmdb->bindStorageBuffer(MATERIAL_SET_LOCAL, MATERIAL_BINDING_BONE_TRANSFORMS, token.m_buffer,
  207. token.m_offset, token.m_range);
  208. cmdb->bindStorageBuffer(MATERIAL_SET_LOCAL, MATERIAL_BINDING_PREVIOUS_BONE_TRANSFORMS, tokenPrev.m_buffer,
  209. tokenPrev.m_offset, tokenPrev.m_range);
  210. }
  211. // Program
  212. cmdb->bindShaderProgram(modelInf.m_program);
  213. // Uniforms
  214. RenderComponent::allocateAndSetupUniforms(
  215. modelc.getModelResource()->getModelPatches()[modelPatchIdx].getMaterial(), ctx,
  216. ConstWeakArray<Mat3x4>(&trfs[0], instanceCount), ConstWeakArray<Mat3x4>(&prevTrfs[0], instanceCount),
  217. *ctx.m_stagingGpuAllocator);
  218. // Set attributes
  219. for(U i = 0; i < modelInf.m_vertexAttributeCount; ++i)
  220. {
  221. const ModelVertexAttribute& attrib = modelInf.m_vertexAttributes[i];
  222. ANKI_ASSERT(attrib.m_format != Format::NONE);
  223. cmdb->setVertexAttribute(U32(attrib.m_location), attrib.m_bufferBinding, attrib.m_format,
  224. attrib.m_relativeOffset);
  225. }
  226. // Set vertex buffers
  227. for(U32 i = 0; i < modelInf.m_vertexBufferBindingCount; ++i)
  228. {
  229. const ModelVertexBufferBinding& binding = modelInf.m_vertexBufferBindings[i];
  230. cmdb->bindVertexBuffer(i, binding.m_buffer, binding.m_offset, binding.m_stride, VertexStepRate::VERTEX);
  231. }
  232. // Index buffer
  233. cmdb->bindIndexBuffer(modelInf.m_indexBuffer, modelInf.m_indexBufferOffset, IndexType::U16);
  234. // Draw
  235. cmdb->drawElements(PrimitiveTopology::TRIANGLES, modelInf.m_indexCount, instanceCount, modelInf.m_firstIndex, 0,
  236. 0);
  237. }
  238. else
  239. {
  240. // Draw the bounding volumes
  241. Mat4* const mvps = ctx.m_frameAllocator.newArray<Mat4>(instanceCount);
  242. for(U32 i = 0; i < instanceCount; ++i)
  243. {
  244. const ModelNode& otherNode = *static_cast<const RenderProxy*>(userData[i])->m_node;
  245. const Aabb& box = otherNode.getFirstComponentOfType<SpatialComponent>().getAabbWorldSpace();
  246. const Vec4 tsl = (box.getMin() + box.getMax()) / 2.0f;
  247. const Vec3 scale = (box.getMax().xyz() - box.getMin().xyz()) / 2.0f;
  248. // Set non uniform scale. Add a margin to avoid flickering
  249. Mat3 nonUniScale = Mat3::getZero();
  250. constexpr F32 MARGIN = 1.02f;
  251. nonUniScale(0, 0) = scale.x() * MARGIN;
  252. nonUniScale(1, 1) = scale.y() * MARGIN;
  253. nonUniScale(2, 2) = scale.z() * MARGIN;
  254. mvps[i] = ctx.m_viewProjectionMatrix * Mat4(tsl.xyz1(), Mat3::getIdentity() * nonUniScale, 1.0f);
  255. }
  256. const Bool enableDepthTest = ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DEPTH_TEST_ON);
  257. if(enableDepthTest)
  258. {
  259. cmdb->setDepthCompareOperation(CompareOperation::LESS);
  260. }
  261. else
  262. {
  263. cmdb->setDepthCompareOperation(CompareOperation::ALWAYS);
  264. }
  265. getSceneGraph().getDebugDrawer().drawCubes(
  266. ConstWeakArray<Mat4>(mvps, instanceCount), Vec4(1.0f, 0.0f, 1.0f, 1.0f), 2.0f,
  267. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), 2.0f,
  268. *ctx.m_stagingGpuAllocator, cmdb);
  269. ctx.m_frameAllocator.deleteArray(mvps, instanceCount);
  270. // Bones
  271. const SkinComponent& skinc = getFirstComponentOfType<SkinComponent>();
  272. if(skinc.isEnabled())
  273. {
  274. const SkinComponent& skinc = getComponentAt<SkinComponent>(0);
  275. SkeletonResourcePtr skeleton = skinc.getSkeleronResource();
  276. const U32 boneCount = skinc.getBoneTransforms().getSize();
  277. DynamicArrayAuto<Vec3> lines(ctx.m_frameAllocator);
  278. lines.resizeStorage(boneCount * 2);
  279. DynamicArrayAuto<Vec3> chidlessLines(ctx.m_frameAllocator);
  280. for(U32 i = 0; i < boneCount; ++i)
  281. {
  282. const Bone& bone = skeleton->getBones()[i];
  283. ANKI_ASSERT(bone.getIndex() == i);
  284. const Vec4 point(0.0f, 0.0f, 0.0f, 1.0f);
  285. const Bone* parent = bone.getParent();
  286. Mat4 m = (parent)
  287. ? skinc.getBoneTransforms()[parent->getIndex()] * parent->getVertexTransform().getInverse()
  288. : Mat4::getIdentity();
  289. const Vec3 a = (m * point).xyz();
  290. m = skinc.getBoneTransforms()[i] * bone.getVertexTransform().getInverse();
  291. const Vec3 b = (m * point).xyz();
  292. lines.emplaceBack(a);
  293. lines.emplaceBack(b);
  294. if(bone.getChildren().getSize() == 0)
  295. {
  296. // If there are not children try to draw something for that bone as well
  297. chidlessLines.emplaceBack(b);
  298. const F32 len = (b - a).getLength();
  299. const Vec3 c = b + (b - a).getNormalized() * len;
  300. chidlessLines.emplaceBack(c);
  301. }
  302. }
  303. const Mat4 mvp =
  304. ctx.m_viewProjectionMatrix * Mat4(getFirstComponentOfType<MoveComponent>().getWorldTransform());
  305. getSceneGraph().getDebugDrawer().drawLines(
  306. ConstWeakArray<Mat4>(&mvp, 1), Vec4(1.0f), 20.0f,
  307. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), lines,
  308. *ctx.m_stagingGpuAllocator, cmdb);
  309. getSceneGraph().getDebugDrawer().drawLines(
  310. ConstWeakArray<Mat4>(&mvp, 1), Vec4(0.7f, 0.7f, 0.7f, 1.0f), 5.0f,
  311. ctx.m_debugDrawFlags.get(RenderQueueDebugDrawFlag::DITHERED_DEPTH_TEST_ON), chidlessLines,
  312. *ctx.m_stagingGpuAllocator, cmdb);
  313. }
  314. // Restore state
  315. if(!enableDepthTest)
  316. {
  317. cmdb->setDepthCompareOperation(CompareOperation::LESS);
  318. }
  319. }
  320. }
  321. void ModelNode::setupRayTracingInstanceQueueElement(U32 lod, U32 modelPatchIdx,
  322. RayTracingInstanceQueueElement& el) const
  323. {
  324. const ModelComponent& modelc = getFirstComponentOfType<ModelComponent>();
  325. const ModelPatch& patch = modelc.getModelResource()->getModelPatches()[modelPatchIdx];
  326. RenderingKey key(RenderingTechnique::RT_SHADOW, lod, 1, false, false);
  327. ModelRayTracingInfo info;
  328. patch.getRayTracingInfo(key, info);
  329. memset(&el, 0, sizeof(el));
  330. el.m_bottomLevelAccelerationStructure = info.m_bottomLevelAccelerationStructure.get();
  331. const MoveComponent& movec = getFirstComponentOfType<MoveComponent>();
  332. el.m_transform = Mat3x4(movec.getWorldTransform());
  333. el.m_shaderGroupHandleIndex = info.m_shaderGroupHandleIndex;
  334. // References
  335. el.m_grObjectCount = info.m_grObjectReferences.getSize();
  336. for(U32 i = 0; i < el.m_grObjectCount; ++i)
  337. {
  338. // const_cast hack follows. To avoid the const you could copy m_grObjectReferences[i] to a GrObjectPtr and then
  339. // call get() on that. But that will cost 2 atomic operations
  340. el.m_grObjects[i] = const_cast<GrObject*>(info.m_grObjectReferences[i].get());
  341. }
  342. }
  343. } // end namespace anki