CustomGeometry.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. //
  2. // Copyright (c) 2008-2015 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/CustomGeometry.h"
  26. #include "../Graphics/Geometry.h"
  27. #include "../IO/Log.h"
  28. #include "../Graphics/Material.h"
  29. #include "../IO/MemoryBuffer.h"
  30. #include "../Scene/Node.h"
  31. #include "../Graphics/OcclusionBuffer.h"
  32. #include "../Graphics/OctreeQuery.h"
  33. #include "../Core/Profiler.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../IO/VectorBuffer.h"
  36. #include "../Graphics/VertexBuffer.h"
  37. #include "../DebugNew.h"
  38. namespace Urho3D
  39. {
  40. extern const char* GEOMETRY_CATEGORY;
  41. CustomGeometry::CustomGeometry(Context* context) :
  42. Drawable(context, DRAWABLE_GEOMETRY),
  43. vertexBuffer_(new VertexBuffer(context)),
  44. elementMask_(MASK_POSITION),
  45. geometryIndex_(0),
  46. materialsAttr_(Material::GetTypeStatic()),
  47. dynamic_(false)
  48. {
  49. vertexBuffer_->SetShadowed(true);
  50. SetNumGeometries(1);
  51. }
  52. CustomGeometry::~CustomGeometry()
  53. {
  54. }
  55. void CustomGeometry::RegisterObject(Context* context)
  56. {
  57. context->RegisterFactory<CustomGeometry>(GEOMETRY_CATEGORY);
  58. ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  59. ATTRIBUTE("Dynamic Vertex Buffer", bool, dynamic_, false, AM_DEFAULT);
  60. MIXED_ACCESSOR_ATTRIBUTE("Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE|AM_NOEDIT);
  61. ACCESSOR_ATTRIBUTE("Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  62. ATTRIBUTE("Is Occluder", bool, occluder_, false, AM_DEFAULT);
  63. ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  64. ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  65. ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  66. ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  67. ACCESSOR_ATTRIBUTE("LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  68. COPY_BASE_ATTRIBUTES(Drawable);
  69. }
  70. void CustomGeometry::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  71. {
  72. RayQueryLevel level = query.level_;
  73. switch (level)
  74. {
  75. case RAY_AABB:
  76. Drawable::ProcessRayQuery(query, results);
  77. break;
  78. case RAY_OBB:
  79. case RAY_TRIANGLE:
  80. Matrix3x4 inverse(node_->GetWorldTransform().Inverse());
  81. Ray localRay = query.ray_.Transformed(inverse);
  82. float distance = localRay.HitDistance(boundingBox_);
  83. Vector3 normal = -query.ray_.direction_;
  84. if (level == RAY_TRIANGLE && distance < query.maxDistance_)
  85. {
  86. distance = M_INFINITY;
  87. for (unsigned i = 0; i < batches_.Size(); ++i)
  88. {
  89. Geometry* geometry = batches_[i].geometry_;
  90. if (geometry)
  91. {
  92. Vector3 geometryNormal;
  93. float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
  94. if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
  95. {
  96. distance = geometryDistance;
  97. normal = (node_->GetWorldTransform() * Vector4(geometryNormal, 0.0f)).Normalized();
  98. }
  99. }
  100. }
  101. }
  102. if (distance < query.maxDistance_)
  103. {
  104. RayQueryResult result;
  105. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  106. result.normal_ = normal;
  107. result.distance_ = distance;
  108. result.drawable_ = this;
  109. result.node_ = node_;
  110. result.subObject_ = M_MAX_UNSIGNED;
  111. results.Push(result);
  112. }
  113. break;
  114. }
  115. }
  116. Geometry* CustomGeometry::GetLodGeometry(unsigned batchIndex, unsigned level)
  117. {
  118. return batchIndex < geometries_.Size() ? geometries_[batchIndex] : (Geometry*)0;
  119. }
  120. unsigned CustomGeometry::GetNumOccluderTriangles()
  121. {
  122. unsigned triangles = 0;
  123. for (unsigned i = 0; i < batches_.Size(); ++i)
  124. {
  125. Geometry* geometry = GetLodGeometry(i, 0);
  126. if (!geometry)
  127. continue;
  128. // Check that the material is suitable for occlusion (default material always is)
  129. Material* mat = batches_[i].material_;
  130. if (mat && !mat->GetOcclusion())
  131. continue;
  132. triangles += geometry->GetVertexCount() / 3;
  133. }
  134. return triangles;
  135. }
  136. bool CustomGeometry::DrawOcclusion(OcclusionBuffer* buffer)
  137. {
  138. bool success = true;
  139. for (unsigned i = 0; i < batches_.Size(); ++i)
  140. {
  141. Geometry* geometry = GetLodGeometry(i, 0);
  142. if (!geometry)
  143. continue;
  144. // Check that the material is suitable for occlusion (default material always is) and set culling mode
  145. Material* material = batches_[i].material_;
  146. if (material)
  147. {
  148. if (!material->GetOcclusion())
  149. continue;
  150. buffer->SetCullMode(material->GetCullMode());
  151. }
  152. else
  153. buffer->SetCullMode(CULL_CCW);
  154. const unsigned char* vertexData;
  155. unsigned vertexSize;
  156. const unsigned char* indexData;
  157. unsigned indexSize;
  158. unsigned elementMask;
  159. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  160. // Check for valid geometry data
  161. if (!vertexData)
  162. continue;
  163. // Draw and check for running out of triangles
  164. success = buffer->Draw(node_->GetWorldTransform(), vertexData, vertexSize, geometry->GetVertexStart(), geometry->GetVertexCount());
  165. if (!success)
  166. break;
  167. }
  168. return success;
  169. }
  170. void CustomGeometry::Clear()
  171. {
  172. elementMask_ = MASK_POSITION;
  173. batches_.Clear();
  174. geometries_.Clear();
  175. primitiveTypes_.Clear();
  176. vertices_.Clear();
  177. }
  178. void CustomGeometry::SetNumGeometries(unsigned num)
  179. {
  180. batches_.Resize(num);
  181. geometries_.Resize(num);
  182. primitiveTypes_.Resize(num);
  183. vertices_.Resize(num);
  184. for (unsigned i = 0; i < geometries_.Size(); ++i)
  185. {
  186. if (!geometries_[i])
  187. geometries_[i] = new Geometry(context_);
  188. batches_[i].geometry_ = geometries_[i];
  189. }
  190. }
  191. void CustomGeometry::SetDynamic(bool enable)
  192. {
  193. dynamic_ = enable;
  194. MarkNetworkUpdate();
  195. }
  196. void CustomGeometry::BeginGeometry(unsigned index, PrimitiveType type)
  197. {
  198. if (index > geometries_.Size())
  199. {
  200. LOGERROR("Geometry index out of bounds");
  201. return;
  202. }
  203. geometryIndex_ = index;
  204. primitiveTypes_[index] = type;
  205. vertices_[index].Clear();
  206. // If beginning the first geometry, reset the element mask
  207. if (!index)
  208. elementMask_ = MASK_POSITION;
  209. }
  210. void CustomGeometry::DefineVertex(const Vector3& position)
  211. {
  212. if (vertices_.Size() < geometryIndex_)
  213. return;
  214. vertices_[geometryIndex_].Resize(vertices_[geometryIndex_].Size() + 1);
  215. vertices_[geometryIndex_].Back().position_ = position;
  216. }
  217. void CustomGeometry::DefineNormal(const Vector3& normal)
  218. {
  219. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  220. return;
  221. vertices_[geometryIndex_].Back().normal_ = normal;
  222. elementMask_ |= MASK_NORMAL;
  223. }
  224. void CustomGeometry::DefineColor(const Color& color)
  225. {
  226. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  227. return;
  228. vertices_[geometryIndex_].Back().color_ = color.ToUInt();
  229. elementMask_ |= MASK_COLOR;
  230. }
  231. void CustomGeometry::DefineTexCoord(const Vector2& texCoord)
  232. {
  233. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  234. return;
  235. vertices_[geometryIndex_].Back().texCoord_ = texCoord;
  236. elementMask_ |= MASK_TEXCOORD1;
  237. }
  238. void CustomGeometry::DefineTangent(const Vector4& tangent)
  239. {
  240. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  241. return;
  242. vertices_[geometryIndex_].Back().tangent_ = tangent;
  243. elementMask_ |= MASK_TANGENT;
  244. }
  245. void CustomGeometry::DefineGeometry(unsigned index, PrimitiveType type, unsigned numVertices, bool hasNormals, bool hasColors, bool hasTexCoords, bool hasTangents)
  246. {
  247. if (index > geometries_.Size())
  248. {
  249. LOGERROR("Geometry index out of bounds");
  250. return;
  251. }
  252. geometryIndex_ = index;
  253. primitiveTypes_[index] = type;
  254. vertices_[index].Resize(numVertices);
  255. // If defining the first geometry, reset the element mask
  256. if (!index)
  257. elementMask_ = MASK_POSITION;
  258. if (hasNormals)
  259. elementMask_ |= MASK_NORMAL;
  260. if (hasColors)
  261. elementMask_ |= MASK_COLOR;
  262. if (hasTexCoords)
  263. elementMask_ |= MASK_TEXCOORD1;
  264. if (hasTangents)
  265. elementMask_ |= MASK_TANGENT;
  266. }
  267. void CustomGeometry::Commit()
  268. {
  269. PROFILE(CommitCustomGeometry);
  270. unsigned totalVertices = 0;
  271. boundingBox_.Clear();
  272. for (unsigned i = 0; i < vertices_.Size(); ++i)
  273. {
  274. totalVertices += vertices_[i].Size();
  275. for (unsigned j = 0; j < vertices_[i].Size(); ++j)
  276. boundingBox_.Merge(vertices_[i][j].position_);
  277. }
  278. // Resize (recreate) the vertex buffer only if necessary
  279. if (vertexBuffer_->GetVertexCount() != totalVertices || vertexBuffer_->GetElementMask() != elementMask_ ||
  280. vertexBuffer_->IsDynamic() != dynamic_)
  281. vertexBuffer_->SetSize(totalVertices, elementMask_, dynamic_);
  282. if (totalVertices)
  283. {
  284. unsigned char* dest = (unsigned char*)vertexBuffer_->Lock(0, totalVertices, true);
  285. if (dest)
  286. {
  287. unsigned vertexStart = 0;
  288. for (unsigned i = 0; i < vertices_.Size(); ++i)
  289. {
  290. unsigned vertexCount = 0;
  291. for (unsigned j = 0; j < vertices_[i].Size(); ++j)
  292. {
  293. *((Vector3*)dest) = vertices_[i][j].position_;
  294. dest += sizeof(Vector3);
  295. if (elementMask_ & MASK_NORMAL)
  296. {
  297. *((Vector3*)dest) = vertices_[i][j].normal_;
  298. dest += sizeof(Vector3);
  299. }
  300. if (elementMask_ & MASK_COLOR)
  301. {
  302. *((unsigned*)dest) = vertices_[i][j].color_;
  303. dest += sizeof(unsigned);
  304. }
  305. if (elementMask_ & MASK_TEXCOORD1)
  306. {
  307. *((Vector2*)dest) = vertices_[i][j].texCoord_;
  308. dest += sizeof(Vector2);
  309. }
  310. if (elementMask_ & MASK_TANGENT)
  311. {
  312. *((Vector4*)dest) = vertices_[i][j].tangent_;
  313. dest += sizeof(Vector4);
  314. }
  315. ++vertexCount;
  316. }
  317. geometries_[i]->SetVertexBuffer(0, vertexBuffer_, elementMask_);
  318. geometries_[i]->SetDrawRange(primitiveTypes_[i], 0, 0, vertexStart, vertexCount);
  319. vertexStart += vertexCount;
  320. }
  321. vertexBuffer_->Unlock();
  322. }
  323. else
  324. LOGERROR("Failed to lock custom geometry vertex buffer");
  325. }
  326. else
  327. {
  328. for (unsigned i = 0; i < geometries_.Size(); ++i)
  329. {
  330. geometries_[i]->SetVertexBuffer(0, vertexBuffer_, elementMask_);
  331. geometries_[i]->SetDrawRange(primitiveTypes_[i], 0, 0, 0, 0);
  332. }
  333. }
  334. vertexBuffer_->ClearDataLost();
  335. }
  336. void CustomGeometry::SetMaterial(Material* material)
  337. {
  338. for (unsigned i = 0; i < batches_.Size(); ++i)
  339. batches_[i].material_ = material;
  340. MarkNetworkUpdate();
  341. }
  342. bool CustomGeometry::SetMaterial(unsigned index, Material* material)
  343. {
  344. if (index >= batches_.Size())
  345. {
  346. LOGERROR("Material index out of bounds");
  347. return false;
  348. }
  349. batches_[index].material_ = material;
  350. MarkNetworkUpdate();
  351. return true;
  352. }
  353. unsigned CustomGeometry::GetNumVertices(unsigned index) const
  354. {
  355. return index < vertices_.Size() ? vertices_[index].Size() : 0;
  356. }
  357. Material* CustomGeometry::GetMaterial(unsigned index) const
  358. {
  359. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  360. }
  361. CustomGeometryVertex* CustomGeometry::GetVertex(unsigned geometryIndex, unsigned vertexNum)
  362. {
  363. return (geometryIndex < vertices_.Size() && vertexNum < vertices_[geometryIndex].Size()) ?
  364. &vertices_[geometryIndex][vertexNum] : (CustomGeometryVertex*)0;
  365. }
  366. void CustomGeometry::SetGeometryDataAttr(const PODVector<unsigned char>& value)
  367. {
  368. if (value.Empty())
  369. return;
  370. MemoryBuffer buffer(value);
  371. SetNumGeometries(buffer.ReadVLE());
  372. elementMask_ = buffer.ReadUInt();
  373. for (unsigned i = 0; i < geometries_.Size(); ++i)
  374. {
  375. unsigned numVertices = buffer.ReadVLE();
  376. vertices_[i].Resize(numVertices);
  377. primitiveTypes_[i] = (PrimitiveType)buffer.ReadUByte();
  378. for (unsigned j = 0; j < numVertices; ++j)
  379. {
  380. if (elementMask_ & MASK_POSITION)
  381. vertices_[i][j].position_ = buffer.ReadVector3();
  382. if (elementMask_ & MASK_NORMAL)
  383. vertices_[i][j].normal_ = buffer.ReadVector3();
  384. if (elementMask_ & MASK_COLOR)
  385. vertices_[i][j].color_ = buffer.ReadUInt();
  386. if (elementMask_ & MASK_TEXCOORD1)
  387. vertices_[i][j].texCoord_ = buffer.ReadVector2();
  388. if (elementMask_ & MASK_TANGENT)
  389. vertices_[i][j].tangent_ = buffer.ReadVector4();
  390. }
  391. }
  392. Commit();
  393. }
  394. void CustomGeometry::SetMaterialsAttr(const ResourceRefList& value)
  395. {
  396. ResourceCache* cache = GetSubsystem<ResourceCache>();
  397. for (unsigned i = 0; i < value.names_.Size(); ++i)
  398. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  399. }
  400. PODVector<unsigned char> CustomGeometry::GetGeometryDataAttr() const
  401. {
  402. VectorBuffer ret;
  403. ret.WriteVLE(geometries_.Size());
  404. ret.WriteUInt(elementMask_);
  405. for (unsigned i = 0; i < geometries_.Size(); ++i)
  406. {
  407. unsigned numVertices = vertices_[i].Size();
  408. ret.WriteVLE(numVertices);
  409. ret.WriteUByte(primitiveTypes_[i]);
  410. for (unsigned j = 0; j < numVertices; ++j)
  411. {
  412. if (elementMask_ & MASK_POSITION)
  413. ret.WriteVector3(vertices_[i][j].position_);
  414. if (elementMask_ & MASK_NORMAL)
  415. ret.WriteVector3(vertices_[i][j].normal_);
  416. if (elementMask_ & MASK_COLOR)
  417. ret.WriteUInt(vertices_[i][j].color_);
  418. if (elementMask_ & MASK_TEXCOORD1)
  419. ret.WriteVector2(vertices_[i][j].texCoord_);
  420. if (elementMask_ & MASK_TANGENT)
  421. ret.WriteVector4(vertices_[i][j].tangent_);
  422. }
  423. }
  424. return ret.GetBuffer();
  425. }
  426. const ResourceRefList& CustomGeometry::GetMaterialsAttr() const
  427. {
  428. materialsAttr_.names_.Resize(batches_.Size());
  429. for (unsigned i = 0; i < batches_.Size(); ++i)
  430. materialsAttr_.names_[i] = GetResourceName(batches_[i].material_);
  431. return materialsAttr_;
  432. }
  433. void CustomGeometry::OnWorldBoundingBoxUpdate()
  434. {
  435. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  436. }
  437. }