StaticModel.cpp 11 KB

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