StaticModelGroup.cpp 13 KB

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