CmVertexIndexData.cpp 33 KB

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