StaticModel.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. //
  2. // Copyright (c) 2008-2015 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 "../Atomic3D/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 "../IO/FileSystem.h"
  33. #include "../IO/Log.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Resource/ResourceEvents.h"
  36. #include "../DebugNew.h"
  37. namespace Atomic
  38. {
  39. extern const char* GEOMETRY_CATEGORY;
  40. StaticModel::StaticModel(Context* context) :
  41. Drawable(context, DRAWABLE_GEOMETRY),
  42. occlusionLodLevel_(M_MAX_UNSIGNED),
  43. materialsAttr_(Material::GetTypeStatic())
  44. {
  45. }
  46. StaticModel::~StaticModel()
  47. {
  48. }
  49. void StaticModel::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<StaticModel>(GEOMETRY_CATEGORY);
  52. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  53. MIXED_ACCESSOR_ATTRIBUTE("Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  54. ACCESSOR_ATTRIBUTE("Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()),
  55. AM_DEFAULT);
  56. ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  57. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  58. ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  60. ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  61. ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  62. COPY_BASE_ATTRIBUTES(Drawable);
  63. ATTRIBUTE("Occlusion LOD Level", int, occlusionLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  64. // ATOMIC BEGIN
  65. ACCESSOR_ATTRIBUTE("Geometry Enabled", GetGeometryEnabledAttr, SetGeometryEnabledAttr, VariantVector,
  66. Variant::emptyVariantVector, AM_FILE | AM_NOEDIT);
  67. // ATOMIC END
  68. }
  69. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  70. {
  71. RayQueryLevel level = query.level_;
  72. switch (level)
  73. {
  74. case RAY_AABB:
  75. Drawable::ProcessRayQuery(query, results);
  76. break;
  77. case RAY_OBB:
  78. case RAY_TRIANGLE:
  79. case RAY_TRIANGLE_UV:
  80. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  81. Ray localRay = query.ray_.Transformed(inverse);
  82. float distance = localRay.HitDistance(boundingBox_);
  83. Vector3 normal = -query.ray_.direction_;
  84. Vector2 geometryUV;
  85. unsigned hitBatch = M_MAX_UNSIGNED;
  86. if (level >= RAY_TRIANGLE && distance < query.maxDistance_)
  87. {
  88. distance = M_INFINITY;
  89. for (unsigned i = 0; i < batches_.Size(); ++i)
  90. {
  91. Geometry* geometry = batches_[i].geometry_;
  92. if (geometry)
  93. {
  94. Vector3 geometryNormal;
  95. float geometryDistance = level == RAY_TRIANGLE ? geometry->GetHitDistance(localRay, &geometryNormal) :
  96. geometry->GetHitDistance(localRay, &geometryNormal, &geometryUV);
  97. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  98. {
  99. distance = geometryDistance;
  100. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  101. hitBatch = i;
  102. }
  103. }
  104. }
  105. }
  106. if (distance < query.maxDistance_)
  107. {
  108. RayQueryResult result;
  109. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  110. result.normal_ = normal;
  111. result.textureUV_ = geometryUV;
  112. result.distance_ = distance;
  113. result.drawable_ = this;
  114. result.node_ = node_;
  115. result.subObject_ = hitBatch;
  116. results.Push(result);
  117. }
  118. break;
  119. }
  120. }
  121. void StaticModel::UpdateBatches(const FrameInfo& frame)
  122. {
  123. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  124. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  125. if (batches_.Size() == 1)
  126. batches_[0].distance_ = distance_;
  127. else
  128. {
  129. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  130. for (unsigned i = 0; i < batches_.Size(); ++i)
  131. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  132. }
  133. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  134. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  135. if (newLodDistance != lodDistance_)
  136. {
  137. lodDistance_ = newLodDistance;
  138. CalculateLodLevels();
  139. }
  140. }
  141. Geometry* StaticModel::GetLodGeometry(unsigned batchIndex, unsigned level)
  142. {
  143. if (batchIndex >= geometries_.Size())
  144. return 0;
  145. // If level is out of range, use visible geometry
  146. if (level < geometries_[batchIndex].Size())
  147. return geometries_[batchIndex][level];
  148. else
  149. return batches_[batchIndex].geometry_;
  150. }
  151. unsigned StaticModel::GetNumOccluderTriangles()
  152. {
  153. unsigned triangles = 0;
  154. for (unsigned i = 0; i < batches_.Size(); ++i)
  155. {
  156. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  157. if (!geometry)
  158. continue;
  159. // Check that the material is suitable for occlusion (default material always is)
  160. Material* mat = batches_[i].material_;
  161. if (mat && !mat->GetOcclusion())
  162. continue;
  163. triangles += geometry->GetIndexCount() / 3;
  164. }
  165. return triangles;
  166. }
  167. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  168. {
  169. for (unsigned i = 0; i < batches_.Size(); ++i)
  170. {
  171. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  172. if (!geometry)
  173. continue;
  174. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  175. Material* material = batches_[i].material_;
  176. if (material)
  177. {
  178. if (!material->GetOcclusion())
  179. continue;
  180. buffer->SetCullMode(material->GetCullMode());
  181. }
  182. else
  183. buffer->SetCullMode(CULL_CCW);
  184. const unsigned char* vertexData;
  185. unsigned vertexSize;
  186. const unsigned char* indexData;
  187. unsigned indexSize;
  188. unsigned elementMask;
  189. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  190. // Check for valid geometry data
  191. if (!vertexData || !indexData)
  192. continue;
  193. unsigned indexStart = geometry->GetIndexStart();
  194. unsigned indexCount = geometry->GetIndexCount();
  195. // Draw and check for running out of triangles
  196. if (!buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  197. return false;
  198. }
  199. return true;
  200. }
  201. void StaticModel::SetModel(Model* model)
  202. {
  203. if (model == model_)
  204. return;
  205. // If script erroneously calls StaticModel::SetModel on an AnimatedModel, warn and redirect
  206. if (GetType() == AnimatedModel::GetTypeStatic())
  207. {
  208. LOGWARNING("StaticModel::SetModel() called on AnimatedModel. Redirecting to AnimatedModel::SetModel()");
  209. AnimatedModel* animatedModel = static_cast<AnimatedModel*>(this);
  210. animatedModel->SetModel(model);
  211. return;
  212. }
  213. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  214. if (model_)
  215. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  216. model_ = model;
  217. if (model)
  218. {
  219. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(StaticModel, HandleModelReloadFinished));
  220. // Copy the subgeometry & LOD level structure
  221. SetNumGeometries(model->GetNumGeometries());
  222. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  223. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  224. const Matrix3x4* worldTransform = node_ ? &node_->GetWorldTransform() : (const Matrix3x4*)0;
  225. for (unsigned i = 0; i < geometries.Size(); ++i)
  226. {
  227. batches_[i].worldTransform_ = worldTransform;
  228. geometries_[i] = geometries[i];
  229. geometryData_[i].center_ = geometryCenters[i];
  230. geometryData_[i].enabled_ = true;
  231. geometryData_[i].batchGeometry_ = 0;
  232. }
  233. SetBoundingBox(model->GetBoundingBox());
  234. ResetLodLevels();
  235. }
  236. else
  237. {
  238. SetNumGeometries(0);
  239. SetBoundingBox(BoundingBox());
  240. }
  241. MarkNetworkUpdate();
  242. }
  243. void StaticModel::SetMaterial(Material* material)
  244. {
  245. for (unsigned i = 0; i < batches_.Size(); ++i)
  246. batches_[i].material_ = material;
  247. MarkNetworkUpdate();
  248. }
  249. bool StaticModel::SetMaterial(unsigned index, Material* material)
  250. {
  251. if (index >= batches_.Size())
  252. {
  253. LOGERROR("Material index out of bounds");
  254. return false;
  255. }
  256. batches_[index].material_ = material;
  257. MarkNetworkUpdate();
  258. return true;
  259. }
  260. void StaticModel::SetOcclusionLodLevel(unsigned level)
  261. {
  262. occlusionLodLevel_ = level;
  263. MarkNetworkUpdate();
  264. }
  265. void StaticModel::ApplyMaterialList(const String& fileName)
  266. {
  267. String useFileName = fileName;
  268. if (useFileName.Trimmed().Empty() && model_)
  269. useFileName = ReplaceExtension(model_->GetName(), ".txt");
  270. ResourceCache* cache = GetSubsystem<ResourceCache>();
  271. SharedPtr<File> file = cache->GetFile(useFileName, false);
  272. if (!file)
  273. return;
  274. unsigned index = 0;
  275. while (!file->IsEof() && index < batches_.Size())
  276. {
  277. Material* material = cache->GetResource<Material>(file->ReadLine());
  278. if (material)
  279. SetMaterial(index, material);
  280. ++index;
  281. }
  282. }
  283. Material* StaticModel::GetMaterial(unsigned index) const
  284. {
  285. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  286. }
  287. bool StaticModel::IsInside(const Vector3& point) const
  288. {
  289. if (!node_)
  290. return false;
  291. Vector3 localPosition = node_->GetWorldTransform().Inverse() * point;
  292. return IsInsideLocal(localPosition);
  293. }
  294. bool StaticModel::IsInsideLocal(const Vector3& point) const
  295. {
  296. // Early-out if point is not inside bounding box
  297. if (boundingBox_.IsInside(point) == OUTSIDE)
  298. return false;
  299. Ray localRay(point, Vector3(1.0f, -1.0f, 1.0f));
  300. for (unsigned i = 0; i < batches_.Size(); ++i)
  301. {
  302. Geometry* geometry = batches_[i].geometry_;
  303. if (geometry)
  304. {
  305. if (geometry->IsInside(localRay))
  306. return true;
  307. }
  308. }
  309. return false;
  310. }
  311. void StaticModel::SetBoundingBox(const BoundingBox& box)
  312. {
  313. boundingBox_ = box;
  314. OnMarkedDirty(node_);
  315. }
  316. void StaticModel::SetNumGeometries(unsigned num)
  317. {
  318. batches_.Resize(num);
  319. geometries_.Resize(num);
  320. geometryData_.Resize(num);
  321. ResetLodLevels();
  322. }
  323. void StaticModel::SetModelAttr(const ResourceRef& value)
  324. {
  325. ResourceCache* cache = GetSubsystem<ResourceCache>();
  326. SetModel(cache->GetResource<Model>(value.name_));
  327. }
  328. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  329. {
  330. ResourceCache* cache = GetSubsystem<ResourceCache>();
  331. for (unsigned i = 0; i < value.names_.Size(); ++i)
  332. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  333. }
  334. ResourceRef StaticModel::GetModelAttr() const
  335. {
  336. return GetResourceRef(model_, Model::GetTypeStatic());
  337. }
  338. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  339. {
  340. materialsAttr_.names_.Resize(batches_.Size());
  341. for (unsigned i = 0; i < batches_.Size(); ++i)
  342. materialsAttr_.names_[i] = GetResourceName(batches_[i].material_);
  343. return materialsAttr_;
  344. }
  345. void StaticModel::OnWorldBoundingBoxUpdate()
  346. {
  347. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  348. }
  349. void StaticModel::ResetLodLevels()
  350. {
  351. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  352. for (unsigned i = 0; i < batches_.Size(); ++i)
  353. {
  354. if (!geometries_[i].Size())
  355. geometries_[i].Resize(1);
  356. batches_[i].geometry_ = geometries_[i][0];
  357. geometryData_[i].lodLevel_ = 0;
  358. }
  359. // Find out the real LOD levels on next geometry update
  360. lodDistance_ = M_INFINITY;
  361. }
  362. void StaticModel::CalculateLodLevels()
  363. {
  364. for (unsigned i = 0; i < batches_.Size(); ++i)
  365. {
  366. const Vector<SharedPtr<Geometry> >& batchGeometries = geometries_[i];
  367. // If only one LOD geometry, no reason to go through the LOD calculation
  368. if (batchGeometries.Size() <= 1)
  369. continue;
  370. unsigned j;
  371. for (j = 1; j < batchGeometries.Size(); ++j)
  372. {
  373. if (batchGeometries[j] && lodDistance_ <= batchGeometries[j]->GetLodDistance())
  374. break;
  375. }
  376. unsigned newLodLevel = j - 1;
  377. if (geometryData_[i].lodLevel_ != newLodLevel)
  378. {
  379. geometryData_[i].lodLevel_ = newLodLevel;
  380. batches_[i].geometry_ = batchGeometries[newLodLevel];
  381. }
  382. }
  383. }
  384. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  385. {
  386. Model* currentModel = model_;
  387. model_.Reset(); // Set null to allow to be re-set
  388. SetModel(currentModel);
  389. }
  390. // ATOMIC BEGIN
  391. bool StaticModel::GetGeometryVisible(const String& name)
  392. {
  393. if (!model_)
  394. return false;
  395. const Vector<String>& names = model_->GetGeometryNames();
  396. for (unsigned i = 0; i < names.Size(); i++)
  397. {
  398. if (name == names[i])
  399. return geometryData_[i].enabled_;
  400. }
  401. return false;
  402. }
  403. void StaticModel::ShowGeometry(const String& name)
  404. {
  405. if (!model_)
  406. return;
  407. const Vector<String>& names = model_->GetGeometryNames();
  408. for (unsigned i = 0; i < names.Size(); i++)
  409. {
  410. if (name == names[i])
  411. geometryData_[i].enabled_ = true;
  412. }
  413. }
  414. void StaticModel::HideGeometry(const String& name)
  415. {
  416. if (!model_)
  417. return;
  418. const Vector<String>& names = model_->GetGeometryNames();
  419. for (unsigned i = 0; i < names.Size(); i++)
  420. {
  421. if (name == names[i])
  422. geometryData_[i].enabled_ = false;
  423. }
  424. }
  425. void StaticModel::SetGeometryEnabledAttr(const VariantVector& value)
  426. {
  427. if (!value.Size() || value.Size() != geometryData_.Size())
  428. {
  429. geometryEnabled_.Clear();
  430. return;
  431. }
  432. bool init = !geometryEnabled_.Size();
  433. geometryEnabled_ = value;
  434. for (unsigned i = 0; i < geometryData_.Size(); i++)
  435. {
  436. geometryData_[i].enabled_ = geometryEnabled_[i].GetBool();
  437. if (init)
  438. geometryData_[i].batchGeometry_ = 0;
  439. }
  440. }
  441. const VariantVector& StaticModel::GetGeometryEnabledAttr() const
  442. {
  443. geometryEnabled_.Resize(geometryData_.Size());
  444. for (unsigned i = 0; i < geometryData_.Size(); i++)
  445. geometryEnabled_[i] = geometryData_[i].enabled_;
  446. return geometryEnabled_;
  447. }
  448. // ATOMIC END
  449. }