CustomGeometry.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 "Precompiled.h"
  23. #include "Batch.h"
  24. #include "Camera.h"
  25. #include "Context.h"
  26. #include "CustomGeometry.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "Material.h"
  30. #include "MemoryBuffer.h"
  31. #include "Node.h"
  32. #include "OcclusionBuffer.h"
  33. #include "OctreeQuery.h"
  34. #include "Profiler.h"
  35. #include "ResourceCache.h"
  36. #include "VectorBuffer.h"
  37. #include "VertexBuffer.h"
  38. #include "DebugNew.h"
  39. namespace Urho3D
  40. {
  41. extern const char* GEOMETRY_CATEGORY;
  42. CustomGeometry::CustomGeometry(Context* context) :
  43. Drawable(context, DRAWABLE_GEOMETRY),
  44. vertexBuffer_(new VertexBuffer(context)),
  45. elementMask_(MASK_POSITION),
  46. geometryIndex_(0),
  47. materialsAttr_(Material::GetTypeStatic())
  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(CustomGeometry, VAR_BOOL, "Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  59. ACCESSOR_ATTRIBUTE(CustomGeometry, VAR_BUFFER, "Geometry Data", GetGeometryDataAttr, SetGeometryDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE|AM_NOEDIT);
  60. REF_ACCESSOR_ATTRIBUTE(CustomGeometry, VAR_RESOURCEREFLIST, "Materials", GetMaterialsAttr, SetMaterialsAttr, ResourceRefList, ResourceRefList(Material::GetTypeStatic()), AM_DEFAULT);
  61. ATTRIBUTE(CustomGeometry, VAR_BOOL, "Is Occluder", occluder_, false, AM_DEFAULT);
  62. ACCESSOR_ATTRIBUTE(CustomGeometry, VAR_BOOL, "Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  63. ATTRIBUTE(CustomGeometry, VAR_BOOL, "Cast Shadows", castShadows_, false, AM_DEFAULT);
  64. ACCESSOR_ATTRIBUTE(CustomGeometry, VAR_FLOAT, "Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  65. ACCESSOR_ATTRIBUTE(CustomGeometry, VAR_FLOAT, "Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  66. ACCESSOR_ATTRIBUTE(CustomGeometry, VAR_FLOAT, "LOD Bias", GetLodBias, SetLodBias, float, 1.0f, AM_DEFAULT);
  67. COPY_BASE_ATTRIBUTES(CustomGeometry, Drawable);
  68. }
  69. void CustomGeometry::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  70. {
  71. RayQueryLevel level = query.level_;
  72. switch (level)
  73. {
  74. case RAY_AABB_NOSUBOBJECTS:
  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::BeginGeometry(unsigned index, PrimitiveType type)
  192. {
  193. if (index > geometries_.Size())
  194. {
  195. LOGERROR("Geometry index out of bounds");
  196. return;
  197. }
  198. geometryIndex_ = index;
  199. primitiveTypes_[index] = type;
  200. vertices_[index].Clear();
  201. }
  202. void CustomGeometry::DefineVertex(const Vector3& position)
  203. {
  204. if (vertices_.Size() < geometryIndex_)
  205. return;
  206. vertices_[geometryIndex_].Resize(vertices_[geometryIndex_].Size() + 1);
  207. vertices_[geometryIndex_].Back().position_ = position;
  208. }
  209. void CustomGeometry::DefineNormal(const Vector3& normal)
  210. {
  211. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  212. return;
  213. vertices_[geometryIndex_].Back().normal_ = normal;
  214. elementMask_ |= MASK_NORMAL;
  215. }
  216. void CustomGeometry::DefineColor(const Color& color)
  217. {
  218. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  219. return;
  220. vertices_[geometryIndex_].Back().color_ = color.ToUInt();
  221. elementMask_ |= MASK_COLOR;
  222. }
  223. void CustomGeometry::DefineTexCoord(const Vector2& texCoord)
  224. {
  225. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  226. return;
  227. vertices_[geometryIndex_].Back().texCoord_ = texCoord;
  228. elementMask_ |= MASK_TEXCOORD1;
  229. }
  230. void CustomGeometry::DefineTangent(const Vector4& tangent)
  231. {
  232. if (vertices_.Size() < geometryIndex_ || vertices_[geometryIndex_].Empty())
  233. return;
  234. vertices_[geometryIndex_].Back().tangent_ = tangent;
  235. elementMask_ |= MASK_TANGENT;
  236. }
  237. void CustomGeometry::Commit()
  238. {
  239. PROFILE(CommitCustomGeometry);
  240. unsigned totalVertices = 0;
  241. boundingBox_.Clear();
  242. for (unsigned i = 0; i < vertices_.Size(); ++i)
  243. {
  244. totalVertices += vertices_[i].Size();
  245. for (unsigned j = 0; j < vertices_[i].Size(); ++j)
  246. boundingBox_.Merge(vertices_[i][j].position_);
  247. }
  248. vertexBuffer_->SetSize(totalVertices, elementMask_);
  249. if (totalVertices)
  250. {
  251. unsigned char* dest = (unsigned char*)vertexBuffer_->Lock(0, totalVertices, true);
  252. if (dest)
  253. {
  254. unsigned vertexStart = 0;
  255. for (unsigned i = 0; i < vertices_.Size(); ++i)
  256. {
  257. unsigned vertexCount = 0;
  258. for (unsigned j = 0; j < vertices_[i].Size(); ++j)
  259. {
  260. *((Vector3*)dest) = vertices_[i][j].position_;
  261. dest += sizeof(Vector3);
  262. if (elementMask_ & MASK_NORMAL)
  263. {
  264. *((Vector3*)dest) = vertices_[i][j].normal_;
  265. dest += sizeof(Vector3);
  266. }
  267. if (elementMask_ & MASK_COLOR)
  268. {
  269. *((unsigned*)dest) = vertices_[i][j].color_;
  270. dest += sizeof(unsigned);
  271. }
  272. if (elementMask_ & MASK_TEXCOORD1)
  273. {
  274. *((Vector2*)dest) = vertices_[i][j].texCoord_;
  275. dest += sizeof(Vector2);
  276. }
  277. if (elementMask_ & MASK_TANGENT)
  278. {
  279. *((Vector4*)dest) = vertices_[i][j].tangent_;
  280. dest += sizeof(Vector4);
  281. }
  282. ++vertexCount;
  283. }
  284. geometries_[i]->SetVertexBuffer(0, vertexBuffer_, elementMask_);
  285. geometries_[i]->SetDrawRange(primitiveTypes_[i], 0, 0, vertexStart, vertexCount);
  286. vertexStart += vertexCount;
  287. }
  288. vertexBuffer_->Unlock();
  289. }
  290. else
  291. LOGERROR("Failed to lock custom geometry vertex buffer");
  292. }
  293. else
  294. {
  295. for (unsigned i = 0; i < geometries_.Size(); ++i)
  296. {
  297. geometries_[i]->SetVertexBuffer(0, vertexBuffer_, elementMask_);
  298. geometries_[i]->SetDrawRange(primitiveTypes_[i], 0, 0, 0, 0);
  299. }
  300. }
  301. vertexBuffer_->ClearDataLost();
  302. }
  303. void CustomGeometry::SetMaterial(Material* material)
  304. {
  305. for (unsigned i = 0; i < batches_.Size(); ++i)
  306. batches_[i].material_ = material;
  307. MarkNetworkUpdate();
  308. }
  309. bool CustomGeometry::SetMaterial(unsigned index, Material* material)
  310. {
  311. if (index >= batches_.Size())
  312. {
  313. LOGERROR("Material index out of bounds");
  314. return false;
  315. }
  316. batches_[index].material_ = material;
  317. MarkNetworkUpdate();
  318. return true;
  319. }
  320. Material* CustomGeometry::GetMaterial(unsigned index) const
  321. {
  322. return index < batches_.Size() ? batches_[index].material_ : (Material*)0;
  323. }
  324. void CustomGeometry::SetGeometryDataAttr(PODVector<unsigned char> value)
  325. {
  326. if (value.Empty())
  327. return;
  328. MemoryBuffer buffer(value);
  329. SetNumGeometries(buffer.ReadVLE());
  330. elementMask_ = buffer.ReadUInt();
  331. for (unsigned i = 0; i < geometries_.Size(); ++i)
  332. {
  333. unsigned numVertices = buffer.ReadVLE();
  334. vertices_[i].Resize(numVertices);
  335. primitiveTypes_[i] = (PrimitiveType)buffer.ReadUByte();
  336. for (unsigned j = 0; j < numVertices; ++j)
  337. {
  338. if (elementMask_ & MASK_POSITION)
  339. vertices_[i][j].position_ = buffer.ReadVector3();
  340. if (elementMask_ & MASK_NORMAL)
  341. vertices_[i][j].normal_ = buffer.ReadVector3();
  342. if (elementMask_ & MASK_COLOR)
  343. vertices_[i][j].color_ = buffer.ReadUInt();
  344. if (elementMask_ & MASK_TEXCOORD1)
  345. vertices_[i][j].texCoord_ = buffer.ReadVector2();
  346. if (elementMask_ & MASK_TANGENT)
  347. vertices_[i][j].tangent_ = buffer.ReadVector4();
  348. }
  349. }
  350. Commit();
  351. }
  352. void CustomGeometry::SetMaterialsAttr(const ResourceRefList& value)
  353. {
  354. ResourceCache* cache = GetSubsystem<ResourceCache>();
  355. for (unsigned i = 0; i < value.names_.Size(); ++i)
  356. SetMaterial(i, cache->GetResource<Material>(value.names_[i]));
  357. }
  358. PODVector<unsigned char> CustomGeometry::GetGeometryDataAttr() const
  359. {
  360. VectorBuffer ret;
  361. ret.WriteVLE(geometries_.Size());
  362. ret.WriteUInt(elementMask_);
  363. for (unsigned i = 0; i < geometries_.Size(); ++i)
  364. {
  365. unsigned numVertices = vertices_[i].Size();
  366. ret.WriteVLE(numVertices);
  367. ret.WriteUByte(primitiveTypes_[i]);
  368. for (unsigned j = 0; j < numVertices; ++j)
  369. {
  370. if (elementMask_ & MASK_POSITION)
  371. ret.WriteVector3(vertices_[i][j].position_);
  372. if (elementMask_ & MASK_NORMAL)
  373. ret.WriteVector3(vertices_[i][j].normal_);
  374. if (elementMask_ & MASK_COLOR)
  375. ret.WriteUInt(vertices_[i][j].color_);
  376. if (elementMask_ & MASK_TEXCOORD1)
  377. ret.WriteVector2(vertices_[i][j].texCoord_);
  378. if (elementMask_ & MASK_TANGENT)
  379. ret.WriteVector4(vertices_[i][j].tangent_);
  380. }
  381. }
  382. return ret.GetBuffer();
  383. }
  384. const ResourceRefList& CustomGeometry::GetMaterialsAttr() const
  385. {
  386. materialsAttr_.names_.Resize(batches_.Size());
  387. for (unsigned i = 0; i < batches_.Size(); ++i)
  388. materialsAttr_.names_[i] = GetResourceName(batches_[i].material_);
  389. return materialsAttr_;
  390. }
  391. void CustomGeometry::OnWorldBoundingBoxUpdate()
  392. {
  393. worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform());
  394. }
  395. }