StaticModel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright (c) 2008-2023 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, DrawableTypes::Geometry),
  24. occlusionLodLevel_(NINDEX),
  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, true, AM_DEFAULT);
  33. URHO3D_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  34. URHO3D_ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList(Material::GetTypeStatic()),
  35. AM_DEFAULT);
  36. URHO3D_ATTRIBUTE("Is Occluder", occluder_, false, AM_DEFAULT);
  37. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, true, AM_DEFAULT);
  38. URHO3D_ATTRIBUTE("Cast Shadows", castShadows_, false, AM_DEFAULT);
  39. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, 0.0f, AM_DEFAULT);
  40. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, 0.0f, AM_DEFAULT);
  41. URHO3D_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, 1.0f, AM_DEFAULT);
  42. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  43. URHO3D_ATTRIBUTE("Occlusion LOD Level", occlusionLodLevel_, NINDEX, AM_DEFAULT);
  44. }
  45. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, Vector<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. i32 hitBatch = NINDEX;
  62. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  63. {
  64. distance = M_INFINITY;
  65. for (i32 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(i32 batchIndex, i32 level)
  118. {
  119. assert(batchIndex >= 0);
  120. assert(level >= 0 || level == NINDEX);
  121. if (batchIndex >= geometries_.Size())
  122. return nullptr;
  123. // If level is out of range, use visible geometry
  124. if (level >= 0 && level < geometries_[batchIndex].Size())
  125. return geometries_[batchIndex][level];
  126. else
  127. return batches_[batchIndex].geometry_;
  128. }
  129. i32 StaticModel::GetNumOccluderTriangles()
  130. {
  131. i32 triangles = 0;
  132. for (i32 i = 0; i < batches_.Size(); ++i)
  133. {
  134. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  135. if (!geometry)
  136. continue;
  137. // Check that the material is suitable for occlusion (default material always is)
  138. Material* mat = batches_[i].material_;
  139. if (mat && !mat->GetOcclusion())
  140. continue;
  141. triangles += geometry->GetIndexCount() / 3;
  142. }
  143. return triangles;
  144. }
  145. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  146. {
  147. for (unsigned i = 0; i < batches_.Size(); ++i)
  148. {
  149. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  150. if (!geometry)
  151. continue;
  152. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  153. Material* material = batches_[i].material_;
  154. if (material)
  155. {
  156. if (!material->GetOcclusion())
  157. continue;
  158. buffer->SetCullMode(material->GetCullMode());
  159. }
  160. else
  161. buffer->SetCullMode(CULL_CCW);
  162. const byte* vertexData;
  163. i32 vertexSize;
  164. const byte* indexData;
  165. i32 indexSize;
  166. const Vector<VertexElement>* elements;
  167. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  168. // Check for valid geometry data
  169. if (!vertexData || !indexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  170. continue;
  171. unsigned indexStart = geometry->GetIndexStart();
  172. unsigned indexCount = geometry->GetIndexCount();
  173. // Draw and check for running out of triangles
  174. if (!buffer->AddTriangles(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  175. return false;
  176. }
  177. return true;
  178. }
  179. void StaticModel::SetModel(Model* model)
  180. {
  181. if (model == model_)
  182. return;
  183. if (!node_)
  184. {
  185. URHO3D_LOGERROR("Can not set model while model component is not attached to a scene node");
  186. return;
  187. }
  188. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  189. if (model_)
  190. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  191. model_ = model;
  192. if (model)
  193. {
  194. SubscribeToEvent(model, E_RELOADFINISHED, URHO3D_HANDLER(StaticModel, HandleModelReloadFinished));
  195. // Copy the subgeometry & LOD level structure
  196. SetNumGeometries(model->GetNumGeometries());
  197. const Vector<Vector<SharedPtr<Geometry>>>& geometries = model->GetGeometries();
  198. const Vector<Vector3>& geometryCenters = model->GetGeometryCenters();
  199. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : nullptr;
  200. for (unsigned i = 0; i < geometries.Size(); ++i)
  201. {
  202. batches_[i].worldTransform_ = worldTransform;
  203. geometries_[i] = geometries[i];
  204. geometryData_[i].center_ = geometryCenters[i];
  205. }
  206. SetBoundingBox(model->GetBoundingBox());
  207. ResetLodLevels();
  208. }
  209. else
  210. {
  211. SetNumGeometries(0);
  212. SetBoundingBox(BoundingBox());
  213. }
  214. MarkNetworkUpdate();
  215. }
  216. void StaticModel::SetMaterial(Material* material)
  217. {
  218. for (unsigned i = 0; i < batches_.Size(); ++i)
  219. batches_[i].material_ = material;
  220. MarkNetworkUpdate();
  221. }
  222. bool StaticModel::SetMaterial(unsigned index, Material* material)
  223. {
  224. if (index >= batches_.Size())
  225. {
  226. URHO3D_LOGERROR("Material index out of bounds");
  227. return false;
  228. }
  229. batches_[index].material_ = material;
  230. MarkNetworkUpdate();
  231. return true;
  232. }
  233. void StaticModel::SetOcclusionLodLevel(i32 level)
  234. {
  235. assert(level >= 0 || level == NINDEX);
  236. occlusionLodLevel_ = level;
  237. MarkNetworkUpdate();
  238. }
  239. void StaticModel::ApplyMaterialList(const String& fileName)
  240. {
  241. String useFileName = fileName;
  242. if (useFileName.Trimmed().Empty() && model_)
  243. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  244. auto* cache = GetSubsystem<ResourceCache>();
  245. SharedPtr<File> file = cache->GetFile(useFileName, false);
  246. if (!file)
  247. return;
  248. unsigned index = 0;
  249. while (!file->IsEof() && index < batches_.Size())
  250. {
  251. auto* material = cache->GetResource<Material>(file->ReadLine());
  252. if (material)
  253. SetMaterial(index, material);
  254. ++index;
  255. }
  256. }
  257. Material* StaticModel::GetMaterial(unsigned index) const
  258. {
  259. return index < batches_.Size() ? batches_[index].material_ : nullptr;
  260. }
  261. bool StaticModel::IsInside(const Vector3& point) const
  262. {
  263. if (!node_)
  264. return false;
  265. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  266. return IsInsideLocal(localPosition);
  267. }
  268. bool StaticModel::IsInsideLocal(const Vector3& point) const
  269. {
  270. // Early-out if point is not inside bounding box
  271. if (boundingBox_.IsInside(point) == OUTSIDE)
  272. return false;
  273. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  274. for (unsigned i = 0; i < batches_.Size(); ++i)
  275. {
  276. Geometry* geometry = batches_[i].geometry_;
  277. if (geometry)
  278. {
  279. if (geometry->IsInside(localRay))
  280. return true;
  281. }
  282. }
  283. return false;
  284. }
  285. void StaticModel::SetBoundingBox(const BoundingBox& box)
  286. {
  287. boundingBox_ = box;
  288. OnMarkedDirty(node_);
  289. }
  290. void StaticModel::SetNumGeometries(unsigned num)
  291. {
  292. batches_.Resize(num);
  293. geometries_.Resize(num);
  294. geometryData_.Resize(num);
  295. ResetLodLevels();
  296. }
  297. void StaticModel::SetModelAttr(const ResourceRef& value)
  298. {
  299. auto* cache = GetSubsystem<ResourceCache>();
  300. SetModel(cache->GetResource<Model>(value.name_));
  301. }
  302. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  303. {
  304. auto* cache = GetSubsystem<ResourceCache>();
  305. for (unsigned i = 0; i < value.names_.Size(); ++i)
  306. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  307. }
  308. ResourceRef StaticModel::GetModelAttr() const
  309. {
  310. return GetResourceRef(model_, Model::GetTypeStatic());
  311. }
  312. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  313. {
  314. materialsAttr_.names_.Resize(batches_.Size());
  315. for (unsigned i = 0; i < batches_.Size(); ++i)
  316. materialsAttr_.names_[i] = GetResourceName(GetMaterial(i));
  317. return materialsAttr_;
  318. }
  319. void StaticModel::OnWorldBoundingBoxUpdate()
  320. {
  321. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  322. }
  323. void StaticModel::ResetLodLevels()
  324. {
  325. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  326. for (unsigned i = 0; i < batches_.Size(); ++i)
  327. {
  328. if (!geometries_[i].Size())
  329. geometries_[i].Resize(1);
  330. batches_[i].geometry_ = geometries_[i][0];
  331. geometryData_[i].lodLevel_ = 0;
  332. }
  333. // Find out the real LOD levels on next geometry update
  334. lodDistance_ = M_INFINITY;
  335. }
  336. void StaticModel::CalculateLodLevels()
  337. {
  338. for (unsigned i = 0; i < batches_.Size(); ++i)
  339. {
  340. const Vector<SharedPtr<Geometry>>& batchGeometries = geometries_[i];
  341. // If only one LOD geometry, no reason to go through the LOD calculation
  342. if (batchGeometries.Size() <= 1)
  343. continue;
  344. unsigned j;
  345. for (j = 1; j < batchGeometries.Size(); ++j)
  346. {
  347. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  348. break;
  349. }
  350. unsigned newLodLevel = j - 1;
  351. if (geometryData_[i].lodLevel_ != newLodLevel)
  352. {
  353. geometryData_[i].lodLevel_ = newLodLevel;
  354. batches_[i].geometry_ = batchGeometries[newLodLevel];
  355. }
  356. }
  357. }
  358. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  359. {
  360. Model* currentModel = model_;
  361. model_.Reset(); // Set null to allow to be re-set
  362. SetModel(currentModel);
  363. }
  364. }