CustomGeometry.cpp 17 KB

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