StaticModel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Core/Context.h"
  5. #include "../Core/Profiler.h"
  6. #include "../Graphics/AnimatedModel.h"
  7. #include "../Graphics/Batch.h"
  8. #include "../Graphics/Camera.h"
  9. #include "../Graphics/Geometry.h"
  10. #include "../Graphics/Material.h"
  11. #include "../Graphics/OcclusionBuffer.h"
  12. #include "../Graphics/OctreeQuery.h"
  13. #include "../GraphicsAPI/VertexBuffer.h"
  14. #include "../IO/FileSystem.h"
  15. #include "../IO/Log.h"
  16. #include "../Resource/ResourceCache.h"
  17. #include "../Resource/ResourceEvents.h"
  18. #include "../DebugNew.h"
  19. namespace Urho3D
  20. {
  21. extern const char* GEOMETRY_CATEGORY;
  22. StaticModel::StaticModel(Context* context) :
  23. Drawable(context, DRAWABLE_GEOMETRY),
  24. occlusionLodLevel_(M_MAX_UNSIGNED),
  25. materialsAttr_(Material::GetTypeStatic())
  26. {
  27. }
  28. StaticModel::~StaticModel() = default;
  29. void StaticModel::RegisterObject(Context* context)
  30. {
  31. context->RegisterFactory<StaticModel>(GEOMETRY_CATEGORY);
  32. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  33. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  34. URHO3D_ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  35. AM_DEFAULT);
  36. URHO3D_ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  37. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  38. URHO3D_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  39. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  40. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  41. URHO3D_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  42. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  43. URHO3D_ATTRIBUTE("Occlusion LOD Level", int, occlusionLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  44. }
  45. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  46. {
  47. RayQueryLevel level = query.level_;
  48. switch (level)
  49. {
  50. case RAY_AABB:
  51. Drawable::ProcessRayQuery(query, results);
  52. break;
  53. case RAY_OBB:
  54. case RAY_TRIANGLE:
  55. case RAY_TRIANGLE_UV:
  56. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  57. Ray localRay = query.ray_.Transformed(inverse);
  58. float distance = localRay.HitDistance(boundingBox_);
  59. Vector3 normal = -query.ray_.direction_;
  60. Vector2 geometryUV;
  61. unsigned hitBatch = M_MAX_UNSIGNED;
  62. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  63. {
  64. distance = M_INFINITY;
  65. for (unsigned i = 0; i < batches_.Size(); ++i)
  66. {
  67. Geometry* geometry = batches_[i].geometry_;
  68. if (geometry)
  69. {
  70. Vector3 geometryNormal;
  71. float geometryDistance = level == RAY_TRIANGLE ? geometry->GetHitDistance(localRay, &geometryNormal) :
  72. geometry->GetHitDistance(localRay, &geometryNormal, &geometryUV);
  73. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  74. {
  75. distance = geometryDistance;
  76. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  77. hitBatch = i;
  78. }
  79. }
  80. }
  81. }
  82. if (distance < query.maxDistance_)
  83. {
  84. RayQueryResult result;
  85. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  86. result.normal_ = normal;
  87. result.textureUV_ = geometryUV;
  88. result.distance_ = distance;
  89. result.drawable_ = this;
  90. result.node_ = node_;
  91. result.subObject_ = hitBatch;
  92. results.Push(result);
  93. }
  94. break;
  95. }
  96. }
  97. void StaticModel::UpdateBatches(const FrameInfo& frame)
  98. {
  99. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  100. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  101. if (batches_.Size() == 1)
  102. batches_[0].distance_ = distance_;
  103. else
  104. {
  105. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  106. for (unsigned i = 0; i < batches_.Size(); ++i)
  107. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  108. }
  109. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  110. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  111. if (newLodDistance != lodDistance_)
  112. {
  113. lodDistance_ = newLodDistance;
  114. CalculateLodLevels();
  115. }
  116. }
  117. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  118. {
  119. if (batchIndex >= geometries_.Size())
  120. return nullptr;
  121. // If level is out of range, use visible geometry
  122. if (level < geometries_[batchIndex].Size())
  123. return geometries_[batchIndex][level];
  124. else
  125. return batches_[batchIndex].geometry_;
  126. }
  127. unsigned StaticModel::GetNumOccluderTriangles()
  128. {
  129. unsigned triangles = 0;
  130. for (unsigned i = 0; i < batches_.Size(); ++i)
  131. {
  132. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  133. if (!geometry)
  134. continue;
  135. // Check that the material is suitable for occlusion (default material always is)
  136. Material* mat = batches_[i].material_;
  137. if (mat && !mat->GetOcclusion())
  138. continue;
  139. triangles += geometry->GetIndexCount() / 3;
  140. }
  141. return triangles;
  142. }
  143. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  144. {
  145. for (unsigned i = 0; i < batches_.Size(); ++i)
  146. {
  147. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  148. if (!geometry)
  149. continue;
  150. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  151. Material* material = batches_[i].material_;
  152. if (material)
  153. {
  154. if (!material->GetOcclusion())
  155. continue;
  156. buffer->SetCullMode(material->GetCullMode());
  157. }
  158. else
  159. buffer->SetCullMode(CULL_CCW);
  160. const unsigned char* vertexData;
  161. unsigned vertexSize;
  162. const unsigned char* indexData;
  163. unsigned indexSize;
  164. const PODVector<VertexElement>* elements;
  165. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  166. // Check for valid geometry data
  167. if (!vertexData || !indexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  168. continue;
  169. unsigned indexStart = geometry->GetIndexStart();
  170. unsigned indexCount = geometry->GetIndexCount();
  171. // Draw and check for running out of triangles
  172. if (!buffer->AddTriangles(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  173. return false;
  174. }
  175. return true;
  176. }
  177. void StaticModel::SetModel(Model* model)
  178. {
  179. if (model == model_)
  180. return;
  181. if (!node_)
  182. {
  183. URHO3D_LOGERROR("Can not set model while model component is not attached to a scene node");
  184. return;
  185. }
  186. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  187. if (model_)
  188. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  189. model_ = model;
  190. if (model)
  191. {
  192. SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(StaticModel, HandleModelReloadFinished));
  193. // Copy the subgeometry & LOD level structure
  194. SetNumGeometries(model->GetNumGeometries());
  195. const Vector<Vector<SharedPtr<Geometry>>>& geometries = model->GetGeometries();
  196. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  197. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : nullptr;
  198. for (unsigned i = 0; i < geometries.Size(); ++i)
  199. {
  200. batches_[i].worldTransform_ = worldTransform;
  201. geometries_[i] = geometries[i];
  202. geometryData_[i].center_ = geometryCenters[i];
  203. }
  204. SetBoundingBox(model->GetBoundingBox());
  205. ResetLodLevels();
  206. }
  207. else
  208. {
  209. SetNumGeometries(0);
  210. SetBoundingBox(BoundingBox());
  211. }
  212. MarkNetworkUpdate();
  213. }
  214. void StaticModel::SetMaterial(Material* material)
  215. {
  216. for (unsigned i = 0; i < batches_.Size(); ++i)
  217. batches_[i].material_ = material;
  218. MarkNetworkUpdate();
  219. }
  220. bool StaticModel::SetMaterial(unsigned index, Material* material)
  221. {
  222. if (index >= batches_.Size())
  223. {
  224. URHO3D_LOGERROR("Material index out of bounds");
  225. return false;
  226. }
  227. batches_[index].material_ = material;
  228. MarkNetworkUpdate();
  229. return true;
  230. }
  231. void StaticModel::SetOcclusionLodLevel(unsigned level)
  232. {
  233. occlusionLodLevel_ = level;
  234. MarkNetworkUpdate();
  235. }
  236. void StaticModel::ApplyMaterialList(const String& fileName)
  237. {
  238. String useFileName = fileName;
  239. if (useFileName.Trimmed().Empty() && model_)
  240. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  241. auto* cache = GetSubsystem<ResourceCache>();
  242. SharedPtr<File> file = cache->GetFile(useFileName, false);
  243. if (!file)
  244. return;
  245. unsigned index = 0;
  246. while (!file->IsEof() && index < batches_.Size())
  247. {
  248. auto* material = cache->GetResource<Material>(file->ReadLine());
  249. if (material)
  250. SetMaterial(index, material);
  251. ++index;
  252. }
  253. }
  254. Material* StaticModel::GetMaterial(unsigned index) const
  255. {
  256. return index < batches_.Size() ? batches_[index].material_ : nullptr;
  257. }
  258. bool StaticModel::IsInside(const Vector3& point) const
  259. {
  260. if (!node_)
  261. return false;
  262. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  263. return IsInsideLocal(localPosition);
  264. }
  265. bool StaticModel::IsInsideLocal(const Vector3& point) const
  266. {
  267. // Early-out if point is not inside bounding box
  268. if (boundingBox_.IsInside(point) == OUTSIDE)
  269. return false;
  270. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  271. for (unsigned i = 0; i < batches_.Size(); ++i)
  272. {
  273. Geometry* geometry = batches_[i].geometry_;
  274. if (geometry)
  275. {
  276. if (geometry->IsInside(localRay))
  277. return true;
  278. }
  279. }
  280. return false;
  281. }
  282. void StaticModel::SetBoundingBox(const BoundingBox& box)
  283. {
  284. boundingBox_ = box;
  285. OnMarkedDirty(node_);
  286. }
  287. void StaticModel::SetNumGeometries(unsigned num)
  288. {
  289. batches_.Resize(num);
  290. geometries_.Resize(num);
  291. geometryData_.Resize(num);
  292. ResetLodLevels();
  293. }
  294. void StaticModel::SetModelAttr(const ResourceRef& value)
  295. {
  296. auto* cache = GetSubsystem<ResourceCache>();
  297. SetModel(cache->GetResource<Model>(value.name_));
  298. }
  299. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  300. {
  301. auto* cache = GetSubsystem<ResourceCache>();
  302. for (unsigned i = 0; i < value.names_.Size(); ++i)
  303. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  304. }
  305. ResourceRef StaticModel::GetModelAttr() const
  306. {
  307. return GetResourceRef(model_, Model::GetTypeStatic());
  308. }
  309. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  310. {
  311. materialsAttr_.names_.Resize(batches_.Size());
  312. for (unsigned i = 0; i < batches_.Size(); ++i)
  313. materialsAttr_.names_[i] = GetResourceName(GetMaterial(i));
  314. return materialsAttr_;
  315. }
  316. void StaticModel::OnWorldBoundingBoxUpdate()
  317. {
  318. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  319. }
  320. void StaticModel::ResetLodLevels()
  321. {
  322. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  323. for (unsigned i = 0; i < batches_.Size(); ++i)
  324. {
  325. if (!geometries_[i].Size())
  326. geometries_[i].Resize(1);
  327. batches_[i].geometry_ = geometries_[i][0];
  328. geometryData_[i].lodLevel_ = 0;
  329. }
  330. // Find out the real LOD levels on next geometry update
  331. lodDistance_ = M_INFINITY;
  332. }
  333. void StaticModel::CalculateLodLevels()
  334. {
  335. for (unsigned i = 0; i < batches_.Size(); ++i)
  336. {
  337. const Vector<SharedPtr<Geometry>>& batchGeometries = geometries_[i];
  338. // If only one LOD geometry, no reason to go through the LOD calculation
  339. if (batchGeometries.Size() <= 1)
  340. continue;
  341. unsigned j;
  342. for (j = 1; j < batchGeometries.Size(); ++j)
  343. {
  344. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  345. break;
  346. }
  347. unsigned newLodLevel = j - 1;
  348. if (geometryData_[i].lodLevel_ != newLodLevel)
  349. {
  350. geometryData_[i].lodLevel_ = newLodLevel;
  351. batches_[i].geometry_ = batchGeometries[newLodLevel];
  352. }
  353. }
  354. }
  355. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  356. {
  357. Model* currentModel = model_;
  358. model_.Reset(); // Set null to allow to be re-set
  359. SetModel(currentModel);
  360. }
  361. }