StaticModelGroup.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //
  2. // Copyright (c) 2008-2013 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 "Batch.h"
  24. #include "Camera.h"
  25. #include "Context.h"
  26. #include "Geometry.h"
  27. #include "Material.h"
  28. #include "OcclusionBuffer.h"
  29. #include "OctreeQuery.h"
  30. #include "Scene.h"
  31. #include "StaticModelGroup.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. extern const char* GEOMETRY_CATEGORY;
  36. StaticModelGroup::StaticModelGroup(Context* context) :
  37. StaticModel(context),
  38. nodeIDsDirty_(false)
  39. {
  40. // Initialize the default node IDs attribute
  41. UpdateNodeIDs();
  42. }
  43. StaticModelGroup::~StaticModelGroup()
  44. {
  45. }
  46. void StaticModelGroup::RegisterObject(Context* context)
  47. {
  48. context->RegisterFactory<StaticModelGroup>(GEOMETRY_CATEGORY);
  49. COPY_BASE_ATTRIBUTES(StaticModelGroup, StaticModel);
  50. REF_ACCESSOR_ATTRIBUTE(StaticModelGroup, VAR_VARIANTVECTOR, "Instance Nodes", GetNodeIDsAttr, SetNodeIDsAttr, VariantVector, Variant::emptyVariantVector, AM_DEFAULT | AM_NODEIDVECTOR);
  51. }
  52. void StaticModelGroup::ApplyAttributes()
  53. {
  54. if (!nodeIDsDirty_)
  55. return;
  56. // Remove all old instance nodes before searching for new. Can not call RemoveAllInstances() as that would modify
  57. // the ID list on its own
  58. for (unsigned i = 0; i < instanceNodes_.Size(); ++i)
  59. {
  60. Node* node = instanceNodes_[i];
  61. if (node)
  62. node->RemoveListener(this);
  63. }
  64. instanceNodes_.Clear();
  65. Scene* scene = GetScene();
  66. if (scene)
  67. {
  68. // The first index stores the number of IDs redundantly. This is for editing
  69. for (unsigned i = 1; i < nodeIDsAttr_.Size(); ++i)
  70. {
  71. Node* node = scene->GetNode(nodeIDsAttr_[i].GetUInt());
  72. if (node)
  73. {
  74. WeakPtr<Node> instanceWeak(node);
  75. node->AddListener(this);
  76. instanceNodes_.Push(instanceWeak);
  77. }
  78. }
  79. }
  80. worldTransforms_.Resize(instanceNodes_.Size());
  81. nodeIDsDirty_ = false;
  82. OnMarkedDirty(GetNode());
  83. }
  84. void StaticModelGroup::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  85. {
  86. // If no bones or no bone-level testing, use the Drawable test
  87. RayQueryLevel level = query.level_;
  88. if (level < RAY_AABB)
  89. {
  90. Drawable::ProcessRayQuery(query, results);
  91. return;
  92. }
  93. // Check ray hit distance to AABB before proceeding with more accurate tests
  94. // GetWorldBoundingBox() updates the world transforms
  95. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  96. return;
  97. for (unsigned i = 0; i < numWorldTransforms_; ++i)
  98. {
  99. // Initial test using AABB
  100. float distance = query.ray_.HitDistance(boundingBox_.Transformed(worldTransforms_[i]));
  101. // Then proceed to OBB and triangle-level tests if necessary
  102. if (level >= RAY_OBB && distance < query.maxDistance_)
  103. {
  104. Matrix3x4 inverse = worldTransforms_[i].Inverse();
  105. Ray localRay = query.ray_.Transformed(inverse);
  106. distance = localRay.HitDistance(boundingBox_);
  107. if (level == RAY_TRIANGLE && distance < query.maxDistance_)
  108. {
  109. distance = M_INFINITY;
  110. for (unsigned j = 0; j < batches_.Size(); ++j)
  111. {
  112. Geometry* geometry = batches_[j].geometry_;
  113. if (geometry)
  114. {
  115. float geometryDistance = geometry->GetHitDistance(localRay);
  116. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  117. distance = geometryDistance;
  118. }
  119. }
  120. }
  121. }
  122. if (distance < query.maxDistance_)
  123. {
  124. RayQueryResult result;
  125. result.drawable_ = this;
  126. result.node_ = node_;
  127. result.distance_ = distance;
  128. result.subObject_ = i;
  129. results.Push(result);
  130. }
  131. }
  132. }
  133. void StaticModelGroup::UpdateBatches(const FrameInfo& frame)
  134. {
  135. // Getting the world bounding box ensures the transforms are updated
  136. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  137. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  138. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  139. if (batches_.Size() > 1)
  140. {
  141. for (unsigned i = 0; i < batches_.Size(); ++i)
  142. {
  143. batches_[i].distance_ = frame.camera_->GetDistance(worldTransform * geometryData_[i].center_);
  144. batches_[i].worldTransform_ = numWorldTransforms_ ? &worldTransforms_[0] : &Matrix3x4::IDENTITY;
  145. batches_[i].numWorldTransforms_ = numWorldTransforms_;
  146. }
  147. }
  148. else if (batches_.Size() == 1)
  149. {
  150. batches_[0].distance_ = distance_;
  151. batches_[0].worldTransform_ = numWorldTransforms_ ? &worldTransforms_[0] : &Matrix3x4::IDENTITY;
  152. batches_[0].numWorldTransforms_ = numWorldTransforms_;
  153. }
  154. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  155. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  156. if (newLodDistance != lodDistance_)
  157. {
  158. lodDistance_ = newLodDistance;
  159. CalculateLodLevels();
  160. }
  161. }
  162. unsigned StaticModelGroup::GetNumOccluderTriangles()
  163. {
  164. // Make sure instance transforms are up-to-date
  165. GetWorldBoundingBox();
  166. unsigned triangles = 0;
  167. for (unsigned i = 0; i < batches_.Size(); ++i)
  168. {
  169. Geometry* geometry = GetLodGeometry(i, occlusionLodLevel_);
  170. if (!geometry)
  171. continue;
  172. // Check that the material is suitable for occlusion (default material always is)
  173. Material* mat = batches_[i].material_;
  174. if (mat && !mat->GetOcclusion())
  175. continue;
  176. triangles += numWorldTransforms_ * geometry->GetIndexCount() / 3;
  177. }
  178. return triangles;
  179. }
  180. bool StaticModelGroup::DrawOcclusion(OcclusionBuffer* buffer)
  181. {
  182. // Make sure instance transforms are up-to-date
  183. GetWorldBoundingBox();
  184. for (unsigned i = 0; i < numWorldTransforms_; ++i)
  185. {
  186. for (unsigned j = 0; j < batches_.Size(); ++j)
  187. {
  188. Geometry* geometry = GetLodGeometry(j, occlusionLodLevel_);
  189. if (!geometry)
  190. continue;
  191. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  192. Material* material = batches_[j].material_;
  193. if (material)
  194. {
  195. if (!material->GetOcclusion())
  196. continue;
  197. buffer->SetCullMode(material->GetCullMode());
  198. }
  199. else
  200. buffer->SetCullMode(CULL_CCW);
  201. const unsigned char* vertexData;
  202. unsigned vertexSize;
  203. const unsigned char* indexData;
  204. unsigned indexSize;
  205. unsigned elementMask;
  206. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  207. // Check for valid geometry data
  208. if (!vertexData || !indexData)
  209. continue;
  210. unsigned indexStart = geometry->GetIndexStart();
  211. unsigned indexCount = geometry->GetIndexCount();
  212. // Draw and check for running out of triangles
  213. if (!buffer->Draw(worldTransforms_[i], vertexData, vertexSize, indexData, indexSize, indexStart, indexCount))
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. void StaticModelGroup::AddInstanceNode(Node* node)
  220. {
  221. if (!node)
  222. return;
  223. WeakPtr<Node> instanceWeak(node);
  224. if (instanceNodes_.Contains(instanceWeak))
  225. return;
  226. // Add as a listener for the instance node, so that we know to dirty the transforms when the node moves or is enabled/disabled
  227. node->AddListener(this);
  228. instanceNodes_.Push(instanceWeak);
  229. UpdateNodeIDs();
  230. OnMarkedDirty(GetNode());
  231. MarkNetworkUpdate();
  232. }
  233. void StaticModelGroup::RemoveInstanceNode(Node* node)
  234. {
  235. if (!node)
  236. return;
  237. WeakPtr<Node> instanceWeak(node);
  238. node->RemoveListener(this);
  239. instanceNodes_.Remove(instanceWeak);
  240. UpdateNodeIDs();
  241. OnMarkedDirty(GetNode());
  242. MarkNetworkUpdate();
  243. }
  244. void StaticModelGroup::RemoveAllInstanceNodes()
  245. {
  246. for (unsigned i = 0; i < instanceNodes_.Size(); ++i)
  247. {
  248. Node* node = instanceNodes_[i];
  249. if (node)
  250. node->RemoveListener(this);
  251. }
  252. instanceNodes_.Clear();
  253. UpdateNodeIDs();
  254. OnMarkedDirty(GetNode());
  255. MarkNetworkUpdate();
  256. }
  257. Node* StaticModelGroup::GetInstanceNode(unsigned index) const
  258. {
  259. return index < instanceNodes_.Size() ? instanceNodes_[index] : (Node*)0;
  260. }
  261. void StaticModelGroup::SetNodeIDsAttr(const VariantVector& value)
  262. {
  263. // Just remember the node IDs. They need to go through the SceneResolver, and we actually find the nodes during
  264. // ApplyAttributes()
  265. if (value.Size())
  266. {
  267. nodeIDsAttr_.Clear();
  268. unsigned index = 0;
  269. unsigned numInstances = value[index++].GetUInt();
  270. // Prevent crash on entering negative value in the editor
  271. if (numInstances > M_MAX_INT)
  272. numInstances = 0;
  273. nodeIDsAttr_.Push(numInstances);
  274. while (numInstances--)
  275. {
  276. // If vector contains less IDs than should, fill the rest with zeroes
  277. if (index < value.Size())
  278. nodeIDsAttr_.Push(value[index++].GetUInt());
  279. else
  280. nodeIDsAttr_.Push(0);
  281. }
  282. }
  283. else
  284. {
  285. nodeIDsAttr_.Clear();
  286. nodeIDsAttr_.Push(0);
  287. }
  288. nodeIDsDirty_ = true;
  289. }
  290. void StaticModelGroup::OnNodeSetEnabled(Node* node)
  291. {
  292. Drawable::OnMarkedDirty(node);
  293. }
  294. void StaticModelGroup::OnWorldBoundingBoxUpdate()
  295. {
  296. // Update transforms and bounding box at the same time to have to go through the objects only once
  297. unsigned index = 0;
  298. BoundingBox worldBox;
  299. for (unsigned i = 0; i < instanceNodes_.Size(); ++i)
  300. {
  301. Node* node = instanceNodes_[i];
  302. if (!node || !node->IsEnabled())
  303. continue;
  304. const Matrix3x4& worldTransform = node->GetWorldTransform();
  305. worldTransforms_[index++] = worldTransform;
  306. worldBox.Merge(boundingBox_.Transformed(worldTransform));
  307. }
  308. worldBoundingBox_ = worldBox;
  309. // Store the amount of valid instances we found instead of resizing worldTransforms_. This is because this function may be
  310. // called from multiple worker threads simultaneously
  311. numWorldTransforms_ = index;
  312. }
  313. void StaticModelGroup::UpdateNodeIDs()
  314. {
  315. unsigned numInstances = instanceNodes_.Size();
  316. nodeIDsAttr_.Clear();
  317. nodeIDsAttr_.Push(numInstances);
  318. worldTransforms_.Resize(numInstances);
  319. numWorldTransforms_ = 0; // For safety. OnWorldBoundingBoxUpdate() will calculate the proper amount
  320. for (unsigned i = 0; i < numInstances; ++i)
  321. {
  322. Node* node = instanceNodes_[i];
  323. nodeIDsAttr_.Push(node ? node->GetID() : 0);
  324. }
  325. }
  326. }