StaticModel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Batch.h"
  25. #include "Camera.h"
  26. #include "Context.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Material.h"
  30. #include "Model.h"
  31. #include "OcclusionBuffer.h"
  32. #include "OctreeQuery.h"
  33. #include "Profiler.h"
  34. #include "ResourceCache.h"
  35. #include "ResourceEvents.h"
  36. #include "StaticModel.h"
  37. #include "XMLElement.h"
  38. #include "DebugNew.h"
  39. static const Vector3 DOT_SCALE(1 / 3.0f, 1 / 3.0f, 1 / 3.0f);
  40. OBJECTTYPESTATIC(StaticModel);
  41. StaticModel::StaticModel(Context* context) :
  42. Drawable(context),
  43. softwareLodLevel_(M_MAX_UNSIGNED)
  44. {
  45. drawableFlags_ = DRAWABLE_GEOMETRY;
  46. materialsAttr_.type_ = Material::GetTypeStatic();
  47. }
  48. StaticModel::~StaticModel()
  49. {
  50. }
  51. void StaticModel::RegisterObject(Context* context)
  52. {
  53. context->RegisterFactory<StaticModel>();
  54. ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  55. REF_ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREFLIST, "Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  56. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  57. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  58. ACCESSOR_ATTRIBUTE(StaticModel, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  59. ATTRIBUTE(StaticModel, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  60. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  61. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  62. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  63. COPY_BASE_ATTRIBUTES(StaticModel, Drawable);
  64. ATTRIBUTE(StaticModel, VAR_INT, "Ray/Occl. LOD Level", softwareLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  65. }
  66. void StaticModel::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  67. {
  68. RayQueryLevel level = query.level_;
  69. switch (level)
  70. {
  71. case RAY_AABB_NOSUBOBJECTS:
  72. case RAY_AABB:
  73. Drawable::ProcessRayQuery(query, results);
  74. break;
  75. case RAY_OBB:
  76. {
  77. Matrix3x4 inverse(GetWorldTransform().Inverse());
  78. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  79. float distance = localRay.HitDistance(boundingBox_);
  80. if (distance <= query.maxDistance_)
  81. {
  82. RayQueryResult result;
  83. result.drawable_ = this;
  84. result.node_ = GetNode();
  85. result.distance_ = distance;
  86. result.subObject_ = M_MAX_UNSIGNED;
  87. results.Push(result);
  88. }
  89. }
  90. break;
  91. case RAY_TRIANGLE:
  92. {
  93. // Do a pretest using the OBB
  94. Matrix3x4 inverse(GetWorldTransform().Inverse());
  95. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  96. float distance = localRay.HitDistance(boundingBox_);
  97. if (distance <= query.maxDistance_)
  98. {
  99. // Then the actual test using triangle geometry
  100. for (unsigned i = 0; i < batches_.Size(); ++i)
  101. {
  102. unsigned lodLevel;
  103. // Check whether to use same LOD as visible, or a specific LOD
  104. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  105. lodLevel = batches_[i].lodLevel_;
  106. else
  107. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[i].Size());
  108. Geometry* geom = geometries_[i][lodLevel];
  109. if (geom)
  110. {
  111. distance = geom->GetDistance(localRay);
  112. if (distance <= query.maxDistance_)
  113. {
  114. RayQueryResult result;
  115. result.drawable_ = this;
  116. result.node_ = GetNode();
  117. result.distance_ = distance;
  118. result.subObject_ = M_MAX_UNSIGNED;
  119. results.Push(result);
  120. break;
  121. }
  122. }
  123. }
  124. }
  125. }
  126. break;
  127. }
  128. }
  129. void StaticModel::UpdateDistance(const FrameInfo& frame)
  130. {
  131. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  132. distance_ = frame.camera_->GetDistance(worldTransform.Translation());
  133. if (batches_.Size() > 1)
  134. {
  135. for (unsigned i = 0; i < batches_.Size(); ++i)
  136. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * batches_[i].center_);
  137. }
  138. else
  139. batches_[0].distance_ = distance_;
  140. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  141. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  142. if (newLodDistance != lodDistance_)
  143. {
  144. lodDistance_ = newLodDistance;
  145. CalculateLodLevels();
  146. }
  147. }
  148. unsigned StaticModel::GetNumBatches()
  149. {
  150. return batches_.Size();
  151. }
  152. void StaticModel::GetBatch(Batch& batch, const FrameInfo& frame, unsigned batchIndex)
  153. {
  154. StaticModelBatch& srcBatch = batches_[batchIndex];
  155. batch.distance_ = srcBatch.distance_;
  156. batch.geometry_ = srcBatch.geometry_;
  157. batch.worldTransform_ = &node_->GetWorldTransform();
  158. batch.material_ = srcBatch.material_;
  159. }
  160. unsigned StaticModel::GetNumOccluderTriangles()
  161. {
  162. unsigned triangles = 0;
  163. for (unsigned i = 0; i < batches_.Size(); ++i)
  164. {
  165. unsigned lodLevel;
  166. // Check whether to use same LOD as visible, or a specific LOD
  167. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  168. lodLevel = batches_[i].lodLevel_;
  169. else
  170. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[i].Size());
  171. Geometry* geom = geometries_[i][lodLevel];
  172. if (!geom)
  173. continue;
  174. // Check that the material is suitable for occlusion (default material always is)
  175. Material* mat = batches_[i].material_;
  176. if (mat && !mat->GetOcclusion())
  177. continue;
  178. triangles += geom->GetIndexCount() / 3;
  179. }
  180. return triangles;
  181. }
  182. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  183. {
  184. bool success = true;
  185. for (unsigned i = 0; i < batches_.Size(); ++i)
  186. {
  187. unsigned lodLevel;
  188. // Check whether to use same LOD as visible, or a specific LOD
  189. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  190. lodLevel = batches_[i].lodLevel_;
  191. else
  192. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[i].Size());
  193. Geometry* geom = geometries_[i][lodLevel];
  194. if (!geom)
  195. continue;
  196. // Check that the material is suitable for occlusion (default material always is)
  197. // and set culling mode
  198. Material* mat = batches_[i].material_;
  199. if (mat)
  200. {
  201. if (!mat->GetOcclusion())
  202. continue;
  203. buffer->SetCullMode(mat->GetCullMode());
  204. }
  205. else
  206. buffer->SetCullMode(CULL_CCW);
  207. const unsigned char* vertexData;
  208. unsigned vertexSize;
  209. const unsigned char* indexData;
  210. unsigned indexSize;
  211. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  212. // Check for valid geometry data
  213. if (!vertexData || !indexData)
  214. continue;
  215. unsigned indexStart = geom->GetIndexStart();
  216. unsigned indexCount = geom->GetIndexCount();
  217. // Draw and check for running out of triangles
  218. if (!buffer->Draw(GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  219. success = false;
  220. if (!success)
  221. break;
  222. }
  223. return success;
  224. }
  225. void StaticModel::SetModel(Model* model)
  226. {
  227. if (!model || model == model_)
  228. return;
  229. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  230. if (model_)
  231. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  232. if (model)
  233. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(StaticModel, HandleModelReloadFinished));
  234. model_ = model;
  235. // Copy the subgeometry & LOD level structure
  236. SetNumGeometries(model->GetNumGeometries());
  237. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  238. const PODVector<Vector3>& geometryCenters = model->GetGeometryCenters();
  239. for (unsigned i = 0; i < geometries.Size(); ++i)
  240. {
  241. geometries_[i] = geometries[i];
  242. batches_[i].center_ = geometryCenters[i];
  243. }
  244. SetBoundingBox(model->GetBoundingBox());
  245. ResetLodLevels();
  246. MarkNetworkUpdate();
  247. }
  248. void StaticModel::SetMaterial(Material* material)
  249. {
  250. for (unsigned i = 0; i < batches_.Size(); ++i)
  251. batches_[i].material_ = material;
  252. MarkNetworkUpdate();
  253. }
  254. bool StaticModel::SetMaterial(unsigned index, Material* material)
  255. {
  256. if (index >= batches_.Size())
  257. {
  258. LOGERROR("Material index out of bounds");
  259. return false;
  260. }
  261. batches_[index].material_ = material;
  262. MarkNetworkUpdate();
  263. return true;
  264. }
  265. void StaticModel::SetSoftwareLodLevel(unsigned level)
  266. {
  267. softwareLodLevel_ = level;
  268. MarkNetworkUpdate();
  269. }
  270. Material* StaticModel::GetMaterial(unsigned index) const
  271. {
  272. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  273. }
  274. void StaticModel::SetBoundingBox(const BoundingBox& box)
  275. {
  276. boundingBox_ = box;
  277. OnMarkedDirty(node_);
  278. }
  279. void StaticModel::SetNumGeometries(unsigned num)
  280. {
  281. batches_.Resize(num);
  282. geometries_.Resize(num);
  283. ResetLodLevels();
  284. }
  285. void StaticModel::SetModelAttr(ResourceRef value)
  286. {
  287. ResourceCache* cache = GetSubsystem<ResourceCache>();
  288. SetModel(cache->GetResource<Model>(value.id_));
  289. }
  290. void StaticModel::SetMaterialsAttr(const ResourceRefList& value)
  291. {
  292. ResourceCache* cache = GetSubsystem<ResourceCache>();
  293. for (unsigned i = 0; i < value.ids_.Size(); ++i)
  294. SetMaterial(i, cache->GetResource<Material>(value.ids_[i]));
  295. }
  296. ResourceRef StaticModel::GetModelAttr() const
  297. {
  298. return GetResourceRef(model_, Model::GetTypeStatic());
  299. }
  300. const ResourceRefList& StaticModel::GetMaterialsAttr() const
  301. {
  302. materialsAttr_.ids_.Resize(batches_.Size());
  303. for (unsigned i = 0; i < batches_.Size(); ++i)
  304. materialsAttr_.ids_[i] = batches_[i].material_ ? batches_[i].material_->GetNameHash() : StringHash();
  305. return materialsAttr_;
  306. }
  307. void StaticModel::OnWorldBoundingBoxUpdate()
  308. {
  309. worldBoundingBox_ = boundingBox_.Transformed(GetWorldTransform());
  310. }
  311. void StaticModel::ResetLodLevels()
  312. {
  313. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  314. for (unsigned i = 0; i < batches_.Size(); ++i)
  315. {
  316. if (!geometries_[i].Size())
  317. geometries_[i].Resize(1);
  318. batches_[i].geometry_ = geometries_[i][0];
  319. batches_[i].lodLevel_ = 0;
  320. }
  321. // Find out the real LOD levels on next geometry update
  322. lodDistance_ = M_INFINITY;
  323. }
  324. void StaticModel::CalculateLodLevels()
  325. {
  326. for (unsigned i = 0; i < batches_.Size(); ++i)
  327. {
  328. unsigned j;
  329. for (j = 1; j < geometries_[i].Size(); ++j)
  330. {
  331. if (geometries_[i][j] && lodDistance_ <= geometries_[i][j]->GetLodDistance())
  332. break;
  333. }
  334. batches_[i].lodLevel_ = j - 1;
  335. batches_[i].geometry_ = geometries_[i][j - 1];
  336. }
  337. }
  338. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  339. {
  340. Model* currentModel = model_;
  341. model_ = 0; // Set null to allow to be re-set
  342. SetModel(currentModel);
  343. }