CmVertexIndexData.cpp 33 KB

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