btHeightfieldTerrainShape.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #include "btHeightfieldTerrainShape.h"
  14. #include "LinearMath/btTransformUtil.h"
  15. btHeightfieldTerrainShape::btHeightfieldTerrainShape(
  16. int heightStickWidth, int heightStickLength,
  17. const float* heightfieldData, btScalar minHeight, btScalar maxHeight,
  18. int upAxis, bool flipQuadEdges)
  19. : m_userValue3(0), m_triangleInfoMap(0)
  20. {
  21. initialize(heightStickWidth, heightStickLength, heightfieldData,
  22. /*heightScale=*/1, minHeight, maxHeight, upAxis, PHY_FLOAT,
  23. flipQuadEdges);
  24. }
  25. btHeightfieldTerrainShape::btHeightfieldTerrainShape(
  26. int heightStickWidth, int heightStickLength, const double* heightfieldData,
  27. btScalar minHeight, btScalar maxHeight, int upAxis, bool flipQuadEdges)
  28. : m_userValue3(0), m_triangleInfoMap(0)
  29. {
  30. initialize(heightStickWidth, heightStickLength, heightfieldData,
  31. /*heightScale=*/1, minHeight, maxHeight, upAxis, PHY_DOUBLE,
  32. flipQuadEdges);
  33. }
  34. btHeightfieldTerrainShape::btHeightfieldTerrainShape(
  35. int heightStickWidth, int heightStickLength, const short* heightfieldData, btScalar heightScale,
  36. btScalar minHeight, btScalar maxHeight, int upAxis, bool flipQuadEdges)
  37. : m_userValue3(0), m_triangleInfoMap(0)
  38. {
  39. initialize(heightStickWidth, heightStickLength, heightfieldData,
  40. heightScale, minHeight, maxHeight, upAxis, PHY_SHORT,
  41. flipQuadEdges);
  42. }
  43. btHeightfieldTerrainShape::btHeightfieldTerrainShape(
  44. int heightStickWidth, int heightStickLength, const unsigned char* heightfieldData, btScalar heightScale,
  45. btScalar minHeight, btScalar maxHeight, int upAxis, bool flipQuadEdges)
  46. : m_userValue3(0), m_triangleInfoMap(0)
  47. {
  48. initialize(heightStickWidth, heightStickLength, heightfieldData,
  49. heightScale, minHeight, maxHeight, upAxis, PHY_UCHAR,
  50. flipQuadEdges);
  51. }
  52. btHeightfieldTerrainShape::btHeightfieldTerrainShape(
  53. int heightStickWidth, int heightStickLength, const void* heightfieldData,
  54. btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis,
  55. PHY_ScalarType hdt, bool flipQuadEdges)
  56. :m_userValue3(0),
  57. m_triangleInfoMap(0)
  58. {
  59. // legacy constructor: Assumes PHY_FLOAT means btScalar.
  60. #ifdef BT_USE_DOUBLE_PRECISION
  61. if (hdt == PHY_FLOAT) hdt = PHY_DOUBLE;
  62. #endif
  63. initialize(heightStickWidth, heightStickLength, heightfieldData,
  64. heightScale, minHeight, maxHeight, upAxis, hdt,
  65. flipQuadEdges);
  66. }
  67. btHeightfieldTerrainShape::btHeightfieldTerrainShape(int heightStickWidth, int heightStickLength, const void* heightfieldData, btScalar maxHeight, int upAxis, bool useFloatData, bool flipQuadEdges)
  68. : m_userValue3(0),
  69. m_triangleInfoMap(0)
  70. {
  71. // legacy constructor: support only btScalar or unsigned char data,
  72. // and min height is zero.
  73. PHY_ScalarType hdt = (useFloatData) ? PHY_FLOAT : PHY_UCHAR;
  74. #ifdef BT_USE_DOUBLE_PRECISION
  75. if (hdt == PHY_FLOAT) hdt = PHY_DOUBLE;
  76. #endif
  77. btScalar minHeight = 0.0f;
  78. // previously, height = uchar * maxHeight / 65535.
  79. // So to preserve legacy behavior, heightScale = maxHeight / 65535
  80. btScalar heightScale = maxHeight / 65535;
  81. initialize(heightStickWidth, heightStickLength, heightfieldData,
  82. heightScale, minHeight, maxHeight, upAxis, hdt,
  83. flipQuadEdges);
  84. }
  85. void btHeightfieldTerrainShape::initialize(
  86. int heightStickWidth, int heightStickLength, const void* heightfieldData,
  87. btScalar heightScale, btScalar minHeight, btScalar maxHeight, int upAxis,
  88. PHY_ScalarType hdt, bool flipQuadEdges)
  89. {
  90. // validation
  91. btAssert(heightStickWidth > 1); // && "bad width");
  92. btAssert(heightStickLength > 1); // && "bad length");
  93. btAssert(heightfieldData); // && "null heightfield data");
  94. // btAssert(heightScale) -- do we care? Trust caller here
  95. btAssert(minHeight <= maxHeight); // && "bad min/max height");
  96. btAssert(upAxis >= 0 && upAxis < 3); // && "bad upAxis--should be in range [0,2]");
  97. btAssert(hdt != PHY_UCHAR || hdt != PHY_FLOAT || hdt != PHY_DOUBLE || hdt != PHY_SHORT); // && "Bad height data type enum");
  98. // initialize member variables
  99. m_shapeType = TERRAIN_SHAPE_PROXYTYPE;
  100. m_heightStickWidth = heightStickWidth;
  101. m_heightStickLength = heightStickLength;
  102. m_minHeight = minHeight;
  103. m_maxHeight = maxHeight;
  104. m_width = (btScalar)(heightStickWidth - 1);
  105. m_length = (btScalar)(heightStickLength - 1);
  106. m_heightScale = heightScale;
  107. m_heightfieldDataUnknown = heightfieldData;
  108. m_heightDataType = hdt;
  109. m_flipQuadEdges = flipQuadEdges;
  110. m_useDiamondSubdivision = false;
  111. m_useZigzagSubdivision = false;
  112. m_flipTriangleWinding = false;
  113. m_upAxis = upAxis;
  114. m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.));
  115. m_vboundsChunkSize = 0;
  116. m_vboundsGridWidth = 0;
  117. m_vboundsGridLength = 0;
  118. // determine min/max axis-aligned bounding box (aabb) values
  119. switch (m_upAxis)
  120. {
  121. case 0:
  122. {
  123. m_localAabbMin.setValue(m_minHeight, 0, 0);
  124. m_localAabbMax.setValue(m_maxHeight, m_width, m_length);
  125. break;
  126. }
  127. case 1:
  128. {
  129. m_localAabbMin.setValue(0, m_minHeight, 0);
  130. m_localAabbMax.setValue(m_width, m_maxHeight, m_length);
  131. break;
  132. };
  133. case 2:
  134. {
  135. m_localAabbMin.setValue(0, 0, m_minHeight);
  136. m_localAabbMax.setValue(m_width, m_length, m_maxHeight);
  137. break;
  138. }
  139. default:
  140. {
  141. //need to get valid m_upAxis
  142. btAssert(0); // && "Bad m_upAxis");
  143. }
  144. }
  145. // remember origin (defined as exact middle of aabb)
  146. m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax);
  147. }
  148. btHeightfieldTerrainShape::~btHeightfieldTerrainShape()
  149. {
  150. clearAccelerator();
  151. }
  152. void btHeightfieldTerrainShape::getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const
  153. {
  154. btVector3 halfExtents = (m_localAabbMax - m_localAabbMin) * m_localScaling * btScalar(0.5);
  155. btVector3 localOrigin(0, 0, 0);
  156. localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5);
  157. localOrigin *= m_localScaling;
  158. btMatrix3x3 abs_b = t.getBasis().absolute();
  159. btVector3 center = t.getOrigin();
  160. btVector3 extent = halfExtents.dot3(abs_b[0], abs_b[1], abs_b[2]);
  161. extent += btVector3(getMargin(), getMargin(), getMargin());
  162. aabbMin = center - extent;
  163. aabbMax = center + extent;
  164. }
  165. /// This returns the "raw" (user's initial) height, not the actual height.
  166. /// The actual height needs to be adjusted to be relative to the center
  167. /// of the heightfield's AABB.
  168. btScalar
  169. btHeightfieldTerrainShape::getRawHeightFieldValue(int x, int y) const
  170. {
  171. btScalar val = 0.f;
  172. switch (m_heightDataType)
  173. {
  174. case PHY_FLOAT:
  175. {
  176. val = m_heightfieldDataFloat[(y * m_heightStickWidth) + x];
  177. break;
  178. }
  179. case PHY_DOUBLE:
  180. {
  181. val = m_heightfieldDataDouble[(y * m_heightStickWidth) + x];
  182. break;
  183. }
  184. case PHY_UCHAR:
  185. {
  186. unsigned char heightFieldValue = m_heightfieldDataUnsignedChar[(y * m_heightStickWidth) + x];
  187. val = heightFieldValue * m_heightScale;
  188. break;
  189. }
  190. case PHY_SHORT:
  191. {
  192. short hfValue = m_heightfieldDataShort[(y * m_heightStickWidth) + x];
  193. val = hfValue * m_heightScale;
  194. break;
  195. }
  196. default:
  197. {
  198. btAssert(!"Bad m_heightDataType");
  199. }
  200. }
  201. return val;
  202. }
  203. /// this returns the vertex in bullet-local coordinates
  204. void btHeightfieldTerrainShape::getVertex(int x, int y, btVector3& vertex) const
  205. {
  206. btAssert(x >= 0);
  207. btAssert(y >= 0);
  208. btAssert(x < m_heightStickWidth);
  209. btAssert(y < m_heightStickLength);
  210. btScalar height = getRawHeightFieldValue(x, y);
  211. switch (m_upAxis)
  212. {
  213. case 0:
  214. {
  215. vertex.setValue(
  216. height - m_localOrigin.getX(),
  217. (-m_width / btScalar(2.0)) + x,
  218. (-m_length / btScalar(2.0)) + y);
  219. break;
  220. }
  221. case 1:
  222. {
  223. vertex.setValue(
  224. (-m_width / btScalar(2.0)) + x,
  225. height - m_localOrigin.getY(),
  226. (-m_length / btScalar(2.0)) + y);
  227. break;
  228. };
  229. case 2:
  230. {
  231. vertex.setValue(
  232. (-m_width / btScalar(2.0)) + x,
  233. (-m_length / btScalar(2.0)) + y,
  234. height - m_localOrigin.getZ());
  235. break;
  236. }
  237. default:
  238. {
  239. //need to get valid m_upAxis
  240. btAssert(0);
  241. }
  242. }
  243. vertex *= m_localScaling;
  244. }
  245. static inline int
  246. getQuantized(
  247. btScalar x)
  248. {
  249. if (x < 0.0)
  250. {
  251. return (int)(x - 0.5);
  252. }
  253. return (int)(x + 0.5);
  254. }
  255. // Equivalent to std::minmax({a, b, c}).
  256. // Performs at most 3 comparisons.
  257. static btHeightfieldTerrainShape::Range minmaxRange(btScalar a, btScalar b, btScalar c)
  258. {
  259. if (a > b)
  260. {
  261. if (b > c)
  262. return btHeightfieldTerrainShape::Range(c, a);
  263. else if (a > c)
  264. return btHeightfieldTerrainShape::Range(b, a);
  265. else
  266. return btHeightfieldTerrainShape::Range(b, c);
  267. }
  268. else
  269. {
  270. if (a > c)
  271. return btHeightfieldTerrainShape::Range(c, b);
  272. else if (b > c)
  273. return btHeightfieldTerrainShape::Range(a, b);
  274. else
  275. return btHeightfieldTerrainShape::Range(a, c);
  276. }
  277. }
  278. /// given input vector, return quantized version
  279. /**
  280. This routine is basically determining the gridpoint indices for a given
  281. input vector, answering the question: "which gridpoint is closest to the
  282. provided point?".
  283. "with clamp" means that we restrict the point to be in the heightfield's
  284. axis-aligned bounding box.
  285. */
  286. void btHeightfieldTerrainShape::quantizeWithClamp(int* out, const btVector3& point, int /*isMax*/) const
  287. {
  288. btVector3 clampedPoint(point);
  289. clampedPoint.setMax(m_localAabbMin);
  290. clampedPoint.setMin(m_localAabbMax);
  291. out[0] = getQuantized(clampedPoint.getX());
  292. out[1] = getQuantized(clampedPoint.getY());
  293. out[2] = getQuantized(clampedPoint.getZ());
  294. }
  295. /// process all triangles within the provided axis-aligned bounding box
  296. /**
  297. basic algorithm:
  298. - convert input aabb to local coordinates (scale down and shift for local origin)
  299. - convert input aabb to a range of heightfield grid points (quantize)
  300. - iterate over all triangles in that subset of the grid
  301. */
  302. void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback, const btVector3& aabbMin, const btVector3& aabbMax) const
  303. {
  304. // scale down the input aabb's so they are in local (non-scaled) coordinates
  305. btVector3 localAabbMin = aabbMin * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]);
  306. btVector3 localAabbMax = aabbMax * btVector3(1.f / m_localScaling[0], 1.f / m_localScaling[1], 1.f / m_localScaling[2]);
  307. // account for local origin
  308. localAabbMin += m_localOrigin;
  309. localAabbMax += m_localOrigin;
  310. //quantize the aabbMin and aabbMax, and adjust the start/end ranges
  311. int quantizedAabbMin[3];
  312. int quantizedAabbMax[3];
  313. quantizeWithClamp(quantizedAabbMin, localAabbMin, 0);
  314. quantizeWithClamp(quantizedAabbMax, localAabbMax, 1);
  315. // expand the min/max quantized values
  316. // this is to catch the case where the input aabb falls between grid points!
  317. for (int i = 0; i < 3; ++i)
  318. {
  319. quantizedAabbMin[i]--;
  320. quantizedAabbMax[i]++;
  321. }
  322. int startX = 0;
  323. int endX = m_heightStickWidth - 1;
  324. int startJ = 0;
  325. int endJ = m_heightStickLength - 1;
  326. switch (m_upAxis)
  327. {
  328. case 0:
  329. {
  330. if (quantizedAabbMin[1] > startX)
  331. startX = quantizedAabbMin[1];
  332. if (quantizedAabbMax[1] < endX)
  333. endX = quantizedAabbMax[1];
  334. if (quantizedAabbMin[2] > startJ)
  335. startJ = quantizedAabbMin[2];
  336. if (quantizedAabbMax[2] < endJ)
  337. endJ = quantizedAabbMax[2];
  338. break;
  339. }
  340. case 1:
  341. {
  342. if (quantizedAabbMin[0] > startX)
  343. startX = quantizedAabbMin[0];
  344. if (quantizedAabbMax[0] < endX)
  345. endX = quantizedAabbMax[0];
  346. if (quantizedAabbMin[2] > startJ)
  347. startJ = quantizedAabbMin[2];
  348. if (quantizedAabbMax[2] < endJ)
  349. endJ = quantizedAabbMax[2];
  350. break;
  351. };
  352. case 2:
  353. {
  354. if (quantizedAabbMin[0] > startX)
  355. startX = quantizedAabbMin[0];
  356. if (quantizedAabbMax[0] < endX)
  357. endX = quantizedAabbMax[0];
  358. if (quantizedAabbMin[1] > startJ)
  359. startJ = quantizedAabbMin[1];
  360. if (quantizedAabbMax[1] < endJ)
  361. endJ = quantizedAabbMax[1];
  362. break;
  363. }
  364. default:
  365. {
  366. //need to get valid m_upAxis
  367. btAssert(0);
  368. }
  369. }
  370. // TODO If m_vboundsGrid is available, use it to determine if we really need to process this area
  371. const Range aabbUpRange(aabbMin[m_upAxis], aabbMax[m_upAxis]);
  372. for (int j = startJ; j < endJ; j++)
  373. {
  374. for (int x = startX; x < endX; x++)
  375. {
  376. btVector3 vertices[3];
  377. int indices[3] = { 0, 1, 2 };
  378. if (m_flipTriangleWinding)
  379. {
  380. indices[0] = 2;
  381. indices[2] = 0;
  382. }
  383. if (m_flipQuadEdges || (m_useDiamondSubdivision && !((j + x) & 1)) || (m_useZigzagSubdivision && !(j & 1)))
  384. {
  385. getVertex(x, j, vertices[indices[0]]);
  386. getVertex(x, j + 1, vertices[indices[1]]);
  387. getVertex(x + 1, j + 1, vertices[indices[2]]);
  388. // Skip triangle processing if the triangle is out-of-AABB.
  389. Range upRange = minmaxRange(vertices[0][m_upAxis], vertices[1][m_upAxis], vertices[2][m_upAxis]);
  390. if (upRange.overlaps(aabbUpRange))
  391. callback->processTriangle(vertices, 2 * x, j);
  392. // already set: getVertex(x, j, vertices[indices[0]])
  393. // equivalent to: getVertex(x + 1, j + 1, vertices[indices[1]]);
  394. vertices[indices[1]] = vertices[indices[2]];
  395. getVertex(x + 1, j, vertices[indices[2]]);
  396. upRange.min = btMin(upRange.min, vertices[indices[2]][m_upAxis]);
  397. upRange.max = btMax(upRange.max, vertices[indices[2]][m_upAxis]);
  398. if (upRange.overlaps(aabbUpRange))
  399. callback->processTriangle(vertices, 2 * x + 1, j);
  400. }
  401. else
  402. {
  403. getVertex(x, j, vertices[indices[0]]);
  404. getVertex(x, j + 1, vertices[indices[1]]);
  405. getVertex(x + 1, j, vertices[indices[2]]);
  406. // Skip triangle processing if the triangle is out-of-AABB.
  407. Range upRange = minmaxRange(vertices[0][m_upAxis], vertices[1][m_upAxis], vertices[2][m_upAxis]);
  408. if (upRange.overlaps(aabbUpRange))
  409. callback->processTriangle(vertices, 2 * x, j);
  410. // already set: getVertex(x, j + 1, vertices[indices[1]]);
  411. // equivalent to: getVertex(x + 1, j, vertices[indices[0]]);
  412. vertices[indices[0]] = vertices[indices[2]];
  413. getVertex(x + 1, j + 1, vertices[indices[2]]);
  414. upRange.min = btMin(upRange.min, vertices[indices[2]][m_upAxis]);
  415. upRange.max = btMax(upRange.max, vertices[indices[2]][m_upAxis]);
  416. if (upRange.overlaps(aabbUpRange))
  417. callback->processTriangle(vertices, 2 * x + 1, j);
  418. }
  419. }
  420. }
  421. }
  422. void btHeightfieldTerrainShape::calculateLocalInertia(btScalar, btVector3& inertia) const
  423. {
  424. //moving concave objects not supported
  425. inertia.setValue(btScalar(0.), btScalar(0.), btScalar(0.));
  426. }
  427. void btHeightfieldTerrainShape::setLocalScaling(const btVector3& scaling)
  428. {
  429. m_localScaling = scaling;
  430. }
  431. const btVector3& btHeightfieldTerrainShape::getLocalScaling() const
  432. {
  433. return m_localScaling;
  434. }
  435. namespace
  436. {
  437. struct GridRaycastState
  438. {
  439. int x; // Next quad coords
  440. int z;
  441. int prev_x; // Previous quad coords
  442. int prev_z;
  443. btScalar param; // Exit param for previous quad
  444. btScalar prevParam; // Enter param for previous quad
  445. btScalar maxDistanceFlat;
  446. btScalar maxDistance3d;
  447. };
  448. }
  449. // TODO Does it really need to take 3D vectors?
  450. /// Iterates through a virtual 2D grid of unit-sized square cells,
  451. /// and executes an action on each cell intersecting the given segment, ordered from begin to end.
  452. /// Initially inspired by http://www.cse.yorku.ca/~amana/research/grid.pdf
  453. template <typename Action_T>
  454. void gridRaycast(Action_T& quadAction, const btVector3& beginPos, const btVector3& endPos, int indices[3])
  455. {
  456. GridRaycastState rs;
  457. rs.maxDistance3d = beginPos.distance(endPos);
  458. if (rs.maxDistance3d < 0.0001)
  459. {
  460. // Consider the ray is too small to hit anything
  461. return;
  462. }
  463. btScalar rayDirectionFlatX = endPos[indices[0]] - beginPos[indices[0]];
  464. btScalar rayDirectionFlatZ = endPos[indices[2]] - beginPos[indices[2]];
  465. rs.maxDistanceFlat = btSqrt(rayDirectionFlatX * rayDirectionFlatX + rayDirectionFlatZ * rayDirectionFlatZ);
  466. if (rs.maxDistanceFlat < 0.0001)
  467. {
  468. // Consider the ray vertical
  469. rayDirectionFlatX = 0;
  470. rayDirectionFlatZ = 0;
  471. }
  472. else
  473. {
  474. rayDirectionFlatX /= rs.maxDistanceFlat;
  475. rayDirectionFlatZ /= rs.maxDistanceFlat;
  476. }
  477. const int xiStep = rayDirectionFlatX > 0 ? 1 : rayDirectionFlatX < 0 ? -1 : 0;
  478. const int ziStep = rayDirectionFlatZ > 0 ? 1 : rayDirectionFlatZ < 0 ? -1 : 0;
  479. const float infinite = 9999999;
  480. const btScalar paramDeltaX = xiStep != 0 ? 1.f / btFabs(rayDirectionFlatX) : infinite;
  481. const btScalar paramDeltaZ = ziStep != 0 ? 1.f / btFabs(rayDirectionFlatZ) : infinite;
  482. // pos = param * dir
  483. btScalar paramCrossX; // At which value of `param` we will cross a x-axis lane?
  484. btScalar paramCrossZ; // At which value of `param` we will cross a z-axis lane?
  485. // paramCrossX and paramCrossZ are initialized as being the first cross
  486. // X initialization
  487. if (xiStep != 0)
  488. {
  489. if (xiStep == 1)
  490. {
  491. paramCrossX = (ceil(beginPos[indices[0]]) - beginPos[indices[0]]) * paramDeltaX;
  492. }
  493. else
  494. {
  495. paramCrossX = (beginPos[indices[0]] - floor(beginPos[indices[0]])) * paramDeltaX;
  496. }
  497. }
  498. else
  499. {
  500. paramCrossX = infinite; // Will never cross on X
  501. }
  502. // Z initialization
  503. if (ziStep != 0)
  504. {
  505. if (ziStep == 1)
  506. {
  507. paramCrossZ = (ceil(beginPos[indices[2]]) - beginPos[indices[2]]) * paramDeltaZ;
  508. }
  509. else
  510. {
  511. paramCrossZ = (beginPos[indices[2]] - floor(beginPos[indices[2]])) * paramDeltaZ;
  512. }
  513. }
  514. else
  515. {
  516. paramCrossZ = infinite; // Will never cross on Z
  517. }
  518. rs.x = static_cast<int>(floor(beginPos[indices[0]]));
  519. rs.z = static_cast<int>(floor(beginPos[indices[2]]));
  520. // Workaround cases where the ray starts at an integer position
  521. if (paramCrossX == 0.0)
  522. {
  523. paramCrossX += paramDeltaX;
  524. // If going backwards, we should ignore the position we would get by the above flooring,
  525. // because the ray is not heading in that direction
  526. if (xiStep == -1)
  527. {
  528. rs.x -= 1;
  529. }
  530. }
  531. if (paramCrossZ == 0.0)
  532. {
  533. paramCrossZ += paramDeltaZ;
  534. if (ziStep == -1)
  535. rs.z -= 1;
  536. }
  537. rs.prev_x = rs.x;
  538. rs.prev_z = rs.z;
  539. rs.param = 0;
  540. while (true)
  541. {
  542. rs.prev_x = rs.x;
  543. rs.prev_z = rs.z;
  544. rs.prevParam = rs.param;
  545. if (paramCrossX < paramCrossZ)
  546. {
  547. // X lane
  548. rs.x += xiStep;
  549. // Assign before advancing the param,
  550. // to be in sync with the initialization step
  551. rs.param = paramCrossX;
  552. paramCrossX += paramDeltaX;
  553. }
  554. else
  555. {
  556. // Z lane
  557. rs.z += ziStep;
  558. rs.param = paramCrossZ;
  559. paramCrossZ += paramDeltaZ;
  560. }
  561. if (rs.param > rs.maxDistanceFlat)
  562. {
  563. rs.param = rs.maxDistanceFlat;
  564. quadAction(rs);
  565. break;
  566. }
  567. else
  568. {
  569. quadAction(rs);
  570. }
  571. }
  572. }
  573. struct ProcessTrianglesAction
  574. {
  575. const btHeightfieldTerrainShape* shape;
  576. bool flipQuadEdges;
  577. bool useDiamondSubdivision;
  578. int width;
  579. int length;
  580. btTriangleCallback* callback;
  581. void exec(int x, int z) const
  582. {
  583. if (x < 0 || z < 0 || x >= width || z >= length)
  584. {
  585. return;
  586. }
  587. btVector3 vertices[3];
  588. // TODO Since this is for raycasts, we could greatly benefit from an early exit on the first hit
  589. // Check quad
  590. if (flipQuadEdges || (useDiamondSubdivision && (((z + x) & 1) > 0)))
  591. {
  592. // First triangle
  593. shape->getVertex(x, z, vertices[0]);
  594. shape->getVertex(x + 1, z, vertices[1]);
  595. shape->getVertex(x + 1, z + 1, vertices[2]);
  596. callback->processTriangle(vertices, x, z);
  597. // Second triangle
  598. shape->getVertex(x, z, vertices[0]);
  599. shape->getVertex(x + 1, z + 1, vertices[1]);
  600. shape->getVertex(x, z + 1, vertices[2]);
  601. callback->processTriangle(vertices, x, z);
  602. }
  603. else
  604. {
  605. // First triangle
  606. shape->getVertex(x, z, vertices[0]);
  607. shape->getVertex(x, z + 1, vertices[1]);
  608. shape->getVertex(x + 1, z, vertices[2]);
  609. callback->processTriangle(vertices, x, z);
  610. // Second triangle
  611. shape->getVertex(x + 1, z, vertices[0]);
  612. shape->getVertex(x, z + 1, vertices[1]);
  613. shape->getVertex(x + 1, z + 1, vertices[2]);
  614. callback->processTriangle(vertices, x, z);
  615. }
  616. }
  617. void operator()(const GridRaycastState& bs) const
  618. {
  619. exec(bs.prev_x, bs.prev_z);
  620. }
  621. };
  622. struct ProcessVBoundsAction
  623. {
  624. const btAlignedObjectArray<btHeightfieldTerrainShape::Range>& vbounds;
  625. int width;
  626. int length;
  627. int chunkSize;
  628. btVector3 rayBegin;
  629. btVector3 rayEnd;
  630. btVector3 rayDir;
  631. int* m_indices;
  632. ProcessTrianglesAction processTriangles;
  633. ProcessVBoundsAction(const btAlignedObjectArray<btHeightfieldTerrainShape::Range>& bnd, int* indices)
  634. : vbounds(bnd),
  635. m_indices(indices)
  636. {
  637. }
  638. void operator()(const GridRaycastState& rs) const
  639. {
  640. int x = rs.prev_x;
  641. int z = rs.prev_z;
  642. if (x < 0 || z < 0 || x >= width || z >= length)
  643. {
  644. return;
  645. }
  646. const btHeightfieldTerrainShape::Range chunk = vbounds[x + z * width];
  647. btVector3 enterPos;
  648. btVector3 exitPos;
  649. if (rs.maxDistanceFlat > 0.0001)
  650. {
  651. btScalar flatTo3d = chunkSize * rs.maxDistance3d / rs.maxDistanceFlat;
  652. btScalar enterParam3d = rs.prevParam * flatTo3d;
  653. btScalar exitParam3d = rs.param * flatTo3d;
  654. enterPos = rayBegin + rayDir * enterParam3d;
  655. exitPos = rayBegin + rayDir * exitParam3d;
  656. // We did enter the flat projection of the AABB,
  657. // but we have to check if we intersect it on the vertical axis
  658. if (enterPos[1] > chunk.max && exitPos[m_indices[1]] > chunk.max)
  659. {
  660. return;
  661. }
  662. if (enterPos[1] < chunk.min && exitPos[m_indices[1]] < chunk.min)
  663. {
  664. return;
  665. }
  666. }
  667. else
  668. {
  669. // Consider the ray vertical
  670. // (though we shouldn't reach this often because there is an early check up-front)
  671. enterPos = rayBegin;
  672. exitPos = rayEnd;
  673. }
  674. gridRaycast(processTriangles, enterPos, exitPos, m_indices);
  675. // Note: it could be possible to have more than one grid at different levels,
  676. // to do this there would be a branch using a pointer to another ProcessVBoundsAction
  677. }
  678. };
  679. // TODO How do I interrupt the ray when there is a hit? `callback` does not return any result
  680. /// Performs a raycast using a hierarchical Bresenham algorithm.
  681. /// Does not allocate any memory by itself.
  682. void btHeightfieldTerrainShape::performRaycast(btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget) const
  683. {
  684. // Transform to cell-local
  685. btVector3 beginPos = raySource / m_localScaling;
  686. btVector3 endPos = rayTarget / m_localScaling;
  687. beginPos += m_localOrigin;
  688. endPos += m_localOrigin;
  689. ProcessTrianglesAction processTriangles;
  690. processTriangles.shape = this;
  691. processTriangles.flipQuadEdges = m_flipQuadEdges;
  692. processTriangles.useDiamondSubdivision = m_useDiamondSubdivision;
  693. processTriangles.callback = callback;
  694. processTriangles.width = m_heightStickWidth - 1;
  695. processTriangles.length = m_heightStickLength - 1;
  696. // TODO Transform vectors to account for m_upAxis
  697. int indices[3] = { 0, 1, 2 };
  698. if (m_upAxis == 2)
  699. {
  700. indices[1] = 2;
  701. indices[2] = 1;
  702. }
  703. int iBeginX = static_cast<int>(floor(beginPos[indices[0]]));
  704. int iBeginZ = static_cast<int>(floor(beginPos[indices[2]]));
  705. int iEndX = static_cast<int>(floor(endPos[indices[0]]));
  706. int iEndZ = static_cast<int>(floor(endPos[indices[2]]));
  707. if (iBeginX == iEndX && iBeginZ == iEndZ)
  708. {
  709. // The ray will never cross quads within the plane,
  710. // so directly process triangles within one quad
  711. // (typically, vertical rays should end up here)
  712. processTriangles.exec(iBeginX, iEndZ);
  713. return;
  714. }
  715. if (m_vboundsGrid.size()==0)
  716. {
  717. // Process all quads intersecting the flat projection of the ray
  718. gridRaycast(processTriangles, beginPos, endPos, &indices[0]);
  719. }
  720. else
  721. {
  722. btVector3 rayDiff = endPos - beginPos;
  723. btScalar flatDistance2 = rayDiff[indices[0]] * rayDiff[indices[0]] + rayDiff[indices[2]] * rayDiff[indices[2]];
  724. if (flatDistance2 < m_vboundsChunkSize * m_vboundsChunkSize)
  725. {
  726. // Don't use chunks, the ray is too short in the plane
  727. gridRaycast(processTriangles, beginPos, endPos, &indices[0]);
  728. }
  729. ProcessVBoundsAction processVBounds(m_vboundsGrid, &indices[0]);
  730. processVBounds.width = m_vboundsGridWidth;
  731. processVBounds.length = m_vboundsGridLength;
  732. processVBounds.rayBegin = beginPos;
  733. processVBounds.rayEnd = endPos;
  734. processVBounds.rayDir = rayDiff.normalized();
  735. processVBounds.processTriangles = processTriangles;
  736. processVBounds.chunkSize = m_vboundsChunkSize;
  737. // The ray is long, run raycast on a higher-level grid
  738. gridRaycast(processVBounds, beginPos / m_vboundsChunkSize, endPos / m_vboundsChunkSize, indices);
  739. }
  740. }
  741. /// Builds a grid data structure storing the min and max heights of the terrain in chunks.
  742. /// if chunkSize is zero, that accelerator is removed.
  743. /// If you modify the heights, you need to rebuild this accelerator.
  744. void btHeightfieldTerrainShape::buildAccelerator(int chunkSize)
  745. {
  746. if (chunkSize <= 0)
  747. {
  748. clearAccelerator();
  749. return;
  750. }
  751. m_vboundsChunkSize = chunkSize;
  752. int nChunksX = m_heightStickWidth / chunkSize;
  753. int nChunksZ = m_heightStickLength / chunkSize;
  754. if (m_heightStickWidth % chunkSize > 0)
  755. {
  756. ++nChunksX; // In case terrain size isn't dividable by chunk size
  757. }
  758. if (m_heightStickLength % chunkSize > 0)
  759. {
  760. ++nChunksZ;
  761. }
  762. if (m_vboundsGridWidth != nChunksX || m_vboundsGridLength != nChunksZ)
  763. {
  764. clearAccelerator();
  765. m_vboundsGridWidth = nChunksX;
  766. m_vboundsGridLength = nChunksZ;
  767. }
  768. if (nChunksX == 0 || nChunksZ == 0)
  769. {
  770. return;
  771. }
  772. // This data structure is only reallocated if the required size changed
  773. m_vboundsGrid.resize(nChunksX * nChunksZ);
  774. // Compute min and max height for all chunks
  775. for (int cz = 0; cz < nChunksZ; ++cz)
  776. {
  777. int z0 = cz * chunkSize;
  778. for (int cx = 0; cx < nChunksX; ++cx)
  779. {
  780. int x0 = cx * chunkSize;
  781. Range r;
  782. r.min = getRawHeightFieldValue(x0, z0);
  783. r.max = r.min;
  784. // Compute min and max height for this chunk.
  785. // We have to include one extra cell to account for neighbors.
  786. // Here is why:
  787. // Say we have a flat terrain, and a plateau that fits a chunk perfectly.
  788. //
  789. // Left Right
  790. // 0---0---0---1---1---1
  791. // | | | | | |
  792. // 0---0---0---1---1---1
  793. // | | | | | |
  794. // 0---0---0---1---1---1
  795. // x
  796. //
  797. // If the AABB for the Left chunk did not share vertices with the Right,
  798. // then we would fail collision tests at x due to a gap.
  799. //
  800. for (int z = z0; z < z0 + chunkSize + 1; ++z)
  801. {
  802. if (z >= m_heightStickLength)
  803. {
  804. continue;
  805. }
  806. for (int x = x0; x < x0 + chunkSize + 1; ++x)
  807. {
  808. if (x >= m_heightStickWidth)
  809. {
  810. continue;
  811. }
  812. btScalar height = getRawHeightFieldValue(x, z);
  813. if (height < r.min)
  814. {
  815. r.min = height;
  816. }
  817. else if (height > r.max)
  818. {
  819. r.max = height;
  820. }
  821. }
  822. }
  823. m_vboundsGrid[cx + cz * nChunksX] = r;
  824. }
  825. }
  826. }
  827. void btHeightfieldTerrainShape::clearAccelerator()
  828. {
  829. m_vboundsGrid.clear();
  830. }