StaticModelGroup.cpp 13 KB

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