BsMesh.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. #include "BsMesh.h"
  2. #include "BsMeshRTTI.h"
  3. #include "BsMeshData.h"
  4. #include "BsVector2.h"
  5. #include "BsVector3.h"
  6. #include "BsDebug.h"
  7. #include "BsHardwareBufferManager.h"
  8. #include "BsMeshManager.h"
  9. #include "BsCoreThread.h"
  10. #include "BsAsyncOp.h"
  11. #include "BsAABox.h"
  12. #include "BsVertexDataDesc.h"
  13. #include "BsResources.h"
  14. #include "BsFrameAlloc.h"
  15. namespace BansheeEngine
  16. {
  17. MeshCore::MeshCore(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  18. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType, MeshDataPtr initialMeshData)
  19. :MeshCoreBase(numVertices, numIndices, subMeshes), mVertexData(nullptr), mIndexBuffer(nullptr),
  20. mVertexDesc(vertexDesc), mBufferType(bufferType), mIndexType(indexType), mTempInitialMeshData(initialMeshData)
  21. { }
  22. MeshCore::~MeshCore()
  23. {
  24. THROW_IF_NOT_CORE_THREAD;
  25. mVertexData = nullptr;
  26. mIndexBuffer = nullptr;
  27. mVertexDesc = nullptr;
  28. mTempInitialMeshData = nullptr;
  29. }
  30. void MeshCore::initialize()
  31. {
  32. THROW_IF_NOT_CORE_THREAD;
  33. mIndexBuffer = HardwareBufferCoreManager::instance().createIndexBuffer(mIndexType,
  34. mProperties.mNumIndices, mBufferType == MeshBufferType::Dynamic ? GBU_DYNAMIC : GBU_STATIC);
  35. mVertexData = std::shared_ptr<VertexData>(bs_new<VertexData, PoolAlloc>());
  36. mVertexData->vertexCount = mProperties.mNumVertices;
  37. List<VertexElement> elements = mVertexDesc->createElements();
  38. mVertexData->vertexDeclaration = HardwareBufferCoreManager::instance().createVertexDeclaration(elements);
  39. for (UINT32 i = 0; i <= mVertexDesc->getMaxStreamIdx(); i++)
  40. {
  41. if (!mVertexDesc->hasStream(i))
  42. continue;
  43. SPtr<VertexBufferCore> vertexBuffer = HardwareBufferCoreManager::instance().createVertexBuffer(
  44. mVertexData->vertexDeclaration->getProperties().getVertexSize(i),
  45. mVertexData->vertexCount,
  46. mBufferType == MeshBufferType::Dynamic ? GBU_DYNAMIC : GBU_STATIC);
  47. mVertexData->setBuffer(i, vertexBuffer);
  48. }
  49. // TODO Low priority - DX11 (and maybe OpenGL)? allow an optimization that allows you to set
  50. // buffer data upon buffer construction, instead of setting it in a second step like I do here
  51. if (mTempInitialMeshData != nullptr)
  52. {
  53. writeSubresource(0, *mTempInitialMeshData, mBufferType == MeshBufferType::Dynamic);
  54. mTempInitialMeshData = nullptr;
  55. }
  56. MeshCoreBase::initialize();
  57. }
  58. std::shared_ptr<VertexData> MeshCore::getVertexData() const
  59. {
  60. THROW_IF_NOT_CORE_THREAD;
  61. return mVertexData;
  62. }
  63. SPtr<IndexBufferCore> MeshCore::getIndexBuffer() const
  64. {
  65. THROW_IF_NOT_CORE_THREAD;
  66. return mIndexBuffer;
  67. }
  68. void MeshCore::writeSubresource(UINT32 subresourceIdx, const MeshData& meshData, bool discardEntireBuffer, bool performUpdateBounds)
  69. {
  70. THROW_IF_NOT_CORE_THREAD;
  71. if (discardEntireBuffer)
  72. {
  73. if (mBufferType == MeshBufferType::Static)
  74. {
  75. LOGWRN("Buffer discard is enabled but buffer was not created as dynamic. Disabling discard.");
  76. discardEntireBuffer = false;
  77. }
  78. }
  79. else
  80. {
  81. if (mBufferType == MeshBufferType::Dynamic)
  82. {
  83. LOGWRN("Buffer discard is not enabled but buffer was created as dynamic. Enabling discard.");
  84. discardEntireBuffer = true;
  85. }
  86. }
  87. // Indices
  88. const IndexBufferProperties& ibProps = mIndexBuffer->getProperties();
  89. UINT32 indicesSize = meshData.getIndexBufferSize();
  90. UINT8* srcIdxData = meshData.getIndexData();
  91. if (meshData.getIndexElementSize() != ibProps.getIndexSize())
  92. {
  93. BS_EXCEPT(InvalidParametersException, "Provided index size doesn't match meshes index size. Needed: " +
  94. toString(ibProps.getIndexSize()) + ". Got: " + toString(meshData.getIndexElementSize()));
  95. }
  96. if (indicesSize > mIndexBuffer->getSizeInBytes())
  97. BS_EXCEPT(InvalidParametersException, "Index buffer values are being written out of valid range.");
  98. mIndexBuffer->writeData(0, indicesSize, srcIdxData, discardEntireBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
  99. // Vertices
  100. for (UINT32 i = 0; i <= mVertexDesc->getMaxStreamIdx(); i++)
  101. {
  102. if (!mVertexDesc->hasStream(i))
  103. continue;
  104. if (!meshData.getVertexDesc()->hasStream(i))
  105. continue;
  106. // Ensure both have the same sized vertices
  107. UINT32 myVertSize = mVertexDesc->getVertexStride(i);
  108. UINT32 otherVertSize = meshData.getVertexDesc()->getVertexStride(i);
  109. if (myVertSize != otherVertSize)
  110. {
  111. BS_EXCEPT(InvalidParametersException, "Provided vertex size for stream " + toString(i) + " doesn't match meshes vertex size. Needed: " +
  112. toString(myVertSize) + ". Got: " + toString(otherVertSize));
  113. }
  114. SPtr<VertexBufferCore> vertexBuffer = mVertexData->getBuffer(i);
  115. const VertexBufferProperties& vbProps = vertexBuffer->getProperties();
  116. UINT32 bufferSize = meshData.getStreamSize(i);
  117. UINT8* srcVertBufferData = meshData.getStreamData(i);
  118. if (bufferSize > vertexBuffer->getSizeInBytes())
  119. BS_EXCEPT(InvalidParametersException, "Vertex buffer values for stream \"" + toString(i) + "\" are being written out of valid range.");
  120. if (RenderAPICore::instance().getVertexColorFlipRequired())
  121. {
  122. UINT8* bufferCopy = (UINT8*)bs_alloc(bufferSize);
  123. memcpy(bufferCopy, srcVertBufferData, bufferSize); // TODO Low priority - Attempt to avoid this copy
  124. UINT32 vertexStride = meshData.getVertexDesc()->getVertexStride(i);
  125. for (INT32 semanticIdx = 0; semanticIdx < VertexBuffer::MAX_SEMANTIC_IDX; semanticIdx++)
  126. {
  127. if (!meshData.getVertexDesc()->hasElement(VES_COLOR, semanticIdx, i))
  128. continue;
  129. UINT8* colorData = bufferCopy + mVertexDesc->getElementOffsetFromStream(VES_COLOR, semanticIdx, i);
  130. for (UINT32 j = 0; j < mVertexData->vertexCount; j++)
  131. {
  132. UINT32* curColor = (UINT32*)colorData;
  133. (*curColor) = ((*curColor) & 0xFF00FF00) | ((*curColor >> 16) & 0x000000FF) | ((*curColor << 16) & 0x00FF0000);
  134. colorData += vertexStride;
  135. }
  136. }
  137. vertexBuffer->writeData(0, bufferSize, bufferCopy, discardEntireBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
  138. bs_free(bufferCopy);
  139. }
  140. else
  141. {
  142. vertexBuffer->writeData(0, bufferSize, srcVertBufferData, discardEntireBuffer ? BufferWriteType::Discard : BufferWriteType::Normal);
  143. }
  144. }
  145. if (performUpdateBounds)
  146. updateBounds(meshData);
  147. }
  148. void MeshCore::readSubresource(UINT32 subresourceIdx, MeshData& meshData)
  149. {
  150. THROW_IF_NOT_CORE_THREAD;
  151. IndexType indexType = IT_32BIT;
  152. if (mIndexBuffer)
  153. indexType = mIndexBuffer->getProperties().getType();
  154. if (mIndexBuffer)
  155. {
  156. const IndexBufferProperties& ibProps = mIndexBuffer->getProperties();
  157. if (meshData.getIndexElementSize() != ibProps.getIndexSize())
  158. {
  159. BS_EXCEPT(InvalidParametersException, "Provided index size doesn't match meshes index size. Needed: " +
  160. toString(ibProps.getIndexSize()) + ". Got: " + toString(meshData.getIndexElementSize()));
  161. }
  162. UINT8* idxData = static_cast<UINT8*>(mIndexBuffer->lock(GBL_READ_ONLY));
  163. UINT32 idxElemSize = ibProps.getIndexSize();
  164. UINT8* indices = nullptr;
  165. if (indexType == IT_16BIT)
  166. indices = (UINT8*)meshData.getIndices16();
  167. else
  168. indices = (UINT8*)meshData.getIndices32();
  169. UINT32 numIndicesToCopy = std::min(mProperties.mNumIndices, meshData.getNumIndices());
  170. UINT32 indicesSize = numIndicesToCopy * idxElemSize;
  171. if (indicesSize > meshData.getIndexBufferSize())
  172. BS_EXCEPT(InvalidParametersException, "Provided buffer doesn't have enough space to store mesh indices.");
  173. memcpy(indices, idxData, numIndicesToCopy * idxElemSize);
  174. mIndexBuffer->unlock();
  175. }
  176. if (mVertexData)
  177. {
  178. auto vertexBuffers = mVertexData->getBuffers();
  179. UINT32 streamIdx = 0;
  180. for (auto iter = vertexBuffers.begin(); iter != vertexBuffers.end(); ++iter)
  181. {
  182. if (!meshData.getVertexDesc()->hasStream(streamIdx))
  183. continue;
  184. SPtr<VertexBufferCore> vertexBuffer = iter->second;
  185. const VertexBufferProperties& vbProps = vertexBuffer->getProperties();
  186. // Ensure both have the same sized vertices
  187. UINT32 myVertSize = mVertexDesc->getVertexStride(streamIdx);
  188. UINT32 otherVertSize = meshData.getVertexDesc()->getVertexStride(streamIdx);
  189. if (myVertSize != otherVertSize)
  190. {
  191. BS_EXCEPT(InvalidParametersException, "Provided vertex size for stream " + toString(streamIdx) + " doesn't match meshes vertex size. Needed: " +
  192. toString(myVertSize) + ". Got: " + toString(otherVertSize));
  193. }
  194. UINT32 numVerticesToCopy = meshData.getNumVertices();
  195. UINT32 bufferSize = vbProps.getVertexSize() * numVerticesToCopy;
  196. if (bufferSize > vertexBuffer->getSizeInBytes())
  197. BS_EXCEPT(InvalidParametersException, "Vertex buffer values for stream \"" + toString(streamIdx) + "\" are being read out of valid range.");
  198. UINT8* vertDataPtr = static_cast<UINT8*>(vertexBuffer->lock(GBL_READ_ONLY));
  199. UINT8* dest = meshData.getStreamData(streamIdx);
  200. memcpy(dest, vertDataPtr, bufferSize);
  201. vertexBuffer->unlock();
  202. streamIdx++;
  203. }
  204. }
  205. }
  206. void MeshCore::updateBounds(const MeshData& meshData)
  207. {
  208. mProperties.mBounds = meshData.calculateBounds();
  209. // TODO - Sync this to sim-thread possibly?
  210. }
  211. Mesh::Mesh(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  212. MeshBufferType bufferType, DrawOperationType drawOp, IndexType indexType)
  213. :MeshBase(numVertices, numIndices, drawOp), mVertexDesc(vertexDesc), mBufferType(bufferType),
  214. mIndexType(indexType)
  215. {
  216. }
  217. Mesh::Mesh(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  218. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType)
  219. :MeshBase(numVertices, numIndices, subMeshes), mVertexDesc(vertexDesc), mBufferType(bufferType),
  220. mIndexType(indexType)
  221. {
  222. }
  223. Mesh::Mesh(const MeshDataPtr& initialMeshData, MeshBufferType bufferType, DrawOperationType drawOp)
  224. :MeshBase(initialMeshData->getNumVertices(), initialMeshData->getNumIndices(), drawOp),
  225. mIndexType(initialMeshData->getIndexType()), mVertexDesc(initialMeshData->getVertexDesc()),
  226. mTempInitialMeshData(initialMeshData)
  227. {
  228. }
  229. Mesh::Mesh(const MeshDataPtr& initialMeshData, const Vector<SubMesh>& subMeshes, MeshBufferType bufferType)
  230. :MeshBase(initialMeshData->getNumVertices(), initialMeshData->getNumIndices(), subMeshes),
  231. mIndexType(initialMeshData->getIndexType()), mVertexDesc(initialMeshData->getVertexDesc()),
  232. mTempInitialMeshData(initialMeshData)
  233. {
  234. }
  235. Mesh::Mesh()
  236. :MeshBase(0, 0, DOT_TRIANGLE_LIST), mBufferType(MeshBufferType::Static), mIndexType(IT_32BIT)
  237. {
  238. }
  239. Mesh::~Mesh()
  240. {
  241. }
  242. AsyncOp Mesh::writeSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const MeshDataPtr& data, bool discardEntireBuffer)
  243. {
  244. updateBounds(*data);
  245. data->_lock();
  246. std::function<void(const SPtr<MeshCore>&, UINT32, const MeshDataPtr&, bool, AsyncOp&)> func =
  247. [&](const SPtr<MeshCore>& mesh, UINT32 _subresourceIdx, const MeshDataPtr& _meshData, bool _discardEntireBuffer, AsyncOp& asyncOp)
  248. {
  249. mesh->writeSubresource(_subresourceIdx, *_meshData, _discardEntireBuffer, false);
  250. _meshData->_unlock();
  251. asyncOp._completeOperation();
  252. };
  253. return accessor.queueReturnCommand(std::bind(func, getCore(), subresourceIdx,
  254. data, discardEntireBuffer, std::placeholders::_1));
  255. }
  256. AsyncOp Mesh::readSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const MeshDataPtr& data)
  257. {
  258. data->_lock();
  259. std::function<void(const SPtr<MeshCore>&, UINT32, const MeshDataPtr&, AsyncOp&)> func =
  260. [&](const SPtr<MeshCore>& mesh, UINT32 _subresourceIdx, const MeshDataPtr& _meshData, AsyncOp& asyncOp)
  261. {
  262. mesh->readSubresource(_subresourceIdx, *_meshData);
  263. _meshData->_unlock();
  264. asyncOp._completeOperation();
  265. };
  266. return accessor.queueReturnCommand(std::bind(func, getCore(), subresourceIdx,
  267. data, std::placeholders::_1));
  268. }
  269. MeshDataPtr Mesh::allocateSubresourceBuffer(UINT32 subresourceIdx) const
  270. {
  271. MeshDataPtr meshData = bs_shared_ptr<MeshData>(mProperties.mNumVertices, mProperties.mNumIndices, mVertexDesc, mIndexType);
  272. return meshData;
  273. }
  274. void Mesh::initialize()
  275. {
  276. if (mTempInitialMeshData != nullptr)
  277. {
  278. updateBounds(*mTempInitialMeshData);
  279. }
  280. MeshBase::initialize();
  281. }
  282. void Mesh::updateBounds(const MeshData& meshData)
  283. {
  284. mProperties.mBounds = meshData.calculateBounds();
  285. markCoreDirty();
  286. }
  287. SPtr<MeshCore> Mesh::getCore() const
  288. {
  289. return std::static_pointer_cast<MeshCore>(mCoreSpecific);
  290. }
  291. SPtr<CoreObjectCore> Mesh::createCore() const
  292. {
  293. MeshCore* obj = new (bs_alloc<MeshCore>()) MeshCore(mProperties.mNumVertices, mProperties.mNumIndices,
  294. mVertexDesc, mProperties.mSubMeshes, mBufferType, mIndexType, mTempInitialMeshData);
  295. SPtr<CoreObjectCore> meshCore = bs_shared_ptr<MeshCore, GenAlloc>(obj);
  296. meshCore->_setThisPtr(meshCore);
  297. mTempInitialMeshData = nullptr;
  298. return meshCore;
  299. }
  300. HMesh Mesh::dummy()
  301. {
  302. return MeshManager::instance().getDummyMesh();
  303. }
  304. /************************************************************************/
  305. /* SERIALIZATION */
  306. /************************************************************************/
  307. RTTITypeBase* Mesh::getRTTIStatic()
  308. {
  309. return MeshRTTI::instance();
  310. }
  311. RTTITypeBase* Mesh::getRTTI() const
  312. {
  313. return Mesh::getRTTIStatic();
  314. }
  315. /************************************************************************/
  316. /* STATICS */
  317. /************************************************************************/
  318. HMesh Mesh::create(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  319. MeshBufferType bufferType, DrawOperationType drawOp, IndexType indexType)
  320. {
  321. MeshPtr meshPtr = _createPtr(numVertices, numIndices, vertexDesc, bufferType, drawOp, indexType);
  322. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  323. }
  324. HMesh Mesh::create(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  325. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType)
  326. {
  327. MeshPtr meshPtr = _createPtr(numVertices, numIndices, vertexDesc, subMeshes, bufferType, indexType);
  328. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  329. }
  330. HMesh Mesh::create(const MeshDataPtr& initialMeshData, MeshBufferType bufferType, DrawOperationType drawOp)
  331. {
  332. MeshPtr meshPtr = _createPtr(initialMeshData, bufferType, drawOp);
  333. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  334. }
  335. HMesh Mesh::create(const MeshDataPtr& initialMeshData, const Vector<SubMesh>& subMeshes, MeshBufferType bufferType)
  336. {
  337. MeshPtr meshPtr = _createPtr(initialMeshData, subMeshes, bufferType);
  338. return static_resource_cast<Mesh>(gResources()._createResourceHandle(meshPtr));
  339. }
  340. MeshPtr Mesh::_createPtr(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  341. MeshBufferType bufferType, DrawOperationType drawOp, IndexType indexType)
  342. {
  343. return MeshManager::instance().create(numVertices, numIndices, vertexDesc, bufferType, drawOp, indexType);
  344. }
  345. MeshPtr Mesh::_createPtr(UINT32 numVertices, UINT32 numIndices, const VertexDataDescPtr& vertexDesc,
  346. const Vector<SubMesh>& subMeshes, MeshBufferType bufferType, IndexType indexType)
  347. {
  348. return MeshManager::instance().create(numVertices, numIndices, vertexDesc, subMeshes, bufferType, indexType);
  349. }
  350. MeshPtr Mesh::_createPtr(const MeshDataPtr& initialMeshData, MeshBufferType bufferType, DrawOperationType drawOp)
  351. {
  352. return MeshManager::instance().create(initialMeshData, bufferType, drawOp);
  353. }
  354. MeshPtr Mesh::_createPtr(const MeshDataPtr& initialMeshData, const Vector<SubMesh>& subMeshes, MeshBufferType bufferType)
  355. {
  356. return MeshManager::instance().create(initialMeshData, subMeshes, bufferType);
  357. }
  358. }