OgreVertexIndexData.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "OgreVertexIndexData.h"
  25. #include "OgreHardwareBufferManager.h"
  26. #include "OgreHardwareVertexBuffer.h"
  27. #include "OgreHardwareIndexBuffer.h"
  28. #include "OgreVector3.h"
  29. #include "OgreAxisAlignedBox.h"
  30. #include "OgreException.h"
  31. #include "OgreRenderSystem.h"
  32. #include "CmRenderSystemManager.h"
  33. namespace Ogre {
  34. //-----------------------------------------------------------------------
  35. VertexData::VertexData(HardwareBufferManagerBase* mgr)
  36. {
  37. mMgr = mgr ? mgr : HardwareBufferManager::getSingletonPtr();
  38. vertexBufferBinding = mMgr->createVertexBufferBinding();
  39. vertexDeclaration = mMgr->createVertexDeclaration();
  40. mDeleteDclBinding = true;
  41. vertexCount = 0;
  42. vertexStart = 0;
  43. hwAnimDataItemsUsed = 0;
  44. }
  45. //---------------------------------------------------------------------
  46. VertexData::VertexData(VertexDeclaration* dcl, VertexBufferBinding* bind)
  47. {
  48. // this is a fallback rather than actively used
  49. mMgr = HardwareBufferManager::getSingletonPtr();
  50. vertexDeclaration = dcl;
  51. vertexBufferBinding = bind;
  52. mDeleteDclBinding = false;
  53. vertexCount = 0;
  54. vertexStart = 0;
  55. hwAnimDataItemsUsed = 0;
  56. }
  57. //-----------------------------------------------------------------------
  58. VertexData::~VertexData()
  59. {
  60. if (mDeleteDclBinding)
  61. {
  62. mMgr->destroyVertexBufferBinding(vertexBufferBinding);
  63. mMgr->destroyVertexDeclaration(vertexDeclaration);
  64. }
  65. }
  66. //-----------------------------------------------------------------------
  67. VertexData* VertexData::clone(bool copyData, HardwareBufferManagerBase* mgr) const
  68. {
  69. HardwareBufferManagerBase* pManager = mgr ? mgr : mMgr;
  70. VertexData* dest = OGRE_NEW VertexData(mgr);
  71. // Copy vertex buffers in turn
  72. const VertexBufferBinding::VertexBufferBindingMap& bindings =
  73. this->vertexBufferBinding->getBindings();
  74. VertexBufferBinding::VertexBufferBindingMap::const_iterator vbi, vbend;
  75. vbend = bindings.end();
  76. for (vbi = bindings.begin(); vbi != vbend; ++vbi)
  77. {
  78. HardwareVertexBufferPtr srcbuf = vbi->second;
  79. HardwareVertexBufferPtr dstBuf;
  80. if (copyData)
  81. {
  82. // create new buffer with the same settings
  83. dstBuf = pManager->createVertexBuffer(
  84. srcbuf->getVertexSize(), srcbuf->getNumVertices(), srcbuf->getUsage(),
  85. srcbuf->hasShadowBuffer());
  86. // copy data
  87. dstBuf->copyData(*srcbuf, 0, 0, srcbuf->getSizeInBytes(), true);
  88. }
  89. else
  90. {
  91. // don't copy, point at existing buffer
  92. dstBuf = srcbuf;
  93. }
  94. // Copy binding
  95. dest->vertexBufferBinding->setBinding(vbi->first, dstBuf);
  96. }
  97. // Basic vertex info
  98. dest->vertexStart = this->vertexStart;
  99. dest->vertexCount = this->vertexCount;
  100. // Copy elements
  101. const VertexDeclaration::VertexElementList elems =
  102. this->vertexDeclaration->getElements();
  103. VertexDeclaration::VertexElementList::const_iterator ei, eiend;
  104. eiend = elems.end();
  105. for (ei = elems.begin(); ei != eiend; ++ei)
  106. {
  107. dest->vertexDeclaration->addElement(
  108. ei->getSource(),
  109. ei->getOffset(),
  110. ei->getType(),
  111. ei->getSemantic(),
  112. ei->getIndex() );
  113. }
  114. // Copy reference to hardware shadow buffer, no matter whether copy data or not
  115. dest->hardwareShadowVolWBuffer = hardwareShadowVolWBuffer;
  116. // copy anim data
  117. dest->hwAnimationDataList = hwAnimationDataList;
  118. dest->hwAnimDataItemsUsed = hwAnimDataItemsUsed;
  119. return dest;
  120. }
  121. //-----------------------------------------------------------------------
  122. void VertexData::prepareForShadowVolume(void)
  123. {
  124. /* NOTE
  125. I would dearly, dearly love to just use a 4D position buffer in order to
  126. store the extra 'w' value I need to differentiate between extruded and
  127. non-extruded sections of the buffer, so that vertex programs could use that.
  128. Hey, it works fine for GL. However, D3D9 in it's infinite stupidity, does not
  129. support 4d position vertices in the fixed-function pipeline. If you use them,
  130. you just see nothing. Since we can't know whether the application is going to use
  131. fixed function or vertex programs, we have to stick to 3d position vertices and
  132. store the 'w' in a separate 1D texture coordinate buffer, which is only used
  133. when rendering the shadow.
  134. */
  135. // Upfront, lets check whether we have vertex program capability
  136. bool useVertexPrograms = false;
  137. RenderSystem* rend = CamelotEngine::RenderSystemManager::getActive();
  138. if (rend && rend->getCapabilities()->hasCapability(RSC_VERTEX_PROGRAM))
  139. {
  140. useVertexPrograms = true;
  141. }
  142. // Look for a position element
  143. const VertexElement* posElem = vertexDeclaration->findElementBySemantic(VES_POSITION);
  144. if (posElem)
  145. {
  146. size_t v;
  147. unsigned short posOldSource = posElem->getSource();
  148. HardwareVertexBufferPtr vbuf = vertexBufferBinding->getBuffer(posOldSource);
  149. bool wasSharedBuffer = false;
  150. // Are there other elements in the buffer except for the position?
  151. if (vbuf->getVertexSize() > posElem->getSize())
  152. {
  153. // We need to create another buffer to contain the remaining elements
  154. // Most drivers don't like gaps in the declaration, and in any case it's waste
  155. wasSharedBuffer = true;
  156. }
  157. HardwareVertexBufferPtr newPosBuffer, newRemainderBuffer;
  158. if (wasSharedBuffer)
  159. {
  160. newRemainderBuffer = vbuf->getManager()->createVertexBuffer(
  161. vbuf->getVertexSize() - posElem->getSize(), vbuf->getNumVertices(), vbuf->getUsage(),
  162. vbuf->hasShadowBuffer());
  163. }
  164. // Allocate new position buffer, will be FLOAT3 and 2x the size
  165. size_t oldVertexCount = vbuf->getNumVertices();
  166. size_t newVertexCount = oldVertexCount * 2;
  167. newPosBuffer = vbuf->getManager()->createVertexBuffer(
  168. VertexElement::getTypeSize(VET_FLOAT3), newVertexCount, vbuf->getUsage(),
  169. vbuf->hasShadowBuffer());
  170. // Iterate over the old buffer, copying the appropriate elements and initialising the rest
  171. float* pSrc;
  172. unsigned char *pBaseSrc = static_cast<unsigned char*>(
  173. vbuf->lock(HardwareBuffer::HBL_READ_ONLY));
  174. // Point first destination pointer at the start of the new position buffer,
  175. // the other one half way along
  176. float *pDest = static_cast<float*>(newPosBuffer->lock(HardwareBuffer::HBL_DISCARD));
  177. float* pDest2 = pDest + oldVertexCount * 3;
  178. // Precalculate any dimensions of vertex areas outside the position
  179. size_t prePosVertexSize = 0, postPosVertexSize, postPosVertexOffset;
  180. unsigned char *pBaseDestRem = 0;
  181. if (wasSharedBuffer)
  182. {
  183. pBaseDestRem = static_cast<unsigned char*>(
  184. newRemainderBuffer->lock(HardwareBuffer::HBL_DISCARD));
  185. prePosVertexSize = posElem->getOffset();
  186. postPosVertexOffset = prePosVertexSize + posElem->getSize();
  187. postPosVertexSize = vbuf->getVertexSize() - postPosVertexOffset;
  188. // the 2 separate bits together should be the same size as the remainder buffer vertex
  189. assert (newRemainderBuffer->getVertexSize() == prePosVertexSize + postPosVertexSize);
  190. // Iterate over the vertices
  191. for (v = 0; v < oldVertexCount; ++v)
  192. {
  193. // Copy position, into both buffers
  194. posElem->baseVertexPointerToElement(pBaseSrc, &pSrc);
  195. *pDest++ = *pDest2++ = *pSrc++;
  196. *pDest++ = *pDest2++ = *pSrc++;
  197. *pDest++ = *pDest2++ = *pSrc++;
  198. // now deal with any other elements
  199. // Basically we just memcpy the vertex excluding the position
  200. if (prePosVertexSize > 0)
  201. memcpy(pBaseDestRem, pBaseSrc, prePosVertexSize);
  202. if (postPosVertexSize > 0)
  203. memcpy(pBaseDestRem + prePosVertexSize,
  204. pBaseSrc + postPosVertexOffset, postPosVertexSize);
  205. pBaseDestRem += newRemainderBuffer->getVertexSize();
  206. pBaseSrc += vbuf->getVertexSize();
  207. } // next vertex
  208. }
  209. else
  210. {
  211. // Unshared buffer, can block copy the whole thing
  212. memcpy(pDest, pBaseSrc, vbuf->getSizeInBytes());
  213. memcpy(pDest2, pBaseSrc, vbuf->getSizeInBytes());
  214. }
  215. vbuf->unlock();
  216. newPosBuffer->unlock();
  217. if (wasSharedBuffer)
  218. newRemainderBuffer->unlock();
  219. // At this stage, he original vertex buffer is going to be destroyed
  220. // So we should force the deallocation of any temporary copies
  221. vbuf->getManager()->_forceReleaseBufferCopies(vbuf);
  222. if (useVertexPrograms)
  223. {
  224. // Now it's time to set up the w buffer
  225. hardwareShadowVolWBuffer = vbuf->getManager()->createVertexBuffer(
  226. sizeof(float), newVertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false);
  227. // Fill the first half with 1.0, second half with 0.0
  228. pDest = static_cast<float*>(
  229. hardwareShadowVolWBuffer->lock(HardwareBuffer::HBL_DISCARD));
  230. for (v = 0; v < oldVertexCount; ++v)
  231. {
  232. *pDest++ = 1.0f;
  233. }
  234. for (v = 0; v < oldVertexCount; ++v)
  235. {
  236. *pDest++ = 0.0f;
  237. }
  238. hardwareShadowVolWBuffer->unlock();
  239. }
  240. unsigned short newPosBufferSource;
  241. if (wasSharedBuffer)
  242. {
  243. // Get the a new buffer binding index
  244. newPosBufferSource= vertexBufferBinding->getNextIndex();
  245. // Re-bind the old index to the remainder buffer
  246. vertexBufferBinding->setBinding(posOldSource, newRemainderBuffer);
  247. }
  248. else
  249. {
  250. // We can just re-use the same source idex for the new position buffer
  251. newPosBufferSource = posOldSource;
  252. }
  253. // Bind the new position buffer
  254. vertexBufferBinding->setBinding(newPosBufferSource, newPosBuffer);
  255. // Now, alter the vertex declaration to change the position source
  256. // and the offsets of elements using the same buffer
  257. VertexDeclaration::VertexElementList::const_iterator elemi =
  258. vertexDeclaration->getElements().begin();
  259. VertexDeclaration::VertexElementList::const_iterator elemiend =
  260. vertexDeclaration->getElements().end();
  261. unsigned short idx;
  262. for(idx = 0; elemi != elemiend; ++elemi, ++idx)
  263. {
  264. if (&(*elemi) == posElem)
  265. {
  266. // Modify position to point at new position buffer
  267. vertexDeclaration->modifyElement(
  268. idx,
  269. newPosBufferSource, // new source buffer
  270. 0, // no offset now
  271. VET_FLOAT3,
  272. VES_POSITION);
  273. }
  274. else if (wasSharedBuffer &&
  275. elemi->getSource() == posOldSource &&
  276. elemi->getOffset() > prePosVertexSize )
  277. {
  278. // This element came after position, remove the position's
  279. // size
  280. vertexDeclaration->modifyElement(
  281. idx,
  282. posOldSource, // same old source
  283. elemi->getOffset() - posElem->getSize(), // less offset now
  284. elemi->getType(),
  285. elemi->getSemantic(),
  286. elemi->getIndex());
  287. }
  288. }
  289. // Note that we don't change vertexCount, because the other buffer(s) are still the same
  290. // size after all
  291. }
  292. }
  293. //-----------------------------------------------------------------------
  294. void VertexData::reorganiseBuffers(VertexDeclaration* newDeclaration,
  295. const BufferUsageList& bufferUsages, HardwareBufferManagerBase* mgr)
  296. {
  297. HardwareBufferManagerBase* pManager = mgr ? mgr : mMgr;
  298. // Firstly, close up any gaps in the buffer sources which might have arisen
  299. newDeclaration->closeGapsInSource();
  300. // Build up a list of both old and new elements in each buffer
  301. unsigned short buf = 0;
  302. vector<void*>::type oldBufferLocks;
  303. vector<size_t>::type oldBufferVertexSizes;
  304. vector<void*>::type newBufferLocks;
  305. vector<size_t>::type newBufferVertexSizes;
  306. VertexBufferBinding* newBinding = pManager->createVertexBufferBinding();
  307. const VertexBufferBinding::VertexBufferBindingMap& oldBindingMap = vertexBufferBinding->getBindings();
  308. VertexBufferBinding::VertexBufferBindingMap::const_iterator itBinding;
  309. // Pre-allocate old buffer locks
  310. if (!oldBindingMap.empty())
  311. {
  312. size_t count = oldBindingMap.rbegin()->first + 1;
  313. oldBufferLocks.resize(count);
  314. oldBufferVertexSizes.resize(count);
  315. }
  316. // Lock all the old buffers for reading
  317. for (itBinding = oldBindingMap.begin(); itBinding != oldBindingMap.end(); ++itBinding)
  318. {
  319. assert(itBinding->second->getNumVertices() >= vertexCount);
  320. oldBufferVertexSizes[itBinding->first] =
  321. itBinding->second->getVertexSize();
  322. oldBufferLocks[itBinding->first] =
  323. itBinding->second->lock(
  324. HardwareBuffer::HBL_READ_ONLY);
  325. }
  326. // Create new buffers and lock all for writing
  327. buf = 0;
  328. while (!newDeclaration->findElementsBySource(buf).empty())
  329. {
  330. size_t vertexSize = newDeclaration->getVertexSize(buf);
  331. HardwareVertexBufferPtr vbuf =
  332. pManager->createVertexBuffer(
  333. vertexSize,
  334. vertexCount,
  335. bufferUsages[buf]);
  336. newBinding->setBinding(buf, vbuf);
  337. newBufferVertexSizes.push_back(vertexSize);
  338. newBufferLocks.push_back(
  339. vbuf->lock(HardwareBuffer::HBL_DISCARD));
  340. buf++;
  341. }
  342. // Map from new to old elements
  343. typedef map<const VertexElement*, const VertexElement*>::type NewToOldElementMap;
  344. NewToOldElementMap newToOldElementMap;
  345. const VertexDeclaration::VertexElementList& newElemList = newDeclaration->getElements();
  346. VertexDeclaration::VertexElementList::const_iterator ei, eiend;
  347. eiend = newElemList.end();
  348. for (ei = newElemList.begin(); ei != eiend; ++ei)
  349. {
  350. // Find corresponding old element
  351. const VertexElement* oldElem =
  352. vertexDeclaration->findElementBySemantic(
  353. (*ei).getSemantic(), (*ei).getIndex());
  354. if (!oldElem)
  355. {
  356. // Error, cannot create new elements with this method
  357. OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
  358. "Element not found in old vertex declaration",
  359. "VertexData::reorganiseBuffers");
  360. }
  361. newToOldElementMap[&(*ei)] = oldElem;
  362. }
  363. // Now iterate over the new buffers, pulling data out of the old ones
  364. // For each vertex
  365. for (size_t v = 0; v < vertexCount; ++v)
  366. {
  367. // For each (new) element
  368. for (ei = newElemList.begin(); ei != eiend; ++ei)
  369. {
  370. const VertexElement* newElem = &(*ei);
  371. NewToOldElementMap::iterator noi = newToOldElementMap.find(newElem);
  372. const VertexElement* oldElem = noi->second;
  373. unsigned short oldBufferNo = oldElem->getSource();
  374. unsigned short newBufferNo = newElem->getSource();
  375. void* pSrcBase = static_cast<void*>(
  376. static_cast<unsigned char*>(oldBufferLocks[oldBufferNo])
  377. + v * oldBufferVertexSizes[oldBufferNo]);
  378. void* pDstBase = static_cast<void*>(
  379. static_cast<unsigned char*>(newBufferLocks[newBufferNo])
  380. + v * newBufferVertexSizes[newBufferNo]);
  381. void *pSrc, *pDst;
  382. oldElem->baseVertexPointerToElement(pSrcBase, &pSrc);
  383. newElem->baseVertexPointerToElement(pDstBase, &pDst);
  384. memcpy(pDst, pSrc, newElem->getSize());
  385. }
  386. }
  387. // Unlock all buffers
  388. for (itBinding = oldBindingMap.begin(); itBinding != oldBindingMap.end(); ++itBinding)
  389. {
  390. itBinding->second->unlock();
  391. }
  392. for (buf = 0; buf < newBinding->getBufferCount(); ++buf)
  393. {
  394. newBinding->getBuffer(buf)->unlock();
  395. }
  396. // Delete old binding & declaration
  397. if (mDeleteDclBinding)
  398. {
  399. pManager->destroyVertexBufferBinding(vertexBufferBinding);
  400. pManager->destroyVertexDeclaration(vertexDeclaration);
  401. }
  402. // Assign new binding and declaration
  403. vertexDeclaration = newDeclaration;
  404. vertexBufferBinding = newBinding;
  405. // after this is complete, new manager should be used
  406. mMgr = pManager;
  407. mDeleteDclBinding = true; // because we created these through a manager
  408. }
  409. //-----------------------------------------------------------------------
  410. void VertexData::reorganiseBuffers(VertexDeclaration* newDeclaration, HardwareBufferManagerBase* mgr)
  411. {
  412. // Derive the buffer usages from looking at where the source has come
  413. // from
  414. BufferUsageList usages;
  415. for (unsigned short b = 0; b <= newDeclaration->getMaxSource(); ++b)
  416. {
  417. VertexDeclaration::VertexElementList destElems = newDeclaration->findElementsBySource(b);
  418. // Initialise with most restrictive version
  419. // (not really a usable option, but these flags will be removed)
  420. HardwareBuffer::Usage final = static_cast<HardwareBuffer::Usage>(
  421. HardwareBuffer::HBU_STATIC_WRITE_ONLY | HardwareBuffer::HBU_DISCARDABLE);
  422. VertexDeclaration::VertexElementList::iterator v;
  423. for (v = destElems.begin(); v != destElems.end(); ++v)
  424. {
  425. VertexElement& destelem = *v;
  426. // get source
  427. const VertexElement* srcelem =
  428. vertexDeclaration->findElementBySemantic(
  429. destelem.getSemantic(), destelem.getIndex());
  430. // get buffer
  431. HardwareVertexBufferPtr srcbuf =
  432. vertexBufferBinding->getBuffer(srcelem->getSource());
  433. // improve flexibility only
  434. if (srcbuf->getUsage() & HardwareBuffer::HBU_DYNAMIC)
  435. {
  436. // remove static
  437. final = static_cast<HardwareBuffer::Usage>(
  438. final & ~HardwareBuffer::HBU_STATIC);
  439. // add dynamic
  440. final = static_cast<HardwareBuffer::Usage>(
  441. final | HardwareBuffer::HBU_DYNAMIC);
  442. }
  443. if (!(srcbuf->getUsage() & HardwareBuffer::HBU_WRITE_ONLY))
  444. {
  445. // remove write only
  446. final = static_cast<HardwareBuffer::Usage>(
  447. final & ~HardwareBuffer::HBU_WRITE_ONLY);
  448. }
  449. if (!(srcbuf->getUsage() & HardwareBuffer::HBU_DISCARDABLE))
  450. {
  451. // remove discardable
  452. final = static_cast<HardwareBuffer::Usage>(
  453. final & ~HardwareBuffer::HBU_DISCARDABLE);
  454. }
  455. }
  456. usages.push_back(final);
  457. }
  458. // Call specific method
  459. reorganiseBuffers(newDeclaration, usages, mgr);
  460. }
  461. //-----------------------------------------------------------------------
  462. void VertexData::closeGapsInBindings(void)
  463. {
  464. if (!vertexBufferBinding->hasGaps())
  465. return;
  466. // Check for error first
  467. const VertexDeclaration::VertexElementList& allelems =
  468. vertexDeclaration->getElements();
  469. VertexDeclaration::VertexElementList::const_iterator ai;
  470. for (ai = allelems.begin(); ai != allelems.end(); ++ai)
  471. {
  472. const VertexElement& elem = *ai;
  473. if (!vertexBufferBinding->isBufferBound(elem.getSource()))
  474. {
  475. OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
  476. "No buffer is bound to that element source.",
  477. "VertexData::closeGapsInBindings");
  478. }
  479. }
  480. // Close gaps in the vertex buffer bindings
  481. VertexBufferBinding::BindingIndexMap bindingIndexMap;
  482. vertexBufferBinding->closeGaps(bindingIndexMap);
  483. // Modify vertex elements to reference to new buffer index
  484. unsigned short elemIndex = 0;
  485. for (ai = allelems.begin(); ai != allelems.end(); ++ai, ++elemIndex)
  486. {
  487. const VertexElement& elem = *ai;
  488. VertexBufferBinding::BindingIndexMap::const_iterator it =
  489. bindingIndexMap.find(elem.getSource());
  490. assert(it != bindingIndexMap.end());
  491. ushort targetSource = it->second;
  492. if (elem.getSource() != targetSource)
  493. {
  494. vertexDeclaration->modifyElement(elemIndex,
  495. targetSource, elem.getOffset(), elem.getType(),
  496. elem.getSemantic(), elem.getIndex());
  497. }
  498. }
  499. }
  500. //-----------------------------------------------------------------------
  501. void VertexData::removeUnusedBuffers(void)
  502. {
  503. set<ushort>::type usedBuffers;
  504. // Collect used buffers
  505. const VertexDeclaration::VertexElementList& allelems =
  506. vertexDeclaration->getElements();
  507. VertexDeclaration::VertexElementList::const_iterator ai;
  508. for (ai = allelems.begin(); ai != allelems.end(); ++ai)
  509. {
  510. const VertexElement& elem = *ai;
  511. usedBuffers.insert(elem.getSource());
  512. }
  513. // Unset unused buffer bindings
  514. ushort count = vertexBufferBinding->getLastBoundIndex();
  515. for (ushort index = 0; index < count; ++index)
  516. {
  517. if (usedBuffers.find(index) == usedBuffers.end() &&
  518. vertexBufferBinding->isBufferBound(index))
  519. {
  520. vertexBufferBinding->unsetBinding(index);
  521. }
  522. }
  523. // Close gaps
  524. closeGapsInBindings();
  525. }
  526. //-----------------------------------------------------------------------
  527. void VertexData::convertPackedColour(
  528. VertexElementType srcType, VertexElementType destType)
  529. {
  530. if (destType != VET_COLOUR_ABGR && destType != VET_COLOUR_ARGB)
  531. {
  532. OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
  533. "Invalid destType parameter", "VertexData::convertPackedColour");
  534. }
  535. if (srcType != VET_COLOUR_ABGR && srcType != VET_COLOUR_ARGB)
  536. {
  537. OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
  538. "Invalid srcType parameter", "VertexData::convertPackedColour");
  539. }
  540. const VertexBufferBinding::VertexBufferBindingMap& bindMap =
  541. vertexBufferBinding->getBindings();
  542. VertexBufferBinding::VertexBufferBindingMap::const_iterator bindi;
  543. for (bindi = bindMap.begin(); bindi != bindMap.end(); ++bindi)
  544. {
  545. VertexDeclaration::VertexElementList elems =
  546. vertexDeclaration->findElementsBySource(bindi->first);
  547. bool conversionNeeded = false;
  548. VertexDeclaration::VertexElementList::iterator elemi;
  549. for (elemi = elems.begin(); elemi != elems.end(); ++elemi)
  550. {
  551. VertexElement& elem = *elemi;
  552. if (elem.getType() == VET_COLOUR ||
  553. ((elem.getType() == VET_COLOUR_ABGR || elem.getType() == VET_COLOUR_ARGB)
  554. && elem.getType() != destType))
  555. {
  556. conversionNeeded = true;
  557. }
  558. }
  559. if (conversionNeeded)
  560. {
  561. void* pBase = bindi->second->lock(HardwareBuffer::HBL_NORMAL);
  562. for (size_t v = 0; v < bindi->second->getNumVertices(); ++v)
  563. {
  564. for (elemi = elems.begin(); elemi != elems.end(); ++elemi)
  565. {
  566. VertexElement& elem = *elemi;
  567. VertexElementType currType = (elem.getType() == VET_COLOUR) ?
  568. srcType : elem.getType();
  569. if (elem.getType() == VET_COLOUR ||
  570. ((elem.getType() == VET_COLOUR_ABGR || elem.getType() == VET_COLOUR_ARGB)
  571. && elem.getType() != destType))
  572. {
  573. uint32* pRGBA;
  574. elem.baseVertexPointerToElement(pBase, &pRGBA);
  575. VertexElement::convertColourValue(currType, destType, pRGBA);
  576. }
  577. }
  578. pBase = static_cast<void*>(
  579. static_cast<char*>(pBase) + bindi->second->getVertexSize());
  580. }
  581. bindi->second->unlock();
  582. // Modify the elements to reflect the changed type
  583. const VertexDeclaration::VertexElementList& allelems =
  584. vertexDeclaration->getElements();
  585. VertexDeclaration::VertexElementList::const_iterator ai;
  586. unsigned short elemIndex = 0;
  587. for (ai = allelems.begin(); ai != allelems.end(); ++ai, ++elemIndex)
  588. {
  589. const VertexElement& elem = *ai;
  590. if (elem.getType() == VET_COLOUR ||
  591. ((elem.getType() == VET_COLOUR_ABGR || elem.getType() == VET_COLOUR_ARGB)
  592. && elem.getType() != destType))
  593. {
  594. vertexDeclaration->modifyElement(elemIndex,
  595. elem.getSource(), elem.getOffset(), destType,
  596. elem.getSemantic(), elem.getIndex());
  597. }
  598. }
  599. }
  600. } // each buffer
  601. }
  602. //-----------------------------------------------------------------------
  603. void VertexData::allocateHardwareAnimationElements(ushort count)
  604. {
  605. // Find first free texture coord set
  606. unsigned short texCoord = 0;
  607. const VertexDeclaration::VertexElementList& vel = vertexDeclaration->getElements();
  608. for (VertexDeclaration::VertexElementList::const_iterator i = vel.begin();
  609. i != vel.end(); ++i)
  610. {
  611. const VertexElement& el = *i;
  612. if (el.getSemantic() == VES_TEXTURE_COORDINATES)
  613. {
  614. ++texCoord;
  615. }
  616. }
  617. assert(texCoord <= OGRE_MAX_TEXTURE_COORD_SETS);
  618. // Increase to correct size
  619. for (size_t c = hwAnimationDataList.size(); c < count; ++c)
  620. {
  621. // Create a new 3D texture coordinate set
  622. HardwareAnimationData data;
  623. data.targetVertexElement = &(vertexDeclaration->addElement(
  624. vertexBufferBinding->getNextIndex(), 0, VET_FLOAT3, VES_TEXTURE_COORDINATES, texCoord++));
  625. hwAnimationDataList.push_back(data);
  626. // Vertex buffer will not be bound yet, we expect this to be done by the
  627. // caller when it becomes appropriate (e.g. through a VertexAnimationTrack)
  628. }
  629. }
  630. //-----------------------------------------------------------------------
  631. //-----------------------------------------------------------------------
  632. IndexData::IndexData()
  633. {
  634. indexCount = 0;
  635. indexStart = 0;
  636. }
  637. //-----------------------------------------------------------------------
  638. IndexData::~IndexData()
  639. {
  640. }
  641. //-----------------------------------------------------------------------
  642. IndexData* IndexData::clone(bool copyData, HardwareBufferManagerBase* mgr) const
  643. {
  644. HardwareBufferManagerBase* pManager = mgr ? mgr : HardwareBufferManager::getSingletonPtr();
  645. IndexData* dest = OGRE_NEW IndexData();
  646. if (indexBuffer.get())
  647. {
  648. if (copyData)
  649. {
  650. dest->indexBuffer = pManager->createIndexBuffer(indexBuffer->getType(), indexBuffer->getNumIndexes(),
  651. indexBuffer->getUsage(), indexBuffer->hasShadowBuffer());
  652. dest->indexBuffer->copyData(*indexBuffer, 0, 0, indexBuffer->getSizeInBytes(), true);
  653. }
  654. else
  655. {
  656. dest->indexBuffer = indexBuffer;
  657. }
  658. }
  659. dest->indexCount = indexCount;
  660. dest->indexStart = indexStart;
  661. return dest;
  662. }
  663. //-----------------------------------------------------------------------
  664. //-----------------------------------------------------------------------
  665. // Local Utility class for vertex cache optimizer
  666. class Triangle
  667. {
  668. public:
  669. enum EdgeMatchType {
  670. AB, BC, CA, ANY, NONE
  671. };
  672. uint32 a, b, c;
  673. inline Triangle()
  674. {
  675. }
  676. inline Triangle( uint32 ta, uint32 tb, uint32 tc )
  677. : a( ta ), b( tb ), c( tc )
  678. {
  679. }
  680. inline Triangle( uint32 t[3] )
  681. : a( t[0] ), b( t[1] ), c( t[2] )
  682. {
  683. }
  684. inline Triangle( const Triangle& t )
  685. : a( t.a ), b( t.b ), c( t.c )
  686. {
  687. }
  688. inline bool sharesEdge(const Triangle& t) const
  689. {
  690. return( a == t.a && b == t.c ||
  691. a == t.b && b == t.a ||
  692. a == t.c && b == t.b ||
  693. b == t.a && c == t.c ||
  694. b == t.b && c == t.a ||
  695. b == t.c && c == t.b ||
  696. c == t.a && a == t.c ||
  697. c == t.b && a == t.a ||
  698. c == t.c && a == t.b );
  699. }
  700. inline bool sharesEdge(const uint32 ea, const uint32 eb, const Triangle& t) const
  701. {
  702. return( ea == t.a && eb == t.c ||
  703. ea == t.b && eb == t.a ||
  704. ea == t.c && eb == t.b );
  705. }
  706. inline bool sharesEdge(const EdgeMatchType edge, const Triangle& t) const
  707. {
  708. if (edge == AB)
  709. return sharesEdge(a, b, t);
  710. else if (edge == BC)
  711. return sharesEdge(b, c, t);
  712. else if (edge == CA)
  713. return sharesEdge(c, a, t);
  714. else
  715. return (edge == ANY) == sharesEdge(t);
  716. }
  717. inline EdgeMatchType endoSharedEdge(const Triangle& t) const
  718. {
  719. if (sharesEdge(a, b, t)) return AB;
  720. if (sharesEdge(b, c, t)) return BC;
  721. if (sharesEdge(c, a, t)) return CA;
  722. return NONE;
  723. }
  724. inline EdgeMatchType exoSharedEdge(const Triangle& t) const
  725. {
  726. return t.endoSharedEdge(*this);
  727. }
  728. inline void shiftClockwise()
  729. {
  730. uint32 t = a;
  731. a = c;
  732. c = b;
  733. b = t;
  734. }
  735. inline void shiftCounterClockwise()
  736. {
  737. uint32 t = a;
  738. a = b;
  739. b = c;
  740. c = t;
  741. }
  742. };
  743. //-----------------------------------------------------------------------
  744. //-----------------------------------------------------------------------
  745. void IndexData::optimiseVertexCacheTriList(void)
  746. {
  747. if (indexBuffer->isLocked()) return;
  748. void *buffer = indexBuffer->lock(HardwareBuffer::HBL_NORMAL);
  749. Triangle* triangles;
  750. uint32 *dest;
  751. size_t nIndexes = indexCount;
  752. size_t nTriangles = nIndexes / 3;
  753. size_t i, j;
  754. uint16 *source = 0;
  755. if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT)
  756. {
  757. triangles = OGRE_ALLOC_T(Triangle, nTriangles, MEMCATEGORY_GEOMETRY);
  758. source = (uint16 *)buffer;
  759. dest = (uint32 *)triangles;
  760. for (i = 0; i < nIndexes; ++i) dest[i] = source[i];
  761. }
  762. else
  763. triangles = (Triangle*)buffer;
  764. // sort triangles based on shared edges
  765. uint32 *destlist = OGRE_ALLOC_T(uint32, nTriangles, MEMCATEGORY_GEOMETRY);
  766. unsigned char *visited = OGRE_ALLOC_T(unsigned char, nTriangles, MEMCATEGORY_GEOMETRY);
  767. for (i = 0; i < nTriangles; ++i) visited[i] = 0;
  768. uint32 start = 0, ti = 0, destcount = 0;
  769. bool found = false;
  770. for (i = 0; i < nTriangles; ++i)
  771. {
  772. if (found)
  773. found = false;
  774. else
  775. {
  776. while (visited[start++]);
  777. ti = start - 1;
  778. }
  779. destlist[destcount++] = ti;
  780. visited[ti] = 1;
  781. for (j = start; j < nTriangles; ++j)
  782. {
  783. if (visited[j]) continue;
  784. if (triangles[ti].sharesEdge(triangles[j]))
  785. {
  786. found = true;
  787. ti = static_cast<uint32>(j);
  788. break;
  789. }
  790. }
  791. }
  792. if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT)
  793. {
  794. // reorder the indexbuffer
  795. j = 0;
  796. for (i = 0; i < nTriangles; ++i)
  797. {
  798. Triangle *t = &triangles[destlist[i]];
  799. source[j++] = (uint16)t->a;
  800. source[j++] = (uint16)t->b;
  801. source[j++] = (uint16)t->c;
  802. }
  803. OGRE_FREE(triangles, MEMCATEGORY_GEOMETRY);
  804. }
  805. else
  806. {
  807. uint32 *reflist = OGRE_ALLOC_T(uint32, nTriangles, MEMCATEGORY_GEOMETRY);
  808. // fill the referencebuffer
  809. for (i = 0; i < nTriangles; ++i)
  810. reflist[destlist[i]] = static_cast<uint32>(i);
  811. // reorder the indexbuffer
  812. for (i = 0; i < nTriangles; ++i)
  813. {
  814. j = destlist[i];
  815. if (i == j) continue; // do not move triangle
  816. // swap triangles
  817. Triangle t = triangles[i];
  818. triangles[i] = triangles[j];
  819. triangles[j] = t;
  820. // change reference
  821. destlist[reflist[i]] = static_cast<uint32>(j);
  822. // destlist[i] = i; // not needed, it will not be used
  823. }
  824. OGRE_FREE(reflist, MEMCATEGORY_GEOMETRY);
  825. }
  826. OGRE_FREE(destlist, MEMCATEGORY_GEOMETRY);
  827. OGRE_FREE(visited, MEMCATEGORY_GEOMETRY);
  828. indexBuffer->unlock();
  829. }
  830. //-----------------------------------------------------------------------
  831. //-----------------------------------------------------------------------
  832. void VertexCacheProfiler::profile(const HardwareIndexBufferPtr& indexBuffer)
  833. {
  834. if (indexBuffer->isLocked()) return;
  835. uint16 *shortbuffer = (uint16 *)indexBuffer->lock(HardwareBuffer::HBL_READ_ONLY);
  836. if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT)
  837. for (unsigned int i = 0; i < indexBuffer->getNumIndexes(); ++i)
  838. inCache(shortbuffer[i]);
  839. else
  840. {
  841. uint32 *buffer = (uint32 *)shortbuffer;
  842. for (unsigned int i = 0; i < indexBuffer->getNumIndexes(); ++i)
  843. inCache(buffer[i]);
  844. }
  845. indexBuffer->unlock();
  846. }
  847. //-----------------------------------------------------------------------
  848. bool VertexCacheProfiler::inCache(unsigned int index)
  849. {
  850. for (unsigned int i = 0; i < buffersize; ++i)
  851. {
  852. if (index == cache[i])
  853. {
  854. hit++;
  855. return true;
  856. }
  857. }
  858. miss++;
  859. cache[tail++] = index;
  860. tail %= size;
  861. if (buffersize < size) buffersize++;
  862. return false;
  863. }
  864. }