CmVertexIndexData.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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 "CmException.h"
  31. #include "CmRenderSystem.h"
  32. #include "CmRenderSystemManager.h"
  33. namespace CamelotEngine {
  34. //-----------------------------------------------------------------------
  35. VertexData::VertexData(HardwareBufferManagerBase* mgr)
  36. {
  37. mMgr = mgr ? mgr : HardwareBufferManager::instancePtr();
  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::instancePtr();
  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. CM_EXCEPT(ItemIdentityException,
  350. "Element not found in old vertex declaration");
  351. }
  352. newToOldElementMap[&(*ei)] = oldElem;
  353. }
  354. // Now iterate over the new buffers, pulling data out of the old ones
  355. // For each vertex
  356. for (size_t v = 0; v < vertexCount; ++v)
  357. {
  358. // For each (new) element
  359. for (ei = newElemList.begin(); ei != eiend; ++ei)
  360. {
  361. const VertexElement* newElem = &(*ei);
  362. NewToOldElementMap::iterator noi = newToOldElementMap.find(newElem);
  363. const VertexElement* oldElem = noi->second;
  364. unsigned short oldBufferNo = oldElem->getSource();
  365. unsigned short newBufferNo = newElem->getSource();
  366. void* pSrcBase = static_cast<void*>(
  367. static_cast<unsigned char*>(oldBufferLocks[oldBufferNo])
  368. + v * oldBufferVertexSizes[oldBufferNo]);
  369. void* pDstBase = static_cast<void*>(
  370. static_cast<unsigned char*>(newBufferLocks[newBufferNo])
  371. + v * newBufferVertexSizes[newBufferNo]);
  372. void *pSrc, *pDst;
  373. oldElem->baseVertexPointerToElement(pSrcBase, &pSrc);
  374. newElem->baseVertexPointerToElement(pDstBase, &pDst);
  375. memcpy(pDst, pSrc, newElem->getSize());
  376. }
  377. }
  378. // Unlock all buffers
  379. for (itBinding = oldBindingMap.begin(); itBinding != oldBindingMap.end(); ++itBinding)
  380. {
  381. itBinding->second->unlock();
  382. }
  383. for (buf = 0; buf < newBinding->getBufferCount(); ++buf)
  384. {
  385. newBinding->getBuffer(buf)->unlock();
  386. }
  387. // Delete old binding & declaration
  388. if (mDeleteDclBinding)
  389. {
  390. pManager->destroyVertexBufferBinding(vertexBufferBinding);
  391. pManager->destroyVertexDeclaration(vertexDeclaration);
  392. }
  393. // Assign new binding and declaration
  394. vertexDeclaration = newDeclaration;
  395. vertexBufferBinding = newBinding;
  396. // after this is complete, new manager should be used
  397. mMgr = pManager;
  398. mDeleteDclBinding = true; // because we created these through a manager
  399. }
  400. //-----------------------------------------------------------------------
  401. void VertexData::reorganiseBuffers(VertexDeclaration* newDeclaration, HardwareBufferManagerBase* mgr)
  402. {
  403. // Derive the buffer usages from looking at where the source has come
  404. // from
  405. BufferUsageList usages;
  406. for (unsigned short b = 0; b <= newDeclaration->getMaxSource(); ++b)
  407. {
  408. VertexDeclaration::VertexElementList destElems = newDeclaration->findElementsBySource(b);
  409. // Initialise with most restrictive version
  410. // (not really a usable option, but these flags will be removed)
  411. HardwareBuffer::Usage final = static_cast<HardwareBuffer::Usage>(
  412. HardwareBuffer::HBU_STATIC_WRITE_ONLY | HardwareBuffer::HBU_DISCARDABLE);
  413. VertexDeclaration::VertexElementList::iterator v;
  414. for (v = destElems.begin(); v != destElems.end(); ++v)
  415. {
  416. VertexElement& destelem = *v;
  417. // get source
  418. const VertexElement* srcelem =
  419. vertexDeclaration->findElementBySemantic(
  420. destelem.getSemantic(), destelem.getIndex());
  421. // get buffer
  422. HardwareVertexBufferPtr srcbuf =
  423. vertexBufferBinding->getBuffer(srcelem->getSource());
  424. // improve flexibility only
  425. if (srcbuf->getUsage() & HardwareBuffer::HBU_DYNAMIC)
  426. {
  427. // remove static
  428. final = static_cast<HardwareBuffer::Usage>(
  429. final & ~HardwareBuffer::HBU_STATIC);
  430. // add dynamic
  431. final = static_cast<HardwareBuffer::Usage>(
  432. final | HardwareBuffer::HBU_DYNAMIC);
  433. }
  434. if (!(srcbuf->getUsage() & HardwareBuffer::HBU_WRITE_ONLY))
  435. {
  436. // remove write only
  437. final = static_cast<HardwareBuffer::Usage>(
  438. final & ~HardwareBuffer::HBU_WRITE_ONLY);
  439. }
  440. if (!(srcbuf->getUsage() & HardwareBuffer::HBU_DISCARDABLE))
  441. {
  442. // remove discardable
  443. final = static_cast<HardwareBuffer::Usage>(
  444. final & ~HardwareBuffer::HBU_DISCARDABLE);
  445. }
  446. }
  447. usages.push_back(final);
  448. }
  449. // Call specific method
  450. reorganiseBuffers(newDeclaration, usages, mgr);
  451. }
  452. //-----------------------------------------------------------------------
  453. void VertexData::closeGapsInBindings(void)
  454. {
  455. if (!vertexBufferBinding->hasGaps())
  456. return;
  457. // Check for error first
  458. const VertexDeclaration::VertexElementList& allelems =
  459. vertexDeclaration->getElements();
  460. VertexDeclaration::VertexElementList::const_iterator ai;
  461. for (ai = allelems.begin(); ai != allelems.end(); ++ai)
  462. {
  463. const VertexElement& elem = *ai;
  464. if (!vertexBufferBinding->isBufferBound(elem.getSource()))
  465. {
  466. CM_EXCEPT(ItemIdentityException,
  467. "No buffer is bound to that element source.");
  468. }
  469. }
  470. // Close gaps in the vertex buffer bindings
  471. VertexBufferBinding::BindingIndexMap bindingIndexMap;
  472. vertexBufferBinding->closeGaps(bindingIndexMap);
  473. // Modify vertex elements to reference to new buffer index
  474. unsigned short elemIndex = 0;
  475. for (ai = allelems.begin(); ai != allelems.end(); ++ai, ++elemIndex)
  476. {
  477. const VertexElement& elem = *ai;
  478. VertexBufferBinding::BindingIndexMap::const_iterator it =
  479. bindingIndexMap.find(elem.getSource());
  480. assert(it != bindingIndexMap.end());
  481. UINT16 targetSource = it->second;
  482. if (elem.getSource() != targetSource)
  483. {
  484. vertexDeclaration->modifyElement(elemIndex,
  485. targetSource, elem.getOffset(), elem.getType(),
  486. elem.getSemantic(), elem.getIndex());
  487. }
  488. }
  489. }
  490. //-----------------------------------------------------------------------
  491. void VertexData::removeUnusedBuffers(void)
  492. {
  493. set<UINT16>::type usedBuffers;
  494. // Collect used buffers
  495. const VertexDeclaration::VertexElementList& allelems =
  496. vertexDeclaration->getElements();
  497. VertexDeclaration::VertexElementList::const_iterator ai;
  498. for (ai = allelems.begin(); ai != allelems.end(); ++ai)
  499. {
  500. const VertexElement& elem = *ai;
  501. usedBuffers.insert(elem.getSource());
  502. }
  503. // Unset unused buffer bindings
  504. UINT16 count = vertexBufferBinding->getLastBoundIndex();
  505. for (UINT16 index = 0; index < count; ++index)
  506. {
  507. if (usedBuffers.find(index) == usedBuffers.end() &&
  508. vertexBufferBinding->isBufferBound(index))
  509. {
  510. vertexBufferBinding->unsetBinding(index);
  511. }
  512. }
  513. // Close gaps
  514. closeGapsInBindings();
  515. }
  516. //-----------------------------------------------------------------------
  517. void VertexData::convertPackedColour(
  518. VertexElementType srcType, VertexElementType destType)
  519. {
  520. if (destType != VET_COLOUR_ABGR && destType != VET_COLOUR_ARGB)
  521. {
  522. CM_EXCEPT(InvalidParametersException,
  523. "Invalid destType parameter");
  524. }
  525. if (srcType != VET_COLOUR_ABGR && srcType != VET_COLOUR_ARGB)
  526. {
  527. CM_EXCEPT(InvalidParametersException,
  528. "Invalid srcType parameter");
  529. }
  530. const VertexBufferBinding::VertexBufferBindingMap& bindMap =
  531. vertexBufferBinding->getBindings();
  532. VertexBufferBinding::VertexBufferBindingMap::const_iterator bindi;
  533. for (bindi = bindMap.begin(); bindi != bindMap.end(); ++bindi)
  534. {
  535. VertexDeclaration::VertexElementList elems =
  536. vertexDeclaration->findElementsBySource(bindi->first);
  537. bool conversionNeeded = false;
  538. VertexDeclaration::VertexElementList::iterator elemi;
  539. for (elemi = elems.begin(); elemi != elems.end(); ++elemi)
  540. {
  541. VertexElement& elem = *elemi;
  542. if (elem.getType() == VET_COLOUR ||
  543. ((elem.getType() == VET_COLOUR_ABGR || elem.getType() == VET_COLOUR_ARGB)
  544. && elem.getType() != destType))
  545. {
  546. conversionNeeded = true;
  547. }
  548. }
  549. if (conversionNeeded)
  550. {
  551. void* pBase = bindi->second->lock(HardwareBuffer::HBL_NORMAL);
  552. for (size_t v = 0; v < bindi->second->getNumVertices(); ++v)
  553. {
  554. for (elemi = elems.begin(); elemi != elems.end(); ++elemi)
  555. {
  556. VertexElement& elem = *elemi;
  557. VertexElementType currType = (elem.getType() == VET_COLOUR) ?
  558. srcType : elem.getType();
  559. if (elem.getType() == VET_COLOUR ||
  560. ((elem.getType() == VET_COLOUR_ABGR || elem.getType() == VET_COLOUR_ARGB)
  561. && elem.getType() != destType))
  562. {
  563. UINT32* pRGBA;
  564. elem.baseVertexPointerToElement(pBase, &pRGBA);
  565. VertexElement::convertColourValue(currType, destType, pRGBA);
  566. }
  567. }
  568. pBase = static_cast<void*>(
  569. static_cast<char*>(pBase) + bindi->second->getVertexSize());
  570. }
  571. bindi->second->unlock();
  572. // Modify the elements to reflect the changed type
  573. const VertexDeclaration::VertexElementList& allelems =
  574. vertexDeclaration->getElements();
  575. VertexDeclaration::VertexElementList::const_iterator ai;
  576. unsigned short elemIndex = 0;
  577. for (ai = allelems.begin(); ai != allelems.end(); ++ai, ++elemIndex)
  578. {
  579. const VertexElement& elem = *ai;
  580. if (elem.getType() == VET_COLOUR ||
  581. ((elem.getType() == VET_COLOUR_ABGR || elem.getType() == VET_COLOUR_ARGB)
  582. && elem.getType() != destType))
  583. {
  584. vertexDeclaration->modifyElement(elemIndex,
  585. elem.getSource(), elem.getOffset(), destType,
  586. elem.getSemantic(), elem.getIndex());
  587. }
  588. }
  589. }
  590. } // each buffer
  591. }
  592. //-----------------------------------------------------------------------
  593. //-----------------------------------------------------------------------
  594. IndexData::IndexData()
  595. {
  596. indexCount = 0;
  597. indexStart = 0;
  598. }
  599. //-----------------------------------------------------------------------
  600. IndexData::~IndexData()
  601. {
  602. }
  603. //-----------------------------------------------------------------------
  604. IndexData* IndexData::clone(bool copyData, HardwareBufferManagerBase* mgr) const
  605. {
  606. HardwareBufferManagerBase* pManager = mgr ? mgr : HardwareBufferManager::instancePtr();
  607. IndexData* dest = new IndexData();
  608. if (indexBuffer.get())
  609. {
  610. if (copyData)
  611. {
  612. dest->indexBuffer = pManager->createIndexBuffer(indexBuffer->getType(), indexBuffer->getNumIndexes(),
  613. indexBuffer->getUsage(), indexBuffer->hasShadowBuffer());
  614. dest->indexBuffer->copyData(*indexBuffer, 0, 0, indexBuffer->getSizeInBytes(), true);
  615. }
  616. else
  617. {
  618. dest->indexBuffer = indexBuffer;
  619. }
  620. }
  621. dest->indexCount = indexCount;
  622. dest->indexStart = indexStart;
  623. return dest;
  624. }
  625. //-----------------------------------------------------------------------
  626. //-----------------------------------------------------------------------
  627. // Local Utility class for vertex cache optimizer
  628. class Triangle
  629. {
  630. public:
  631. enum EdgeMatchType {
  632. AB, BC, CA, ANY, NONE
  633. };
  634. UINT32 a, b, c;
  635. inline Triangle()
  636. {
  637. }
  638. inline Triangle( UINT32 ta, UINT32 tb, UINT32 tc )
  639. : a( ta ), b( tb ), c( tc )
  640. {
  641. }
  642. inline Triangle( UINT32 t[3] )
  643. : a( t[0] ), b( t[1] ), c( t[2] )
  644. {
  645. }
  646. inline Triangle( const Triangle& t )
  647. : a( t.a ), b( t.b ), c( t.c )
  648. {
  649. }
  650. inline bool sharesEdge(const Triangle& t) const
  651. {
  652. return( a == t.a && b == t.c ||
  653. a == t.b && b == t.a ||
  654. a == t.c && b == t.b ||
  655. b == t.a && c == t.c ||
  656. b == t.b && c == t.a ||
  657. b == t.c && c == t.b ||
  658. c == t.a && a == t.c ||
  659. c == t.b && a == t.a ||
  660. c == t.c && a == t.b );
  661. }
  662. inline bool sharesEdge(const UINT32 ea, const UINT32 eb, const Triangle& t) const
  663. {
  664. return( ea == t.a && eb == t.c ||
  665. ea == t.b && eb == t.a ||
  666. ea == t.c && eb == t.b );
  667. }
  668. inline bool sharesEdge(const EdgeMatchType edge, const Triangle& t) const
  669. {
  670. if (edge == AB)
  671. return sharesEdge(a, b, t);
  672. else if (edge == BC)
  673. return sharesEdge(b, c, t);
  674. else if (edge == CA)
  675. return sharesEdge(c, a, t);
  676. else
  677. return (edge == ANY) == sharesEdge(t);
  678. }
  679. inline EdgeMatchType endoSharedEdge(const Triangle& t) const
  680. {
  681. if (sharesEdge(a, b, t)) return AB;
  682. if (sharesEdge(b, c, t)) return BC;
  683. if (sharesEdge(c, a, t)) return CA;
  684. return NONE;
  685. }
  686. inline EdgeMatchType exoSharedEdge(const Triangle& t) const
  687. {
  688. return t.endoSharedEdge(*this);
  689. }
  690. inline void shiftClockwise()
  691. {
  692. UINT32 t = a;
  693. a = c;
  694. c = b;
  695. b = t;
  696. }
  697. inline void shiftCounterClockwise()
  698. {
  699. UINT32 t = a;
  700. a = b;
  701. b = c;
  702. c = t;
  703. }
  704. };
  705. //-----------------------------------------------------------------------
  706. //-----------------------------------------------------------------------
  707. void IndexData::optimiseVertexCacheTriList(void)
  708. {
  709. if (indexBuffer->isLocked()) return;
  710. void *buffer = indexBuffer->lock(HardwareBuffer::HBL_NORMAL);
  711. Triangle* triangles;
  712. UINT32 *dest;
  713. size_t nIndexes = indexCount;
  714. size_t nTriangles = nIndexes / 3;
  715. size_t i, j;
  716. UINT16 *source = 0;
  717. if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT)
  718. {
  719. triangles = (Triangle*) malloc(sizeof(Triangle) * nTriangles);
  720. source = (UINT16 *)buffer;
  721. dest = (UINT32 *)triangles;
  722. for (i = 0; i < nIndexes; ++i) dest[i] = source[i];
  723. }
  724. else
  725. triangles = (Triangle*)buffer;
  726. // sort triangles based on shared edges
  727. UINT32 *destlist = (UINT32*)malloc(sizeof(UINT32) * nTriangles);
  728. unsigned char *visited = (unsigned char*)malloc(sizeof(unsigned char) * nTriangles);
  729. for (i = 0; i < nTriangles; ++i) visited[i] = 0;
  730. UINT32 start = 0, ti = 0, destcount = 0;
  731. bool found = false;
  732. for (i = 0; i < nTriangles; ++i)
  733. {
  734. if (found)
  735. found = false;
  736. else
  737. {
  738. while (visited[start++]);
  739. ti = start - 1;
  740. }
  741. destlist[destcount++] = ti;
  742. visited[ti] = 1;
  743. for (j = start; j < nTriangles; ++j)
  744. {
  745. if (visited[j]) continue;
  746. if (triangles[ti].sharesEdge(triangles[j]))
  747. {
  748. found = true;
  749. ti = static_cast<UINT32>(j);
  750. break;
  751. }
  752. }
  753. }
  754. if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT)
  755. {
  756. // reorder the indexbuffer
  757. j = 0;
  758. for (i = 0; i < nTriangles; ++i)
  759. {
  760. Triangle *t = &triangles[destlist[i]];
  761. source[j++] = (UINT16)t->a;
  762. source[j++] = (UINT16)t->b;
  763. source[j++] = (UINT16)t->c;
  764. }
  765. free(triangles);
  766. }
  767. else
  768. {
  769. UINT32 *reflist = (UINT32*)malloc(sizeof(UINT32) * nTriangles);
  770. // fill the referencebuffer
  771. for (i = 0; i < nTriangles; ++i)
  772. reflist[destlist[i]] = static_cast<UINT32>(i);
  773. // reorder the indexbuffer
  774. for (i = 0; i < nTriangles; ++i)
  775. {
  776. j = destlist[i];
  777. if (i == j) continue; // do not move triangle
  778. // swap triangles
  779. Triangle t = triangles[i];
  780. triangles[i] = triangles[j];
  781. triangles[j] = t;
  782. // change reference
  783. destlist[reflist[i]] = static_cast<UINT32>(j);
  784. // destlist[i] = i; // not needed, it will not be used
  785. }
  786. free(reflist);
  787. }
  788. free(destlist);
  789. free(visited);
  790. indexBuffer->unlock();
  791. }
  792. //-----------------------------------------------------------------------
  793. //-----------------------------------------------------------------------
  794. void VertexCacheProfiler::profile(const HardwareIndexBufferPtr& indexBuffer)
  795. {
  796. if (indexBuffer->isLocked()) return;
  797. UINT16 *shortbuffer = (UINT16 *)indexBuffer->lock(HardwareBuffer::HBL_READ_ONLY);
  798. if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT)
  799. for (unsigned int i = 0; i < indexBuffer->getNumIndexes(); ++i)
  800. inCache(shortbuffer[i]);
  801. else
  802. {
  803. UINT32 *buffer = (UINT32 *)shortbuffer;
  804. for (unsigned int i = 0; i < indexBuffer->getNumIndexes(); ++i)
  805. inCache(buffer[i]);
  806. }
  807. indexBuffer->unlock();
  808. }
  809. //-----------------------------------------------------------------------
  810. bool VertexCacheProfiler::inCache(unsigned int index)
  811. {
  812. for (unsigned int i = 0; i < buffersize; ++i)
  813. {
  814. if (index == cache[i])
  815. {
  816. hit++;
  817. return true;
  818. }
  819. }
  820. miss++;
  821. cache[tail++] = index;
  822. tail %= size;
  823. if (buffersize < size) buffersize++;
  824. return false;
  825. }
  826. }