StaticModel.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. //
  2. // Copyright (c) 2008-2016 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/AnimatedModel.h"
  26. #include "../Graphics/Batch.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/Material.h"
  30. #include "../Graphics/OcclusionBuffer.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/FileSystem.h"
  34. #include "../IO/Log.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../Resource/ResourceEvents.h"
  37. #include "../DebugNew.h"
  38. namespace Atomic
  39. {
  40. extern const char* GEOMETRY_CATEGORY;
  41. StaticModel::StaticModel(Context* context) :
  42. Drawable(context, DRAWABLE_GEOMETRY),
  43. occlusionLodLevel_(M_MAX_UNSIGNED),
  44. materialsAttr_(Material::GetTypeStatic()),
  45. geometryDisabled_(false)
  46. {
  47. }
  48. StaticModel::~StaticModel()
  49. {
  50. }
  51. void StaticModel::RegisterObject(Context* context)
  52. {
  53. context->RegisterFactory<StaticModel>(GEOMETRY_CATEGORY);
  54. ATOMIC_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  55. ATOMIC_MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  56. ATOMIC_ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  57. AM_DEFAULT);
  58. ATOMIC_ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  59. ATOMIC_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  60. ATOMIC_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  61. ATOMIC_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  62. ATOMIC_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  63. ATOMIC_ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  64. ATOMIC_COPY_BASE_ATTRIBUTES(Drawable);
  65. ATOMIC_ATTRIBUTE("Occlusion LOD Level", int, occlusionLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  66. // ATOMIC BEGIN
  67. ATOMIC_ACCESSOR_ATTRIBUTE("Geometry Enabled", GetGeometryEnabledAttr, SetGeometryEnabledAttr, VariantVector,
  68. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  69. // ATOMIC END
  70. }
  71. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  72. {
  73. RayQueryLevel level = query.level_;
  74. switch (level)
  75. {
  76. case RAY_AABB:
  77. Drawable::ProcessRayQuery(query, results);
  78. break;
  79. case RAY_OBB:
  80. case RAY_TRIANGLE:
  81. case RAY_TRIANGLE_UV:
  82. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  83. Ray localRay = query.ray_.Transformed(inverse);
  84. float distance = localRay.HitDistance(boundingBox_);
  85. Vector3 normal = -query.ray_.direction_;
  86. Vector2 geometryUV;
  87. unsigned hitBatch = M_MAX_UNSIGNED;
  88. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  89. {
  90. distance = M_INFINITY;
  91. for (unsigned i = 0; i < batches_.Size(); ++i)
  92. {
  93. Geometry* geometry = batches_[i].geometry_;
  94. if (geometry)
  95. {
  96. Vector3 geometryNormal;
  97. float geometryDistance = level == RAY_TRIANGLE ? geometry->GetHitDistance(localRay, &geometryNormal) :
  98. geometry->GetHitDistance(localRay, &geometryNormal, &geometryUV);
  99. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  100. {
  101. distance = geometryDistance;
  102. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  103. hitBatch = i;
  104. }
  105. }
  106. }
  107. }
  108. if (distance < query.maxDistance_)
  109. {
  110. RayQueryResult result;
  111. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  112. result.normal_ = normal;
  113. result.textureUV_ = geometryUV;
  114. result.distance_ = distance;
  115. result.drawable_ = this;
  116. result.node_ = node_;
  117. result.subObject_ = hitBatch;
  118. results.Push(result);
  119. }
  120. break;
  121. }
  122. }
  123. void StaticModel::UpdateBatches(const FrameInfo& frame)
  124. {
  125. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  126. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  127. if (batches_.Size() == 1)
  128. batches_[0].distance_ = distance_;
  129. else
  130. {
  131. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  132. for (unsigned i = 0; i < batches_.Size(); ++i)
  133. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  134. }
  135. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  136. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  137. if (newLodDistance != lodDistance_)
  138. {
  139. lodDistance_ = newLodDistance;
  140. CalculateLodLevels();
  141. }
  142. }
  143. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  144. {
  145. if (batchIndex >= geometries_.Size())
  146. return 0;
  147. // If level is out of range, use visible geometry
  148. if (level < geometries_[batchIndex].Size())
  149. return geometries_[batchIndex][level];
  150. else
  151. return batches_[batchIndex].geometry_;
  152. }
  153. unsigned StaticModel::GetNumOccluderTriangles()
  154. {
  155. unsigned triangles = 0;
  156. for (unsigned i = 0; i < batches_.Size(); ++i)
  157. {
  158. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  159. if (!geometry)
  160. continue;
  161. // Check that the material is suitable for occlusion (default material always is)
  162. Material* mat = batches_[i].material_;
  163. if (mat && !mat->GetOcclusion())
  164. continue;
  165. triangles += geometry->GetIndexCount() / 3;
  166. }
  167. return triangles;
  168. }
  169. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  170. {
  171. for (unsigned i = 0; i < batches_.Size(); ++i)
  172. {
  173. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  174. if (!geometry)
  175. continue;
  176. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  177. Material* material = batches_[i].material_;
  178. if (material)
  179. {
  180. if (!material->GetOcclusion())
  181. continue;
  182. buffer->SetCullMode(material->GetCullMode());
  183. }
  184. else
  185. buffer->SetCullMode(CULL_CCW);
  186. const unsigned char* vertexData;
  187. unsigned vertexSize;
  188. const unsigned char* indexData;
  189. unsigned indexSize;
  190. const PODVector<VertexElement>* elements;
  191. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elements);
  192. // Check for valid geometry data
  193. if (!vertexData || !indexData || !elements || VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION) != 0)
  194. continue;
  195. unsigned indexStart = geometry->GetIndexStart();
  196. unsigned indexCount = geometry->GetIndexCount();
  197. // Draw and check for running out of triangles
  198. if (!buffer->AddTriangles(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  199. return false;
  200. }
  201. return true;
  202. }
  203. void StaticModel::SetModel(Model* model)
  204. {
  205. if (model == model_)
  206. return;
  207. // If script erroneously calls StaticModel::SetModel on an AnimatedModel, warn and redirect
  208. if (GetType() == AnimatedModel::GetTypeStatic())
  209. {
  210. ATOMIC_LOGWARNING("StaticModel::SetModel() called on AnimatedModel. Redirecting to AnimatedModel::SetModel()");
  211. AnimatedModel* animatedModel = static_cast<AnimatedModel*>(this);
  212. animatedModel->SetModel(model);
  213. return;
  214. }
  215. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  216. if (model_)
  217. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  218. model_ = model;
  219. if (model)
  220. {
  221. SubscribeToEvent(model, E_RELOADFINISHED, ATOMIC_HANDLER(StaticModel, HandleModelReloadFinished));
  222. // Copy the subgeometry & LOD level structure
  223. SetNumGeometries(model->GetNumGeometries());
  224. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  225. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  226. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : (const Matrix3x4*)0;
  227. for (unsigned i = 0; i < geometries.Size(); ++i)
  228. {
  229. batches_[i].worldTransform_ = worldTransform;
  230. geometries_[i] = geometries[i];
  231. geometryData_[i].center_ = geometryCenters[i];
  232. // ATOMIC BEGIN
  233. geometryData_[i].enabled_ = true;
  234. geometryData_[i].batchGeometry_ = 0;
  235. // ATOMIC END
  236. }
  237. SetBoundingBox(model->GetBoundingBox());
  238. ResetLodLevels();
  239. }
  240. else
  241. {
  242. SetNumGeometries(0);
  243. SetBoundingBox(BoundingBox());
  244. }
  245. MarkNetworkUpdate();
  246. }
  247. void StaticModel::SetMaterial(Material* material)
  248. {
  249. for (unsigned i = 0; i < batches_.Size(); ++i)
  250. batches_[i].material_ = material;
  251. MarkNetworkUpdate();
  252. }
  253. bool StaticModel::SetMaterial(unsigned index, Material* material)
  254. {
  255. if (index >= batches_.Size())
  256. {
  257. ATOMIC_LOGERROR("Material index out of bounds");
  258. return false;
  259. }
  260. batches_[index].material_ = material;
  261. MarkNetworkUpdate();
  262. return true;
  263. }
  264. void StaticModel::SetOcclusionLodLevel(unsigned level)
  265. {
  266. occlusionLodLevel_ = level;
  267. MarkNetworkUpdate();
  268. }
  269. void StaticModel::ApplyMaterialList(const String& fileName)
  270. {
  271. String useFileName = fileName;
  272. if (useFileName.Trimmed().Empty() && model_)
  273. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  274. ResourceCache* cache = GetSubsystem<ResourceCache>();
  275. SharedPtr<File> file = cache->GetFile(useFileName, false);
  276. if (!file)
  277. return;
  278. unsigned index = 0;
  279. while (!file->IsEof() && index < batches_.Size())
  280. {
  281. Material* material = cache->GetResource<Material>(file->ReadLine());
  282. if (material)
  283. SetMaterial(index, material);
  284. ++index;
  285. }
  286. }
  287. Material* StaticModel::GetMaterial(unsigned index) const
  288. {
  289. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  290. }
  291. bool StaticModel::IsInside(const Vector3& point) const
  292. {
  293. if (!node_)
  294. return false;
  295. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  296. return IsInsideLocal(localPosition);
  297. }
  298. bool StaticModel::IsInsideLocal(const Vector3& point) const
  299. {
  300. // Early-out if point is not inside bounding box
  301. if (boundingBox_.IsInside(point) == OUTSIDE)
  302. return false;
  303. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  304. for (unsigned i = 0; i < batches_.Size(); ++i)
  305. {
  306. Geometry* geometry = batches_[i].geometry_;
  307. if (geometry)
  308. {
  309. if (geometry->IsInside(localRay))
  310. return true;
  311. }
  312. }
  313. return false;
  314. }
  315. void StaticModel::SetBoundingBox(const BoundingBox& box)
  316. {
  317. boundingBox_ = box;
  318. OnMarkedDirty(node_);
  319. }
  320. void StaticModel::SetNumGeometries(unsigned num)
  321. {
  322. batches_.Resize(num);
  323. geometries_.Resize(num);
  324. geometryData_.Resize(num);
  325. ResetLodLevels();
  326. }
  327. void StaticModel::SetModelAttr(const ResourceRef& value)
  328. {
  329. ResourceCache* cache = GetSubsystem<ResourceCache>();
  330. SetModel(cache->GetResource<Model>(value.name_));
  331. }
  332. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  333. {
  334. ResourceCache* cache = GetSubsystem<ResourceCache>();
  335. for (unsigned i = 0; i < value.names_.Size(); ++i)
  336. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  337. }
  338. ResourceRef StaticModel::GetModelAttr() const
  339. {
  340. return GetResourceRef(model_, Model::GetTypeStatic());
  341. }
  342. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  343. {
  344. materialsAttr_.names_.Resize(batches_.Size());
  345. for (unsigned i = 0; i < batches_.Size(); ++i)
  346. materialsAttr_.names_[i] = GetResourceName(batches_[i].material_);
  347. return materialsAttr_;
  348. }
  349. void StaticModel::OnWorldBoundingBoxUpdate()
  350. {
  351. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  352. }
  353. void StaticModel::ResetLodLevels()
  354. {
  355. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  356. for (unsigned i = 0; i < batches_.Size(); ++i)
  357. {
  358. if (!geometries_[i].Size())
  359. geometries_[i].Resize(1);
  360. batches_[i].geometry_ = geometries_[i][0];
  361. geometryData_[i].lodLevel_ = 0;
  362. }
  363. // Find out the real LOD levels on next geometry update
  364. lodDistance_ = M_INFINITY;
  365. }
  366. void StaticModel::CalculateLodLevels()
  367. {
  368. for (unsigned i = 0; i < batches_.Size(); ++i)
  369. {
  370. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  371. // If only one LOD geometry, no reason to go through the LOD calculation
  372. if (batchGeometries.Size() <= 1)
  373. continue;
  374. unsigned j;
  375. for (j = 1; j < batchGeometries.Size(); ++j)
  376. {
  377. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  378. break;
  379. }
  380. unsigned newLodLevel = j - 1;
  381. if (geometryData_[i].lodLevel_ != newLodLevel)
  382. {
  383. geometryData_[i].lodLevel_ = newLodLevel;
  384. batches_[i].geometry_ = batchGeometries[newLodLevel];
  385. }
  386. }
  387. }
  388. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  389. {
  390. Model* currentModel = model_;
  391. model_.Reset(); // Set null to allow to be re-set
  392. SetModel(currentModel);
  393. }
  394. // ATOMIC BEGIN
  395. bool StaticModel::GetGeometryVisible(const String& name)
  396. {
  397. if (!model_)
  398. return false;
  399. const Vector<String>& names = model_->GetGeometryNames();
  400. for (unsigned i = 0; i < names.Size(); i++)
  401. {
  402. if (name == names[i])
  403. return geometryData_[i].enabled_;
  404. }
  405. return false;
  406. }
  407. void StaticModel::ShowGeometry(const String& name)
  408. {
  409. if (!model_)
  410. return;
  411. const Vector<String>& names = model_->GetGeometryNames();
  412. for (unsigned i = 0; i < names.Size(); i++)
  413. {
  414. if (name == names[i])
  415. {
  416. if (geometryData_[i].batchGeometry_)
  417. batches_[i].geometry_ = geometryData_[i].batchGeometry_;
  418. geometryData_[i].batchGeometry_ = 0;
  419. geometryData_[i].enabled_ = true;
  420. }
  421. }
  422. geometryDisabled_ = false;
  423. for (unsigned i = 0; i < geometryData_.Size(); i++)
  424. {
  425. if (!geometryData_[i].enabled_)
  426. {
  427. geometryDisabled_ = true;
  428. break;
  429. }
  430. }
  431. }
  432. void StaticModel::HideGeometry(const String& name)
  433. {
  434. if (!model_)
  435. return;
  436. const Vector<String>& names = model_->GetGeometryNames();
  437. for (unsigned i = 0; i < names.Size(); i++)
  438. {
  439. if (name == names[i])
  440. {
  441. geometryDisabled_ = true;
  442. if (batches_[i].geometry_)
  443. geometryData_[i].batchGeometry_ = batches_[i].geometry_;
  444. geometryData_[i].enabled_ = false;
  445. }
  446. }
  447. }
  448. void StaticModel::SetGeometryEnabledAttr(const VariantVector& value)
  449. {
  450. if (!value.Size() || value.Size() != geometryData_.Size())
  451. {
  452. geometryDisabled_ = false;
  453. geometryEnabled_.Clear();
  454. return;
  455. }
  456. bool init = !geometryEnabled_.Size();
  457. geometryEnabled_ = value;
  458. for (unsigned i = 0; i < geometryData_.Size(); i++)
  459. {
  460. geometryData_[i].enabled_ = geometryEnabled_[i].GetBool();
  461. if (!geometryData_[i].enabled_)
  462. geometryDisabled_ = true;
  463. if (init)
  464. geometryData_[i].batchGeometry_ = 0;
  465. }
  466. }
  467. const VariantVector& StaticModel::GetGeometryEnabledAttr() const
  468. {
  469. geometryEnabled_.Resize(geometryData_.Size());
  470. geometryDisabled_ = false;
  471. for (unsigned i = 0; i < geometryData_.Size(); i++)
  472. {
  473. geometryEnabled_[i] = geometryData_[i].enabled_;
  474. if (!geometryData_[i].enabled_)
  475. geometryDisabled_ = true;
  476. }
  477. return geometryEnabled_;
  478. }
  479. // ATOMIC END
  480. }