StaticModel.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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. }
  47. StaticModel::~StaticModel()
  48. {
  49. }
  50. void StaticModel::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<StaticModel>();
  53. ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREF, "Model", GetModelAttr, SetModelAttr, ResourceRef, ResourceRef(Model::GetTypeStatic()), AM_DEFAULT);
  54. ACCESSOR_ATTRIBUTE(StaticModel, VAR_RESOURCEREFLIST, "Material", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  55. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Visible", visible_, true, AM_DEFAULT);
  56. ATTRIBUTE(StaticModel, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  57. ATTRIBUTE(StaticModel, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  58. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  60. ACCESSOR_ATTRIBUTE(StaticModel, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  61. COPY_BASE_ATTRIBUTES(StaticModel, Drawable);
  62. ATTRIBUTE(StaticModel, VAR_INT, "Ray/Occl. LOD Level", softwareLodLevel_, M_MAX_UNSIGNED, AM_DEFAULT);
  63. }
  64. void StaticModel::ProcessRayQuery(RayOctreeQuery& query, float initialDistance)
  65. {
  66. PROFILE(RaycastStaticModel);
  67. RayQueryLevel level = query.level_;
  68. switch (level)
  69. {
  70. case RAY_AABB_NOSUBOBJECTS:
  71. case RAY_AABB:
  72. {
  73. RayQueryResult result;
  74. result.drawable_ = this;
  75. result.node_ = GetNode();
  76. result.distance_ = initialDistance;
  77. query.result_.Push(result);
  78. }
  79. break;
  80. case RAY_OBB:
  81. {
  82. Matrix3x4 inverse(GetWorldTransform().Inverse());
  83. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  84. float distance = localRay.HitDistance(boundingBox_);
  85. if (distance < query.maxDistance_)
  86. {
  87. RayQueryResult result;
  88. result.drawable_ = this;
  89. result.node_ = GetNode();
  90. result.distance_ = distance;
  91. query.result_.Push(result);
  92. }
  93. }
  94. break;
  95. case RAY_TRIANGLE:
  96. {
  97. // Do a pretest using the OBB
  98. Matrix3x4 inverse(GetWorldTransform().Inverse());
  99. Ray localRay(inverse * query.ray_.origin_, inverse * Vector4(query.ray_.direction_, 0.0f));
  100. float distance = localRay.HitDistance(boundingBox_);
  101. if (distance < query.maxDistance_)
  102. {
  103. // Then the actual test using triangle geometry
  104. for (unsigned i = 0; i < geometries_.Size(); ++i)
  105. {
  106. unsigned lodLevel;
  107. // Check whether to use same LOD as visible, or a specific LOD
  108. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  109. lodLevel = lodLevels_[i];
  110. else
  111. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[i].Size());
  112. Geometry* geom = geometries_[i][lodLevel];
  113. if (geom)
  114. {
  115. distance = geom->GetDistance(localRay);
  116. if (distance < query.maxDistance_)
  117. {
  118. RayQueryResult result;
  119. result.drawable_ = this;
  120. result.node_ = GetNode();
  121. result.distance_ = distance;
  122. query.result_.Push(result);
  123. break;
  124. }
  125. }
  126. }
  127. }
  128. }
  129. break;
  130. }
  131. }
  132. void StaticModel::UpdateDistance(const FrameInfo& frame)
  133. {
  134. const Matrix3x4& worldTransform = GetWorldTransform();
  135. distance_ = frame.camera_->GetDistance(worldTransform.Translation());
  136. for (unsigned i = 0; i < geometryCenters_.Size(); ++i)
  137. geometryDistances_[i] = frame.camera_->GetDistance(worldTransform * geometryCenters_[i]);
  138. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  139. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  140. if (newLodDistance != lodDistance_)
  141. {
  142. lodDistance_ = newLodDistance;
  143. CalculateLodLevels();
  144. }
  145. }
  146. unsigned StaticModel::GetNumBatches()
  147. {
  148. return geometries_.Size();
  149. }
  150. void StaticModel::GetBatch(Batch& batch, const FrameInfo& frame, unsigned batchIndex)
  151. {
  152. batch.distance_ = geometryDistances_[batchIndex];
  153. batch.geometry_ = geometries_[batchIndex][lodLevels_[batchIndex]];
  154. batch.worldTransform_ = &GetWorldTransform();
  155. batch.material_ = materials_[batchIndex];
  156. }
  157. unsigned StaticModel::GetNumOccluderTriangles()
  158. {
  159. unsigned triangles = 0;
  160. for (unsigned i = 0; i < geometries_.Size(); ++i)
  161. {
  162. unsigned lodLevel;
  163. // Check whether to use same LOD as visible, or a specific LOD
  164. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  165. lodLevel = lodLevels_[i];
  166. else
  167. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[i].Size());
  168. Geometry* geom = geometries_[i][lodLevel];
  169. if (!geom)
  170. continue;
  171. // Check that the material is suitable for occlusion (default material always is)
  172. Material* mat = materials_[i];
  173. if (mat && !mat->GetOcclusion())
  174. continue;
  175. triangles += geom->GetIndexCount() / 3;
  176. }
  177. return triangles;
  178. }
  179. bool StaticModel::DrawOcclusion(OcclusionBuffer* buffer)
  180. {
  181. bool success = true;
  182. for (unsigned i = 0; i < geometries_.Size(); ++i)
  183. {
  184. unsigned lodLevel;
  185. // Check whether to use same LOD as visible, or a specific LOD
  186. if (softwareLodLevel_ == M_MAX_UNSIGNED)
  187. lodLevel = lodLevels_[i];
  188. else
  189. lodLevel = Clamp(softwareLodLevel_, 0, geometries_[i].Size());
  190. Geometry* geom = geometries_[i][lodLevel];
  191. if (!geom)
  192. continue;
  193. // Check that the material is suitable for occlusion (default material always is)
  194. // and set culling mode
  195. Material* mat = materials_[i];
  196. if (mat)
  197. {
  198. if (!mat->GetOcclusion())
  199. continue;
  200. buffer->SetCullMode(mat->GetCullMode());
  201. }
  202. else
  203. buffer->SetCullMode(CULL_CCW);
  204. const unsigned char* vertexData;
  205. unsigned vertexSize;
  206. const unsigned char* indexData;
  207. unsigned indexSize;
  208. geom->GetRawData(vertexData, vertexSize, indexData, indexSize);
  209. // Check for valid geometry data
  210. if (!vertexData || !indexData)
  211. continue;
  212. unsigned indexStart = geom->GetIndexStart();
  213. unsigned indexCount = geom->GetIndexCount();
  214. // Draw and check for running out of triangles
  215. if (!buffer->Draw(GetWorldTransform(), vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  216. success = false;
  217. if (!success)
  218. break;
  219. }
  220. return success;
  221. }
  222. void StaticModel::SetModel(Model* model)
  223. {
  224. if (!model || model == model_)
  225. return;
  226. // Unsubscribe from the reload event of previous model (if any), then subscribe to the new
  227. if (model_)
  228. UnsubscribeFromEvent(model_, E_RELOADFINISHED);
  229. if (model)
  230. SubscribeToEvent(model, E_RELOADFINISHED, HANDLER(StaticModel, HandleModelReloadFinished));
  231. model_ = model;
  232. // Copy the subgeometry & LOD level structure
  233. SetNumGeometries(model->GetNumGeometries());
  234. const Vector<Vector<SharedPtr<Geometry> > >& geometries = model->GetGeometries();
  235. for (unsigned i = 0; i < geometries.Size(); ++i)
  236. geometries_[i] = geometries[i];
  237. geometryCenters_ = model->GetGeometryCenters();
  238. geometryDistances_.Resize(geometryCenters_.Size());
  239. SetBoundingBox(model->GetBoundingBox());
  240. ResetLodLevels();
  241. }
  242. void StaticModel::SetMaterial(Material* material)
  243. {
  244. for (unsigned i = 0; i < materials_.Size(); ++i)
  245. materials_[i] = material;
  246. }
  247. bool StaticModel::SetMaterial(unsigned index, Material* material)
  248. {
  249. if (index >= materials_.Size())
  250. {
  251. LOGERROR("Material index out of bounds");
  252. return false;
  253. }
  254. materials_[index] = material;
  255. return true;
  256. }
  257. void StaticModel::SetSoftwareLodLevel(unsigned level)
  258. {
  259. softwareLodLevel_ = level;
  260. }
  261. Material* StaticModel::GetMaterial(unsigned index) const
  262. {
  263. return index < materials_.Size() ? materials_[index] : (Material*)0;
  264. }
  265. void StaticModel::SetBoundingBox(const BoundingBox& box)
  266. {
  267. boundingBox_ = box;
  268. OnMarkedDirty(node_);
  269. }
  270. void StaticModel::SetNumGeometries(unsigned num)
  271. {
  272. geometries_.Resize(num);
  273. materials_.Resize(num);
  274. ResetLodLevels();
  275. }
  276. void StaticModel::SetModelAttr(ResourceRef value)
  277. {
  278. ResourceCache* cache = GetSubsystem<ResourceCache>();
  279. SetModel(cache->GetResource<Model>(value.id_));
  280. }
  281. void StaticModel::SetMaterialsAttr(ResourceRefList value)
  282. {
  283. ResourceCache* cache = GetSubsystem<ResourceCache>();
  284. for (unsigned i = 0; i < value.ids_.Size(); ++i)
  285. SetMaterial(i, cache->GetResource<Material>(value.ids_[i]));
  286. }
  287. ResourceRef StaticModel::GetModelAttr() const
  288. {
  289. return GetResourceRef(model_, Model::GetTypeStatic());
  290. }
  291. ResourceRefList StaticModel::GetMaterialsAttr() const
  292. {
  293. return GetResourceRefList(materials_);
  294. }
  295. void StaticModel::OnWorldBoundingBoxUpdate()
  296. {
  297. worldBoundingBox_ = boundingBox_.Transformed(GetWorldTransform());
  298. }
  299. void StaticModel::ResetLodLevels()
  300. {
  301. // Ensure that each subgeometry has at least one LOD level, and reset the current LOD level
  302. lodLevels_.Resize(geometries_.Size());
  303. for (unsigned i = 0; i < geometries_.Size(); ++i)
  304. {
  305. if (!geometries_[i].Size())
  306. geometries_[i].Resize(1);
  307. lodLevels_[i] = 0;
  308. }
  309. // Find out the real LOD levels on next geometry update
  310. lodDistance_ = M_INFINITY;
  311. }
  312. void StaticModel::CalculateLodLevels()
  313. {
  314. for (unsigned i = 0; i < geometries_.Size(); ++i)
  315. {
  316. unsigned j;
  317. for (j = 1; j < geometries_[i].Size(); ++j)
  318. {
  319. if (geometries_[i][j] && lodDistance_ <= geometries_[i][j]->GetLodDistance())
  320. break;
  321. }
  322. lodLevels_[i] = j - 1;
  323. }
  324. }
  325. void StaticModel::HandleModelReloadFinished(StringHash eventType, VariantMap& eventData)
  326. {
  327. Model* currentModel = model_;
  328. model_ = 0; // Set null to allow to be re-set
  329. SetModel(currentModel);
  330. }