HeightFieldShape.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Collision/Shape/HeightFieldShape.h>
  6. #include <Jolt/Physics/Collision/Shape/ConvexShape.h>
  7. #include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
  8. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  9. #include <Jolt/Physics/Collision/RayCast.h>
  10. #include <Jolt/Physics/Collision/ShapeCast.h>
  11. #include <Jolt/Physics/Collision/CastResult.h>
  12. #include <Jolt/Physics/Collision/CollidePointResult.h>
  13. #include <Jolt/Physics/Collision/ShapeFilter.h>
  14. #include <Jolt/Physics/Collision/CastConvexVsTriangles.h>
  15. #include <Jolt/Physics/Collision/CastSphereVsTriangles.h>
  16. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  17. #include <Jolt/Physics/Collision/CollideSphereVsTriangles.h>
  18. #include <Jolt/Physics/Collision/TransformedShape.h>
  19. #include <Jolt/Physics/Collision/ActiveEdges.h>
  20. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  21. #include <Jolt/Physics/Collision/SortReverseAndStore.h>
  22. #include <Jolt/Core/Profiler.h>
  23. #include <Jolt/Core/StringTools.h>
  24. #include <Jolt/Core/StreamIn.h>
  25. #include <Jolt/Core/StreamOut.h>
  26. #include <Jolt/Geometry/AABox4.h>
  27. #include <Jolt/Geometry/RayTriangle.h>
  28. #include <Jolt/Geometry/RayAABox.h>
  29. #include <Jolt/Geometry/OrientedBox.h>
  30. #include <Jolt/ObjectStream/TypeDeclarations.h>
  31. //#define JPH_DEBUG_HEIGHT_FIELD
  32. JPH_NAMESPACE_BEGIN
  33. #ifdef JPH_DEBUG_RENDERER
  34. bool HeightFieldShape::sDrawTriangleOutlines = false;
  35. #endif // JPH_DEBUG_RENDERER
  36. using namespace HeightFieldShapeConstants;
  37. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(HeightFieldShapeSettings)
  38. {
  39. JPH_ADD_BASE_CLASS(HeightFieldShapeSettings, ShapeSettings)
  40. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mHeightSamples)
  41. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mOffset)
  42. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mScale)
  43. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mSampleCount)
  44. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBlockSize)
  45. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBitsPerSample)
  46. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterialIndices)
  47. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterials)
  48. }
  49. const uint HeightFieldShape::sGridOffsets[] =
  50. {
  51. 0, // level: 0, max x/y: 0, offset: 0
  52. 1, // level: 1, max x/y: 1, offset: 1
  53. 5, // level: 2, max x/y: 3, offset: 1 + 4
  54. 21, // level: 3, max x/y: 7, offset: 1 + 4 + 16
  55. 85, // level: 4, max x/y: 15, offset: 1 + 4 + 16 + 64
  56. 341, // level: 5, max x/y: 31, offset: 1 + 4 + 16 + 64 + 256
  57. 1365, // level: 6, max x/y: 63, offset: 1 + 4 + 16 + 64 + 256 + 1024
  58. 5461, // level: 7, max x/y: 127, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096
  59. 21845, // level: 8, max x/y: 255, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  60. 87381, // level: 9, max x/y: 511, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  61. 349525, // level: 10, max x/y: 1023, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  62. 1398101, // level: 11, max x/y: 2047, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  63. 5592405, // level: 12, max x/y: 4095, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  64. 22369621, // level: 13, max x/y: 8191, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  65. 89478485, // level: 14, max x/y: 16383, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  66. };
  67. HeightFieldShapeSettings::HeightFieldShapeSettings(const float *inSamples, Vec3Arg inOffset, Vec3Arg inScale, uint32 inSampleCount, const uint8 *inMaterialIndices, const PhysicsMaterialList &inMaterialList) :
  68. mOffset(inOffset),
  69. mScale(inScale),
  70. mSampleCount(inSampleCount)
  71. {
  72. mHeightSamples.resize(inSampleCount * inSampleCount);
  73. memcpy(&mHeightSamples[0], inSamples, inSampleCount * inSampleCount * sizeof(float));
  74. if (!inMaterialList.empty() && inMaterialIndices != nullptr)
  75. {
  76. mMaterialIndices.resize(Square(inSampleCount - 1));
  77. memcpy(&mMaterialIndices[0], inMaterialIndices, Square(inSampleCount - 1) * sizeof(uint8));
  78. mMaterials = inMaterialList;
  79. }
  80. else
  81. {
  82. JPH_ASSERT(inMaterialList.empty());
  83. JPH_ASSERT(inMaterialIndices == nullptr);
  84. }
  85. }
  86. ShapeSettings::ShapeResult HeightFieldShapeSettings::Create() const
  87. {
  88. if (mCachedResult.IsEmpty())
  89. Ref<Shape> shape = new HeightFieldShape(*this, mCachedResult);
  90. return mCachedResult;
  91. }
  92. void HeightFieldShapeSettings::DetermineMinAndMaxSample(float &outMinValue, float &outMaxValue, float &outQuantizationScale) const
  93. {
  94. // Determine min and max value
  95. outMinValue = FLT_MAX;
  96. outMaxValue = -FLT_MAX;
  97. for (float h : mHeightSamples)
  98. if (h != cNoCollisionValue)
  99. {
  100. outMinValue = min(outMinValue, h);
  101. outMaxValue = max(outMaxValue, h);
  102. }
  103. // Prevent dividing by zero by setting a minimal height difference
  104. float height_diff = max(outMaxValue - outMinValue, 1.0e-6f);
  105. // Calculate the scale factor to quantize to 16 bits
  106. outQuantizationScale = float(cMaxHeightValue16) / height_diff;
  107. }
  108. uint32 HeightFieldShapeSettings::CalculateBitsPerSampleForError(float inMaxError) const
  109. {
  110. // Start with 1 bit per sample
  111. uint32 bits_per_sample = 1;
  112. // Determine total range
  113. float min_value, max_value, scale;
  114. DetermineMinAndMaxSample(min_value, max_value, scale);
  115. if (min_value < max_value)
  116. {
  117. // Loop over all blocks
  118. for (uint y = 0; y < mSampleCount; y += mBlockSize)
  119. for (uint x = 0; x < mSampleCount; x += mBlockSize)
  120. {
  121. // Determine min and max block value + take 1 sample border just like we do while building the hierarchical grids
  122. float block_min_value = FLT_MAX, block_max_value = -FLT_MAX;
  123. for (uint bx = x; bx < min(x + mBlockSize + 1, mSampleCount); ++bx)
  124. for (uint by = y; by < min(y + mBlockSize + 1, mSampleCount); ++by)
  125. {
  126. float h = mHeightSamples[by * mSampleCount + bx];
  127. if (h != cNoCollisionValue)
  128. {
  129. block_min_value = min(block_min_value, h);
  130. block_max_value = max(block_max_value, h);
  131. }
  132. }
  133. if (block_min_value < block_max_value)
  134. {
  135. // Quantize then dequantize block min/max value
  136. block_min_value = min_value + floor((block_min_value - min_value) * scale) / scale;
  137. block_max_value = min_value + ceil((block_max_value - min_value) * scale) / scale;
  138. float block_height = block_max_value - block_min_value;
  139. // Loop over the block again
  140. for (uint bx = x; bx < x + mBlockSize; ++bx)
  141. for (uint by = y; by < y + mBlockSize; ++by)
  142. {
  143. // Get the height
  144. float height = mHeightSamples[by * mSampleCount + bx];
  145. if (height != cNoCollisionValue)
  146. {
  147. for (;;)
  148. {
  149. // Determine bitmask for sample
  150. uint32 sample_mask = (1 << bits_per_sample) - 1;
  151. // Quantize
  152. float quantized_height = floor((height - block_min_value) * float(sample_mask) / block_height);
  153. quantized_height = Clamp(quantized_height, 0.0f, float(sample_mask - 1));
  154. // Dequantize and check error
  155. float dequantized_height = block_min_value + (quantized_height + 0.5f) * block_height / float(sample_mask);
  156. if (abs(dequantized_height - height) <= inMaxError)
  157. break;
  158. // Not accurate enough, increase bits per sample
  159. bits_per_sample++;
  160. // Don't go above 8 bits per sample
  161. if (bits_per_sample == 8)
  162. return bits_per_sample;
  163. }
  164. }
  165. }
  166. }
  167. }
  168. }
  169. return bits_per_sample;
  170. }
  171. void HeightFieldShape::CalculateActiveEdges()
  172. {
  173. // Store active edges. The triangles are organized like this:
  174. // + +
  175. // | \ T1B | \ T2B
  176. // e0 e2 | \
  177. // | T1A \ | T2A \
  178. // +--e1---+-------+
  179. // | \ T3B | \ T4B
  180. // | \ | \
  181. // | T3A \ | T4A \
  182. // +-------+-------+
  183. // We store active edges e0 .. e2 as bits 0 .. 2.
  184. // We store triangles horizontally then vertically (order T1A, T2A, T3A and T4A).
  185. // The top edge and right edge of the heightfield are always active so we do not need to store them,
  186. // therefore we only need to store (mSampleCount - 1)^2 * 3-bit
  187. // The triangles T1B, T2B, T3B and T4B do not need to be stored, their active edges can be constructed from adjacent triangles.
  188. // Add 1 byte padding so we can always read 1 uint16 to get the bits that cross an 8 bit boundary
  189. uint count_min_1 = mSampleCount - 1;
  190. uint count_min_1_sq = Square(count_min_1);
  191. mActiveEdges.resize((count_min_1_sq * 3 + 7) / 8 + 1);
  192. memset(&mActiveEdges[0], 0, mActiveEdges.size());
  193. // Calculate triangle normals and make normals zero for triangles that are missing
  194. Array<Vec3> normals;
  195. normals.resize(2 * count_min_1_sq);
  196. memset(&normals[0], 0, normals.size() * sizeof(Vec3));
  197. for (uint y = 0; y < count_min_1; ++y)
  198. for (uint x = 0; x < count_min_1; ++x)
  199. if (!IsNoCollision(x, y) && !IsNoCollision(x + 1, y + 1))
  200. {
  201. Vec3 x1y1 = GetPosition(x, y);
  202. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  203. uint offset = 2 * (count_min_1 * y + x);
  204. if (!IsNoCollision(x, y + 1))
  205. {
  206. Vec3 x1y2 = GetPosition(x, y + 1);
  207. normals[offset] = (x2y2 - x1y2).Cross(x1y1 - x1y2).Normalized();
  208. }
  209. if (!IsNoCollision(x + 1, y))
  210. {
  211. Vec3 x2y1 = GetPosition(x + 1, y);
  212. normals[offset + 1] = (x1y1 - x2y1).Cross(x2y2 - x2y1).Normalized();
  213. }
  214. }
  215. // Calculate active edges
  216. for (uint y = 0; y < count_min_1; ++y)
  217. for (uint x = 0; x < count_min_1; ++x)
  218. {
  219. // Calculate vertex positions.
  220. // We don't check 'no colliding' since those normals will be zero and sIsEdgeActive will return true
  221. Vec3 x1y1 = GetPosition(x, y);
  222. Vec3 x1y2 = GetPosition(x, y + 1);
  223. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  224. // Calculate the edge flags (3 bits)
  225. uint offset = 2 * (count_min_1 * y + x);
  226. bool edge0_active = x == 0 || ActiveEdges::IsEdgeActive(normals[offset], normals[offset - 1], x1y2 - x1y1);
  227. bool edge1_active = y == count_min_1 - 1 || ActiveEdges::IsEdgeActive(normals[offset], normals[offset + 2 * count_min_1 + 1], x2y2 - x1y2);
  228. bool edge2_active = ActiveEdges::IsEdgeActive(normals[offset], normals[offset + 1], x1y1 - x2y2);
  229. uint16 edge_flags = (edge0_active? 0b001 : 0) | (edge1_active? 0b010 : 0) | (edge2_active? 0b100 : 0);
  230. // Store the edge flags in the array
  231. uint bit_pos = 3 * (y * count_min_1 + x);
  232. uint byte_pos = bit_pos >> 3;
  233. bit_pos &= 0b111;
  234. edge_flags <<= bit_pos;
  235. mActiveEdges[byte_pos] |= uint8(edge_flags);
  236. mActiveEdges[byte_pos + 1] |= uint8(edge_flags >> 8);
  237. }
  238. }
  239. void HeightFieldShape::StoreMaterialIndices(const Array<uint8> &inMaterialIndices)
  240. {
  241. uint count_min_1 = mSampleCount - 1;
  242. mNumBitsPerMaterialIndex = 32 - CountLeadingZeros((uint32)mMaterials.size() - 1);
  243. mMaterialIndices.resize(((Square(count_min_1) * mNumBitsPerMaterialIndex + 7) >> 3) + 1); // Add 1 byte so we don't read out of bounds when reading an uint16
  244. for (uint y = 0; y < count_min_1; ++y)
  245. for (uint x = 0; x < count_min_1; ++x)
  246. {
  247. // Read material
  248. uint sample_pos = x + y * count_min_1;
  249. uint16 material_index = uint16(inMaterialIndices[sample_pos]);
  250. // Calculate byte and bit position where the material index needs to go
  251. uint bit_pos = sample_pos * mNumBitsPerMaterialIndex;
  252. uint byte_pos = bit_pos >> 3;
  253. bit_pos &= 0b111;
  254. // Write the material index
  255. material_index <<= bit_pos;
  256. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  257. mMaterialIndices[byte_pos] |= uint8(material_index);
  258. mMaterialIndices[byte_pos + 1] |= uint8(material_index >> 8);
  259. }
  260. }
  261. void HeightFieldShape::CacheValues()
  262. {
  263. mSampleMask = uint8((uint32(1) << mBitsPerSample) - 1);
  264. }
  265. HeightFieldShape::HeightFieldShape(const HeightFieldShapeSettings &inSettings, ShapeResult &outResult) :
  266. Shape(EShapeType::HeightField, EShapeSubType::HeightField, inSettings, outResult),
  267. mOffset(inSettings.mOffset),
  268. mScale(inSettings.mScale),
  269. mSampleCount(inSettings.mSampleCount),
  270. mBlockSize(inSettings.mBlockSize),
  271. mBitsPerSample(uint8(inSettings.mBitsPerSample)),
  272. mMaterials(inSettings.mMaterials)
  273. {
  274. CacheValues();
  275. // Check block size
  276. if (mBlockSize < 2 || mBlockSize > 8)
  277. {
  278. outResult.SetError("HeightFieldShape: Block size must be in the range [2, 8]!");
  279. return;
  280. }
  281. // Check sample count
  282. if (mSampleCount % mBlockSize != 0)
  283. {
  284. outResult.SetError("HeightFieldShape: Sample count must be a multiple of block size!");
  285. return;
  286. }
  287. // Check bits per sample
  288. if (inSettings.mBitsPerSample < 1 || inSettings.mBitsPerSample > 8)
  289. {
  290. outResult.SetError("HeightFieldShape: Bits per sample must be in the range [1, 8]!");
  291. return;
  292. }
  293. // We stop at mBlockSize x mBlockSize height sample blocks
  294. uint n = GetNumBlocks();
  295. // Required to be power of two to allow creating a hierarchical grid
  296. if (!IsPowerOf2(n))
  297. {
  298. outResult.SetError("HeightFieldShape: Sample count / block size must be power of 2!");
  299. return;
  300. }
  301. // We want at least 1 grid layer
  302. if (n < 2)
  303. {
  304. outResult.SetError("HeightFieldShape: Sample count too low!");
  305. return;
  306. }
  307. // Check that we don't overflow our 32 bit 'properties'
  308. if (n > (1 << cNumBitsXY))
  309. {
  310. outResult.SetError("HeightFieldShape: Sample count too high!");
  311. return;
  312. }
  313. // Check if we're not exceeding the amount of sub shape id bits
  314. if (GetSubShapeIDBitsRecursive() > SubShapeID::MaxBits)
  315. {
  316. outResult.SetError("HeightFieldShape: Size exceeds the amount of available sub shape ID bits!");
  317. return;
  318. }
  319. if (!mMaterials.empty())
  320. {
  321. // Validate materials
  322. if (mMaterials.size() > 256)
  323. {
  324. outResult.SetError("Supporting max 256 materials per height field");
  325. return;
  326. }
  327. for (uint8 s : inSettings.mMaterialIndices)
  328. if (s >= mMaterials.size())
  329. {
  330. outResult.SetError(StringFormat("Material %u is beyond material list (size: %u)", s, (uint)mMaterials.size()));
  331. return;
  332. }
  333. }
  334. else
  335. {
  336. // No materials assigned, validate that no materials have been specified
  337. if (!inSettings.mMaterialIndices.empty())
  338. {
  339. outResult.SetError("No materials present, mMaterialIndices should be empty");
  340. return;
  341. }
  342. }
  343. // Determine range
  344. float min_value, max_value, scale;
  345. inSettings.DetermineMinAndMaxSample(min_value, max_value, scale);
  346. if (min_value > max_value)
  347. {
  348. // If there is no collision with this heightmap, leave everything empty
  349. mMaterials.clear();
  350. outResult.Set(this);
  351. return;
  352. }
  353. // Quantize to uint16
  354. Array<uint16> quantized_samples;
  355. quantized_samples.reserve(mSampleCount * mSampleCount);
  356. for (float h : inSettings.mHeightSamples)
  357. if (h == cNoCollisionValue)
  358. {
  359. quantized_samples.push_back(cNoCollisionValue16);
  360. }
  361. else
  362. {
  363. // Floor the quantized height to get a lower bound for the quantized value
  364. int quantized_height = (int)floor(scale * (h - min_value));
  365. // Ensure that the height says below the max height value so we can safely add 1 to get the upper bound for the quantized value
  366. quantized_height = Clamp(quantized_height, 0, int(cMaxHeightValue16 - 1));
  367. quantized_samples.push_back(uint16(quantized_height));
  368. }
  369. // Update offset and scale to account for the compression to uint16
  370. if (min_value <= max_value) // Only when there was collision
  371. {
  372. // In GetPosition we always add 0.5 to the quantized sample in order to reduce the average error.
  373. // We want to be able to exactly quantize min_value (this is important in case the heightfield is entirely flat) so we subtract that value from min_value.
  374. min_value -= 0.5f / (scale * mSampleMask);
  375. mOffset.SetY(mOffset.GetY() + mScale.GetY() * min_value);
  376. }
  377. mScale.SetY(mScale.GetY() / scale);
  378. // Calculate amount of grids
  379. uint max_level = sGetMaxLevel(n);
  380. // Temporary data structure used during creating of a hierarchy of grids
  381. struct Range
  382. {
  383. uint16 mMin;
  384. uint16 mMax;
  385. };
  386. // Reserve size for temporary range data + reserve 1 extra for a 1x1 grid that we won't store but use for calculating the bounding box
  387. Array<Array<Range>> ranges;
  388. ranges.resize(max_level + 1);
  389. // Calculate highest detail grid by combining mBlockSize x mBlockSize height samples
  390. Array<Range> *cur_range_vector = &ranges.back();
  391. cur_range_vector->resize(n * n);
  392. Range *range_dst = &cur_range_vector->front();
  393. for (uint y = 0; y < n; ++y)
  394. for (uint x = 0; x < n; ++x)
  395. {
  396. range_dst->mMin = 0xffff;
  397. range_dst->mMax = 0;
  398. uint max_bx = x == n - 1? mBlockSize : mBlockSize + 1; // for interior blocks take 1 more because the triangles connect to the next block so we must include their height too
  399. uint max_by = y == n - 1? mBlockSize : mBlockSize + 1;
  400. for (uint by = 0; by < max_by; ++by)
  401. for (uint bx = 0; bx < max_bx; ++bx)
  402. {
  403. uint16 h = quantized_samples[(y * mBlockSize + by) * mSampleCount + (x * mBlockSize + bx)];
  404. if (h != cNoCollisionValue16)
  405. {
  406. range_dst->mMin = min(range_dst->mMin, h);
  407. range_dst->mMax = max(range_dst->mMax, uint16(h + 1)); // Add 1 to the max so we know the real value is between mMin and mMax
  408. }
  409. }
  410. ++range_dst;
  411. }
  412. // Calculate remaining grids
  413. while (n > 1)
  414. {
  415. // Get source buffer
  416. const Range *range_src = &cur_range_vector->front();
  417. // Previous array element
  418. --cur_range_vector;
  419. // Make space for this grid
  420. n >>= 1;
  421. cur_range_vector->resize(n * n);
  422. // Get target buffer
  423. range_dst = &cur_range_vector->front();
  424. // Combine the results of 2x2 ranges
  425. for (uint y = 0; y < n; ++y)
  426. for (uint x = 0; x < n; ++x)
  427. {
  428. range_dst->mMin = 0xffff;
  429. range_dst->mMax = 0;
  430. for (uint by = 0; by < 2; ++by)
  431. for (uint bx = 0; bx < 2; ++bx)
  432. {
  433. const Range &r = range_src[(y * 2 + by) * n * 2 + x * 2 + bx];
  434. range_dst->mMin = min(range_dst->mMin, r.mMin);
  435. range_dst->mMax = max(range_dst->mMax, r.mMax);
  436. }
  437. ++range_dst;
  438. }
  439. }
  440. JPH_ASSERT(cur_range_vector == &ranges.front());
  441. // Store global range for bounding box calculation
  442. mMinSample = ranges[0][0].mMin;
  443. mMaxSample = ranges[0][0].mMax;
  444. #ifdef JPH_ENABLE_ASSERTS
  445. // Validate that we did not lose range along the way
  446. uint16 minv = 0xffff, maxv = 0;
  447. for (uint16 v : quantized_samples)
  448. if (v != cNoCollisionValue16)
  449. {
  450. minv = min(minv, v);
  451. maxv = max(maxv, uint16(v + 1));
  452. }
  453. JPH_ASSERT(mMinSample == minv && mMaxSample == maxv);
  454. #endif
  455. // Now erase the first element, we need a 2x2 grid to start with
  456. ranges.erase(ranges.begin());
  457. // Create blocks
  458. mRangeBlocks.reserve(sGridOffsets[ranges.size()]);
  459. for (uint level = 0; level < ranges.size(); ++level)
  460. {
  461. JPH_ASSERT(mRangeBlocks.size() == sGridOffsets[level]);
  462. n = 1 << level;
  463. for (uint y = 0; y < n; ++y)
  464. for (uint x = 0; x < n; ++x)
  465. {
  466. // Convert from 2x2 Range structure to 1 RangeBlock structure
  467. RangeBlock rb;
  468. for (uint by = 0; by < 2; ++by)
  469. for (uint bx = 0; bx < 2; ++bx)
  470. {
  471. uint src_pos = (y * 2 + by) * n * 2 + (x * 2 + bx);
  472. uint dst_pos = by * 2 + bx;
  473. rb.mMin[dst_pos] = ranges[level][src_pos].mMin;
  474. rb.mMax[dst_pos] = ranges[level][src_pos].mMax;
  475. }
  476. // Add this block
  477. mRangeBlocks.push_back(rb);
  478. }
  479. }
  480. JPH_ASSERT(mRangeBlocks.size() == sGridOffsets[ranges.size()]);
  481. // Quantize height samples
  482. mHeightSamples.resize((mSampleCount * mSampleCount * inSettings.mBitsPerSample + 7) / 8 + 1);
  483. int sample = 0;
  484. for (uint y = 0; y < mSampleCount; ++y)
  485. for (uint x = 0; x < mSampleCount; ++x)
  486. {
  487. uint32 output_value;
  488. float h = inSettings.mHeightSamples[y * mSampleCount + x];
  489. if (h == cNoCollisionValue)
  490. {
  491. // No collision
  492. output_value = mSampleMask;
  493. }
  494. else
  495. {
  496. // Get range of block so we know what range to compress to
  497. uint bx = x / mBlockSize;
  498. uint by = y / mBlockSize;
  499. const Range &range = ranges.back()[by * (mSampleCount / mBlockSize) + bx];
  500. JPH_ASSERT(range.mMin < range.mMax);
  501. // Quantize to mBitsPerSample bits, note that mSampleMask is reserved for indicating that there's no collision.
  502. // We divide the range into mSampleMask segments and use the mid points of these segments as the quantized values.
  503. // This results in a lower error than if we had quantized our data using the lowest point of all these segments.
  504. float h_min = min_value + range.mMin / scale;
  505. float h_delta = float(range.mMax - range.mMin) / scale;
  506. float quantized_height = floor((h - h_min) * float(mSampleMask) / h_delta);
  507. output_value = uint32(Clamp((int)quantized_height, 0, int(mSampleMask) - 1)); // mSampleMask is reserved as 'no collision value'
  508. }
  509. // Store the sample
  510. uint byte_pos = sample >> 3;
  511. uint bit_pos = sample & 0b111;
  512. output_value <<= bit_pos;
  513. mHeightSamples[byte_pos] |= uint8(output_value);
  514. mHeightSamples[byte_pos + 1] |= uint8(output_value >> 8);
  515. sample += inSettings.mBitsPerSample;
  516. }
  517. // Calculate the active edges
  518. CalculateActiveEdges();
  519. // Compress material indices
  520. if (mMaterials.size() > 1)
  521. StoreMaterialIndices(inSettings.mMaterialIndices);
  522. outResult.Set(this);
  523. }
  524. inline void HeightFieldShape::sGetRangeBlockOffsetAndStride(uint inNumBlocks, uint inMaxLevel, uint &outRangeBlockOffset, uint &outRangeBlockStride)
  525. {
  526. outRangeBlockOffset = sGridOffsets[inMaxLevel - 1];
  527. outRangeBlockStride = inNumBlocks >> 1;
  528. }
  529. inline void HeightFieldShape::GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const
  530. {
  531. JPH_ASSERT(inBlockX < GetNumBlocks() && inBlockY < GetNumBlocks());
  532. // Convert to location of range block
  533. uint rbx = inBlockX >> 1;
  534. uint rby = inBlockY >> 1;
  535. uint n = ((inBlockY & 1) << 1) + (inBlockX & 1);
  536. // Calculate offset and scale
  537. const RangeBlock &block = mRangeBlocks[inRangeBlockOffset + rby * inRangeBlockStride + rbx];
  538. outBlockOffset = float(block.mMin[n]);
  539. outBlockScale = float(block.mMax[n] - block.mMin[n]) / float(mSampleMask);
  540. }
  541. inline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const
  542. {
  543. JPH_ASSERT(inX < mSampleCount);
  544. JPH_ASSERT(inY < mSampleCount);
  545. // Determine bit position of sample
  546. uint sample = (inY * mSampleCount + inX) * uint(mBitsPerSample);
  547. uint byte_pos = sample >> 3;
  548. uint bit_pos = sample & 0b111;
  549. // Fetch the height sample value
  550. JPH_ASSERT(byte_pos + 1 < mHeightSamples.size());
  551. const uint8 *height_samples = mHeightSamples.data() + byte_pos;
  552. uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);
  553. return uint8(height_sample >> bit_pos) & mSampleMask;
  554. }
  555. inline Vec3 HeightFieldShape::GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const
  556. {
  557. // Get quantized value
  558. uint8 height_sample = GetHeightSample(inX, inY);
  559. outNoCollision = height_sample == mSampleMask;
  560. // Add 0.5 to the quantized value to minimize the error (see constructor)
  561. return mOffset + mScale * Vec3(float(inX), inBlockOffset + (0.5f + height_sample) * inBlockScale, float(inY));
  562. }
  563. Vec3 HeightFieldShape::GetPosition(uint inX, uint inY) const
  564. {
  565. // Test if there are any samples
  566. if (mHeightSamples.empty())
  567. return mOffset + mScale * Vec3(float(inX), 0.0f, float(inY));
  568. // Get block location
  569. uint bx = inX / mBlockSize;
  570. uint by = inY / mBlockSize;
  571. // Calculate offset and stride
  572. uint num_blocks = GetNumBlocks();
  573. uint range_block_offset, range_block_stride;
  574. sGetRangeBlockOffsetAndStride(num_blocks, sGetMaxLevel(num_blocks), range_block_offset, range_block_stride);
  575. float offset, scale;
  576. GetBlockOffsetAndScale(bx, by, range_block_offset, range_block_stride, offset, scale);
  577. bool no_collision;
  578. return GetPosition(inX, inY, offset, scale, no_collision);
  579. }
  580. bool HeightFieldShape::IsNoCollision(uint inX, uint inY) const
  581. {
  582. return mHeightSamples.empty() || GetHeightSample(inX, inY) == mSampleMask;
  583. }
  584. bool HeightFieldShape::ProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const
  585. {
  586. // Check if we have collision
  587. if (mHeightSamples.empty())
  588. return false;
  589. // Convert coordinate to integer space
  590. Vec3 integer_space = (inLocalPosition - mOffset) / mScale;
  591. // Get x coordinate and fraction
  592. float x_frac = integer_space.GetX();
  593. if (x_frac < 0.0f || x_frac >= mSampleCount - 1)
  594. return false;
  595. uint x = (uint)floor(x_frac);
  596. x_frac -= x;
  597. // Get y coordinate and fraction
  598. float y_frac = integer_space.GetZ();
  599. if (y_frac < 0.0f || y_frac >= mSampleCount - 1)
  600. return false;
  601. uint y = (uint)floor(y_frac);
  602. y_frac -= y;
  603. // If one of the diagonal points doesn't have collision, we don't have a height at this location
  604. if (IsNoCollision(x, y) || IsNoCollision(x + 1, y + 1))
  605. return false;
  606. if (y_frac >= x_frac)
  607. {
  608. // Left bottom triangle, test the 3rd point
  609. if (IsNoCollision(x, y + 1))
  610. return false;
  611. // Interpolate height value
  612. Vec3 v1 = GetPosition(x, y);
  613. Vec3 v2 = GetPosition(x, y + 1);
  614. Vec3 v3 = GetPosition(x + 1, y + 1);
  615. outSurfacePosition = v1 + y_frac * (v2 - v1) + x_frac * (v3 - v2);
  616. SubShapeIDCreator creator;
  617. outSubShapeID = EncodeSubShapeID(creator, x, y, 0);
  618. return true;
  619. }
  620. else
  621. {
  622. // Right top triangle, test the third point
  623. if (IsNoCollision(x + 1, y))
  624. return false;
  625. // Interpolate height value
  626. Vec3 v1 = GetPosition(x, y);
  627. Vec3 v2 = GetPosition(x + 1, y + 1);
  628. Vec3 v3 = GetPosition(x + 1, y);
  629. outSurfacePosition = v1 + y_frac * (v2 - v3) + x_frac * (v3 - v1);
  630. SubShapeIDCreator creator;
  631. outSubShapeID = EncodeSubShapeID(creator, x, y, 1);
  632. return true;
  633. }
  634. }
  635. MassProperties HeightFieldShape::GetMassProperties() const
  636. {
  637. // Object should always be static, return default mass properties
  638. return MassProperties();
  639. }
  640. const PhysicsMaterial *HeightFieldShape::GetMaterial(uint inX, uint inY) const
  641. {
  642. if (mMaterials.empty())
  643. return PhysicsMaterial::sDefault;
  644. if (mMaterials.size() == 1)
  645. return mMaterials[0];
  646. uint count_min_1 = mSampleCount - 1;
  647. JPH_ASSERT(inX < count_min_1);
  648. JPH_ASSERT(inY < count_min_1);
  649. // Calculate at which bit the material index starts
  650. uint bit_pos = (inX + inY * count_min_1) * mNumBitsPerMaterialIndex;
  651. uint byte_pos = bit_pos >> 3;
  652. bit_pos &= 0b111;
  653. // Read the material index
  654. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  655. const uint8 *material_indices = mMaterialIndices.data() + byte_pos;
  656. uint16 material_index = uint16(material_indices[0]) + uint16(uint16(material_indices[1]) << 8);
  657. material_index >>= bit_pos;
  658. material_index &= (1 << mNumBitsPerMaterialIndex) - 1;
  659. // Return the material
  660. return mMaterials[material_index];
  661. }
  662. uint HeightFieldShape::GetSubShapeIDBits() const
  663. {
  664. // Need to store X, Y and 1 extra bit to specify the triangle number in the quad
  665. return 2 * (32 - CountLeadingZeros(mSampleCount - 1)) + 1;
  666. }
  667. SubShapeID HeightFieldShape::EncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const
  668. {
  669. return inCreator.PushID((inX + inY * mSampleCount) * 2 + inTriangle, GetSubShapeIDBits()).GetID();
  670. }
  671. void HeightFieldShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const
  672. {
  673. // Decode sub shape id
  674. SubShapeID remainder;
  675. uint32 id = inSubShapeID.PopID(GetSubShapeIDBits(), remainder);
  676. JPH_ASSERT(remainder.IsEmpty(), "Invalid subshape ID");
  677. // Get triangle index
  678. outTriangle = id & 1;
  679. id >>= 1;
  680. // Fetch the x and y coordinate
  681. outX = id % mSampleCount;
  682. outY = id / mSampleCount;
  683. }
  684. const PhysicsMaterial *HeightFieldShape::GetMaterial(const SubShapeID &inSubShapeID) const
  685. {
  686. // Decode ID
  687. uint x, y, triangle;
  688. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  689. // Fetch the material
  690. return GetMaterial(x, y);
  691. }
  692. Vec3 HeightFieldShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  693. {
  694. // Decode ID
  695. uint x, y, triangle;
  696. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  697. // Fetch vertices that both triangles share
  698. Vec3 x1y1 = GetPosition(x, y);
  699. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  700. // Get normal depending on which triangle was selected
  701. Vec3 normal;
  702. if (triangle == 0)
  703. {
  704. Vec3 x1y2 = GetPosition(x, y + 1);
  705. normal = (x2y2 - x1y2).Cross(x1y1 - x1y2);
  706. }
  707. else
  708. {
  709. Vec3 x2y1 = GetPosition(x + 1, y);
  710. normal = (x1y1 - x2y1).Cross(x2y2 - x2y1);
  711. }
  712. return normal.Normalized();
  713. }
  714. void HeightFieldShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  715. {
  716. // Decode ID
  717. uint x, y, triangle;
  718. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  719. // Fetch the triangle
  720. outVertices.resize(3);
  721. outVertices[0] = GetPosition(x, y);
  722. Vec3 v2 = GetPosition(x + 1, y + 1);
  723. if (triangle == 0)
  724. {
  725. outVertices[1] = GetPosition(x, y + 1);
  726. outVertices[2] = v2;
  727. }
  728. else
  729. {
  730. outVertices[1] = v2;
  731. outVertices[2] = GetPosition(x + 1, y);
  732. }
  733. // Flip triangle if scaled inside out
  734. if (ScaleHelpers::IsInsideOut(inScale))
  735. swap(outVertices[1], outVertices[2]);
  736. // Transform to world space
  737. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  738. for (Vec3 &v : outVertices)
  739. v = transform * v;
  740. }
  741. inline uint8 HeightFieldShape::GetEdgeFlags(uint inX, uint inY, uint inTriangle) const
  742. {
  743. if (inTriangle == 0)
  744. {
  745. // The edge flags for this triangle are directly stored, find the right 3 bits
  746. uint bit_pos = 3 * (inX + inY * (mSampleCount - 1));
  747. uint byte_pos = bit_pos >> 3;
  748. bit_pos &= 0b111;
  749. JPH_ASSERT(byte_pos + 1 < mActiveEdges.size());
  750. const uint8 *active_edges = mActiveEdges.data() + byte_pos;
  751. uint16 edge_flags = uint16(active_edges[0]) + uint16(uint16(active_edges[1]) << 8);
  752. return uint8(edge_flags >> bit_pos) & 0b111;
  753. }
  754. else
  755. {
  756. // We don't store this triangle directly, we need to look at our three neighbours to construct the edge flags
  757. uint8 edge0 = (GetEdgeFlags(inX, inY, 0) & 0b100) != 0? 0b001 : 0; // Diagonal edge
  758. uint8 edge1 = inX == mSampleCount - 1 || (GetEdgeFlags(inX + 1, inY, 0) & 0b001) != 0? 0b010 : 0; // Vertical edge
  759. uint8 edge2 = inY == 0 || (GetEdgeFlags(inX, inY - 1, 0) & 0b010) != 0? 0b100 : 0; // Horizontal edge
  760. return edge0 | edge1 | edge2;
  761. }
  762. }
  763. AABox HeightFieldShape::GetLocalBounds() const
  764. {
  765. if (mMinSample == cNoCollisionValue16)
  766. {
  767. // This whole height field shape doesn't have any collision, return the center point
  768. Vec3 center = mOffset + 0.5f * mScale * Vec3(float(mSampleCount - 1), 0.0f, float(mSampleCount - 1));
  769. return AABox(center, center);
  770. }
  771. else
  772. {
  773. // Bounding box based on min and max sample height
  774. Vec3 bmin = mOffset + mScale * Vec3(0.0f, float(mMinSample), 0.0f);
  775. Vec3 bmax = mOffset + mScale * Vec3(float(mSampleCount - 1), float(mMaxSample), float(mSampleCount - 1));
  776. return AABox(bmin, bmax);
  777. }
  778. }
  779. #ifdef JPH_DEBUG_RENDERER
  780. void HeightFieldShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  781. {
  782. // Don't draw anything if we don't have any collision
  783. if (mHeightSamples.empty())
  784. return;
  785. // Reset the batch if we switch coloring mode
  786. if (mCachedUseMaterialColors != inUseMaterialColors)
  787. {
  788. mGeometry.clear();
  789. mCachedUseMaterialColors = inUseMaterialColors;
  790. }
  791. if (mGeometry.empty())
  792. {
  793. // Divide terrain in triangle batches of max 64x64x2 triangles to allow better culling of the terrain
  794. uint32 block_size = min<uint32>(mSampleCount, 64);
  795. for (uint32 by = 0; by < mSampleCount; by += block_size)
  796. for (uint32 bx = 0; bx < mSampleCount; bx += block_size)
  797. {
  798. // Create vertices for a block
  799. Array<DebugRenderer::Triangle> triangles;
  800. triangles.resize(block_size * block_size * 2);
  801. DebugRenderer::Triangle *out_tri = &triangles[0];
  802. for (uint32 y = by, max_y = min(by + block_size, mSampleCount - 1); y < max_y; ++y)
  803. for (uint32 x = bx, max_x = min(bx + block_size, mSampleCount - 1); x < max_x; ++x)
  804. if (!IsNoCollision(x, y) && !IsNoCollision(x + 1, y + 1))
  805. {
  806. Vec3 x1y1 = GetPosition(x, y);
  807. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  808. Color color = inUseMaterialColors? GetMaterial(x, y)->GetDebugColor() : Color::sWhite;
  809. if (!IsNoCollision(x, y + 1))
  810. {
  811. Vec3 x1y2 = GetPosition(x, y + 1);
  812. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  813. x1y2.StoreFloat3(&out_tri->mV[1].mPosition);
  814. x2y2.StoreFloat3(&out_tri->mV[2].mPosition);
  815. Vec3 normal = (x2y2 - x1y2).Cross(x1y1 - x1y2).Normalized();
  816. for (DebugRenderer::Vertex &v : out_tri->mV)
  817. {
  818. v.mColor = color;
  819. v.mUV = Float2(0, 0);
  820. normal.StoreFloat3(&v.mNormal);
  821. }
  822. ++out_tri;
  823. }
  824. if (!IsNoCollision(x + 1, y))
  825. {
  826. Vec3 x2y1 = GetPosition(x + 1, y);
  827. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  828. x2y2.StoreFloat3(&out_tri->mV[1].mPosition);
  829. x2y1.StoreFloat3(&out_tri->mV[2].mPosition);
  830. Vec3 normal = (x1y1 - x2y1).Cross(x2y2 - x2y1).Normalized();
  831. for (DebugRenderer::Vertex &v : out_tri->mV)
  832. {
  833. v.mColor = color;
  834. v.mUV = Float2(0, 0);
  835. normal.StoreFloat3(&v.mNormal);
  836. }
  837. ++out_tri;
  838. }
  839. }
  840. // Resize triangles array to actual amount of triangles written
  841. size_t num_triangles = out_tri - &triangles[0];
  842. triangles.resize(num_triangles);
  843. // Create batch
  844. if (num_triangles > 0)
  845. mGeometry.push_back(new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), DebugRenderer::sCalculateBounds(&triangles[0].mV[0], int(3 * num_triangles))));
  846. }
  847. }
  848. // Get transform including scale
  849. RMat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  850. // Test if the shape is scaled inside out
  851. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  852. // Determine the draw mode
  853. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  854. // Draw the geometry
  855. for (const DebugRenderer::GeometryRef &b : mGeometry)
  856. inRenderer->DrawGeometry(transform, inColor, b, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  857. if (sDrawTriangleOutlines)
  858. {
  859. struct Visitor
  860. {
  861. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, DebugRenderer *inRenderer, RMat44Arg inTransform) :
  862. mShape(inShape),
  863. mRenderer(inRenderer),
  864. mTransform(inTransform)
  865. {
  866. }
  867. JPH_INLINE bool ShouldAbort() const
  868. {
  869. return false;
  870. }
  871. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  872. {
  873. return true;
  874. }
  875. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  876. {
  877. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  878. return CountAndSortTrues(valid, ioProperties);
  879. }
  880. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  881. {
  882. // Determine active edges
  883. uint8 active_edges = mShape->GetEdgeFlags(inX, inY, inTriangle);
  884. // Loop through edges
  885. Vec3 v[] = { inV0, inV1, inV2 };
  886. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  887. {
  888. RVec3 v1 = mTransform * v[edge_idx];
  889. RVec3 v2 = mTransform * v[(edge_idx + 1) % 3];
  890. // Draw active edge as a green arrow, other edges as grey
  891. if (active_edges & (1 << edge_idx))
  892. mRenderer->DrawArrow(v1, v2, Color::sGreen, 0.01f);
  893. else
  894. mRenderer->DrawLine(v1, v2, Color::sGrey);
  895. }
  896. }
  897. const HeightFieldShape *mShape;
  898. DebugRenderer * mRenderer;
  899. RMat44 mTransform;
  900. };
  901. Visitor visitor(this, inRenderer, inCenterOfMassTransform.PreScaled(inScale));
  902. WalkHeightField(visitor);
  903. }
  904. }
  905. #endif // JPH_DEBUG_RENDERER
  906. class HeightFieldShape::DecodingContext
  907. {
  908. public:
  909. JPH_INLINE explicit DecodingContext(const HeightFieldShape *inShape) :
  910. mShape(inShape)
  911. {
  912. static_assert(sizeof(sGridOffsets) / sizeof(uint) == cNumBitsXY + 1, "Offsets array is not long enough");
  913. // Construct root stack entry
  914. mPropertiesStack[0] = 0; // level: 0, x: 0, y: 0
  915. }
  916. template <class Visitor>
  917. JPH_INLINE void WalkHeightField(Visitor &ioVisitor)
  918. {
  919. // Early out if there's no collision
  920. if (mShape->mHeightSamples.empty())
  921. return;
  922. // Precalculate values relating to sample count
  923. uint32 sample_count = mShape->mSampleCount;
  924. UVec4 sample_count_min_1 = UVec4::sReplicate(sample_count - 1);
  925. // Precalculate values relating to block size
  926. uint32 block_size = mShape->mBlockSize;
  927. uint32 block_size_plus_1 = block_size + 1;
  928. uint num_blocks = mShape->GetNumBlocks();
  929. uint num_blocks_min_1 = num_blocks - 1;
  930. uint max_level = HeightFieldShape::sGetMaxLevel(num_blocks);
  931. // Precalculate range block offset and stride for GetBlockOffsetAndScale
  932. uint range_block_offset, range_block_stride;
  933. sGetRangeBlockOffsetAndStride(num_blocks, max_level, range_block_offset, range_block_stride);
  934. // Allocate space for vertices and 'no collision' flags
  935. int array_size = Square(block_size_plus_1);
  936. Vec3 *vertices = reinterpret_cast<Vec3 *>(JPH_STACK_ALLOC(array_size * sizeof(Vec3)));
  937. bool *no_collision = reinterpret_cast<bool *>(JPH_STACK_ALLOC(array_size * sizeof(bool)));
  938. // Splat offsets
  939. Vec4 ox = mShape->mOffset.SplatX();
  940. Vec4 oy = mShape->mOffset.SplatY();
  941. Vec4 oz = mShape->mOffset.SplatZ();
  942. // Splat scales
  943. Vec4 sx = mShape->mScale.SplatX();
  944. Vec4 sy = mShape->mScale.SplatY();
  945. Vec4 sz = mShape->mScale.SplatZ();
  946. do
  947. {
  948. // Decode properties
  949. uint32 properties_top = mPropertiesStack[mTop];
  950. uint32 x = properties_top & cMaskBitsXY;
  951. uint32 y = (properties_top >> cNumBitsXY) & cMaskBitsXY;
  952. uint32 level = properties_top >> cLevelShift;
  953. if (level >= max_level)
  954. {
  955. // Determine actual range of samples (minus one because we eventually want to iterate over the triangles, not the samples)
  956. uint32 min_x = x * block_size;
  957. uint32 max_x = min_x + block_size;
  958. uint32 min_y = y * block_size;
  959. uint32 max_y = min_y + block_size;
  960. // Decompress vertices of block at (x, y)
  961. Vec3 *dst_vertex = vertices;
  962. bool *dst_no_collision = no_collision;
  963. float block_offset, block_scale;
  964. mShape->GetBlockOffsetAndScale(x, y, range_block_offset, range_block_stride, block_offset, block_scale);
  965. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  966. {
  967. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  968. {
  969. *dst_vertex = mShape->GetPosition(v_x, v_y, block_offset, block_scale, *dst_no_collision);
  970. ++dst_vertex;
  971. ++dst_no_collision;
  972. }
  973. // Skip last column, these values come from a different block
  974. ++dst_vertex;
  975. ++dst_no_collision;
  976. }
  977. // Decompress block (x + 1, y)
  978. uint32 max_x_decrement = 0;
  979. if (x < num_blocks_min_1)
  980. {
  981. dst_vertex = vertices + block_size;
  982. dst_no_collision = no_collision + block_size;
  983. mShape->GetBlockOffsetAndScale(x + 1, y, range_block_offset, range_block_stride, block_offset, block_scale);
  984. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  985. {
  986. *dst_vertex = mShape->GetPosition(max_x, v_y, block_offset, block_scale, *dst_no_collision);
  987. dst_vertex += block_size_plus_1;
  988. dst_no_collision += block_size_plus_1;
  989. }
  990. }
  991. else
  992. max_x_decrement = 1; // We don't have a next block, one less triangle to test
  993. // Decompress block (x, y + 1)
  994. if (y < num_blocks_min_1)
  995. {
  996. uint start = block_size * block_size_plus_1;
  997. dst_vertex = vertices + start;
  998. dst_no_collision = no_collision + start;
  999. mShape->GetBlockOffsetAndScale(x, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  1000. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  1001. {
  1002. *dst_vertex = mShape->GetPosition(v_x, max_y, block_offset, block_scale, *dst_no_collision);
  1003. ++dst_vertex;
  1004. ++dst_no_collision;
  1005. }
  1006. // Decompress single sample of block at (x + 1, y + 1)
  1007. if (x < num_blocks_min_1)
  1008. {
  1009. mShape->GetBlockOffsetAndScale(x + 1, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  1010. *dst_vertex = mShape->GetPosition(max_x, max_y, block_offset, block_scale, *dst_no_collision);
  1011. }
  1012. }
  1013. else
  1014. --max_y; // We don't have a next block, one less triangle to test
  1015. // Update max_x (we've been using it so we couldn't update it earlier)
  1016. max_x -= max_x_decrement;
  1017. // We're going to divide the vertices in 4 blocks to do one more runtime sub-division, calculate the ranges of those blocks
  1018. struct Range
  1019. {
  1020. uint32 mMinX, mMinY, mNumTrianglesX, mNumTrianglesY;
  1021. };
  1022. uint32 half_block_size = block_size >> 1;
  1023. uint32 block_size_x = max_x - min_x - half_block_size;
  1024. uint32 block_size_y = max_y - min_y - half_block_size;
  1025. Range ranges[] =
  1026. {
  1027. { 0, 0, half_block_size, half_block_size },
  1028. { half_block_size, 0, block_size_x, half_block_size },
  1029. { 0, half_block_size, half_block_size, block_size_y },
  1030. { half_block_size, half_block_size, block_size_x, block_size_y },
  1031. };
  1032. // Calculate the min and max of each of the blocks
  1033. Mat44 block_min, block_max;
  1034. for (int block = 0; block < 4; ++block)
  1035. {
  1036. // Get the range for this block
  1037. const Range &range = ranges[block];
  1038. uint32 start = range.mMinX + range.mMinY * block_size_plus_1;
  1039. uint32 size_x_plus_1 = range.mNumTrianglesX + 1;
  1040. uint32 size_y_plus_1 = range.mNumTrianglesY + 1;
  1041. // Calculate where to start reading
  1042. const Vec3 *src_vertex = vertices + start;
  1043. const bool *src_no_collision = no_collision + start;
  1044. uint32 stride = block_size_plus_1 - size_x_plus_1;
  1045. // Start range with a very large inside-out box
  1046. Vec3 value_min = Vec3::sReplicate(1.0e30f);
  1047. Vec3 value_max = Vec3::sReplicate(-1.0e30f);
  1048. // Loop over the samples to determine the min and max of this block
  1049. for (uint32 block_y = 0; block_y < size_y_plus_1; ++block_y)
  1050. {
  1051. for (uint32 block_x = 0; block_x < size_x_plus_1; ++block_x)
  1052. {
  1053. if (!*src_no_collision)
  1054. {
  1055. value_min = Vec3::sMin(value_min, *src_vertex);
  1056. value_max = Vec3::sMax(value_max, *src_vertex);
  1057. }
  1058. ++src_vertex;
  1059. ++src_no_collision;
  1060. }
  1061. src_vertex += stride;
  1062. src_no_collision += stride;
  1063. }
  1064. block_min.SetColumn4(block, Vec4(value_min));
  1065. block_max.SetColumn4(block, Vec4(value_max));
  1066. }
  1067. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1068. // Draw the bounding boxes of the sub-nodes
  1069. for (int block = 0; block < 4; ++block)
  1070. {
  1071. AABox bounds(block_min.GetColumn3(block), block_max.GetColumn3(block));
  1072. if (bounds.IsValid())
  1073. DebugRenderer::sInstance->DrawWireBox(bounds, Color::sYellow);
  1074. }
  1075. #endif // JPH_DEBUG_HEIGHT_FIELD
  1076. // Transpose so we have the mins and maxes of each of the blocks in rows instead of columns
  1077. Mat44 transposed_min = block_min.Transposed();
  1078. Mat44 transposed_max = block_max.Transposed();
  1079. // Check which blocks collide
  1080. // Note: At this point we don't use our own stack but we do allow the visitor to use its own stack
  1081. // to store collision distances so that we can still early out when no closer hits have been found.
  1082. UVec4 colliding_blocks(0, 1, 2, 3);
  1083. int num_results = ioVisitor.VisitRangeBlock(transposed_min.GetColumn4(0), transposed_min.GetColumn4(1), transposed_min.GetColumn4(2), transposed_max.GetColumn4(0), transposed_max.GetColumn4(1), transposed_max.GetColumn4(2), colliding_blocks, mTop);
  1084. // Loop through the results backwards (closest first)
  1085. int result = num_results - 1;
  1086. while (result >= 0)
  1087. {
  1088. // Calculate the min and max of this block
  1089. uint32 block = colliding_blocks[result];
  1090. const Range &range = ranges[block];
  1091. uint32 block_min_x = min_x + range.mMinX;
  1092. uint32 block_max_x = block_min_x + range.mNumTrianglesX;
  1093. uint32 block_min_y = min_y + range.mMinY;
  1094. uint32 block_max_y = block_min_y + range.mNumTrianglesY;
  1095. // Loop triangles
  1096. for (uint32 v_y = block_min_y; v_y < block_max_y; ++v_y)
  1097. for (uint32 v_x = block_min_x; v_x < block_max_x; ++v_x)
  1098. {
  1099. // Get first vertex
  1100. const int offset = (v_y - min_y) * block_size_plus_1 + (v_x - min_x);
  1101. const Vec3 *start_vertex = vertices + offset;
  1102. const bool *start_no_collision = no_collision + offset;
  1103. // Check if vertices shared by both triangles have collision
  1104. if (!start_no_collision[0] && !start_no_collision[block_size_plus_1 + 1])
  1105. {
  1106. // Loop 2 triangles
  1107. for (uint t = 0; t < 2; ++t)
  1108. {
  1109. // Determine triangle vertices
  1110. Vec3 v0, v1, v2;
  1111. if (t == 0)
  1112. {
  1113. // Check third vertex
  1114. if (start_no_collision[block_size_plus_1])
  1115. continue;
  1116. // Get vertices for triangle
  1117. v0 = start_vertex[0];
  1118. v1 = start_vertex[block_size_plus_1];
  1119. v2 = start_vertex[block_size_plus_1 + 1];
  1120. }
  1121. else
  1122. {
  1123. // Check third vertex
  1124. if (start_no_collision[1])
  1125. continue;
  1126. // Get vertices for triangle
  1127. v0 = start_vertex[0];
  1128. v1 = start_vertex[block_size_plus_1 + 1];
  1129. v2 = start_vertex[1];
  1130. }
  1131. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1132. DebugRenderer::sInstance->DrawWireTriangle(RVec3(v0), RVec3(v1), RVec3(v2), Color::sWhite);
  1133. #endif
  1134. // Call visitor
  1135. ioVisitor.VisitTriangle(v_x, v_y, t, v0, v1, v2);
  1136. // Check if we're done
  1137. if (ioVisitor.ShouldAbort())
  1138. return;
  1139. }
  1140. }
  1141. }
  1142. // Fetch next block until we find one that the visitor wants to see
  1143. do
  1144. --result;
  1145. while (result >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop + result));
  1146. }
  1147. }
  1148. else
  1149. {
  1150. // Visit child grid
  1151. uint32 offset = sGridOffsets[level] + (1 << level) * y + x;
  1152. // Decode min/max height
  1153. UVec4 block = UVec4::sLoadInt4Aligned(reinterpret_cast<const uint32 *>(&mShape->mRangeBlocks[offset]));
  1154. Vec4 bounds_miny = oy + sy * block.Expand4Uint16Lo().ToFloat();
  1155. Vec4 bounds_maxy = oy + sy * block.Expand4Uint16Hi().ToFloat();
  1156. // Calculate size of one cell at this grid level
  1157. UVec4 internal_cell_size = UVec4::sReplicate(block_size << (max_level - level - 1)); // subtract 1 from level because we have an internal grid of 2x2
  1158. // Calculate min/max x and z
  1159. UVec4 two_x = UVec4::sReplicate(2 * x); // multiply by two because we have an internal grid of 2x2
  1160. Vec4 bounds_minx = ox + sx * (internal_cell_size * (two_x + UVec4(0, 1, 0, 1))).ToFloat();
  1161. Vec4 bounds_maxx = ox + sx * UVec4::sMin(internal_cell_size * (two_x + UVec4(1, 2, 1, 2)), sample_count_min_1).ToFloat();
  1162. UVec4 two_y = UVec4::sReplicate(2 * y);
  1163. Vec4 bounds_minz = oz + sz * (internal_cell_size * (two_y + UVec4(0, 0, 1, 1))).ToFloat();
  1164. Vec4 bounds_maxz = oz + sz * UVec4::sMin(internal_cell_size * (two_y + UVec4(1, 1, 2, 2)), sample_count_min_1).ToFloat();
  1165. // Calculate properties of child blocks
  1166. UVec4 properties = UVec4::sReplicate(((level + 1) << cLevelShift) + (y << (cNumBitsXY + 1)) + (x << 1)) + UVec4(0, 1, 1 << cNumBitsXY, (1 << cNumBitsXY) + 1);
  1167. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1168. // Draw boxes
  1169. for (int i = 0; i < 4; ++i)
  1170. {
  1171. AABox b(Vec3(bounds_minx[i], bounds_miny[i], bounds_minz[i]), Vec3(bounds_maxx[i], bounds_maxy[i], bounds_maxz[i]));
  1172. if (b.IsValid())
  1173. DebugRenderer::sInstance->DrawWireBox(b, Color::sGreen);
  1174. }
  1175. #endif
  1176. // Check which sub nodes to visit
  1177. int num_results = ioVisitor.VisitRangeBlock(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, properties, mTop);
  1178. // Push them onto the stack
  1179. JPH_ASSERT(mTop + 4 < cStackSize);
  1180. properties.StoreInt4(&mPropertiesStack[mTop]);
  1181. mTop += num_results;
  1182. }
  1183. // Check if we're done
  1184. if (ioVisitor.ShouldAbort())
  1185. return;
  1186. // Fetch next node until we find one that the visitor wants to see
  1187. do
  1188. --mTop;
  1189. while (mTop >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop));
  1190. }
  1191. while (mTop >= 0);
  1192. }
  1193. // This can be used to have the visitor early out (ioVisitor.ShouldAbort() returns true) and later continue again (call WalkHeightField() again)
  1194. JPH_INLINE bool IsDoneWalking() const
  1195. {
  1196. return mTop < 0;
  1197. }
  1198. private:
  1199. const HeightFieldShape * mShape;
  1200. int mTop = 0;
  1201. uint32 mPropertiesStack[cStackSize];
  1202. };
  1203. template <class Visitor>
  1204. JPH_INLINE void HeightFieldShape::WalkHeightField(Visitor &ioVisitor) const
  1205. {
  1206. DecodingContext ctx(this);
  1207. ctx.WalkHeightField(ioVisitor);
  1208. }
  1209. bool HeightFieldShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  1210. {
  1211. JPH_PROFILE_FUNCTION();
  1212. struct Visitor
  1213. {
  1214. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) :
  1215. mHit(ioHit),
  1216. mRayOrigin(inRay.mOrigin),
  1217. mRayDirection(inRay.mDirection),
  1218. mRayInvDirection(inRay.mDirection),
  1219. mShape(inShape),
  1220. mSubShapeIDCreator(inSubShapeIDCreator)
  1221. {
  1222. }
  1223. JPH_INLINE bool ShouldAbort() const
  1224. {
  1225. return mHit.mFraction <= 0.0f;
  1226. }
  1227. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1228. {
  1229. return mDistanceStack[inStackTop] < mHit.mFraction;
  1230. }
  1231. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1232. {
  1233. // Test bounds of 4 children
  1234. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1235. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1236. return SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);
  1237. }
  1238. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1239. {
  1240. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1241. if (fraction < mHit.mFraction)
  1242. {
  1243. // It's a closer hit
  1244. mHit.mFraction = fraction;
  1245. mHit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1246. mReturnValue = true;
  1247. }
  1248. }
  1249. RayCastResult & mHit;
  1250. Vec3 mRayOrigin;
  1251. Vec3 mRayDirection;
  1252. RayInvDirection mRayInvDirection;
  1253. const HeightFieldShape *mShape;
  1254. SubShapeIDCreator mSubShapeIDCreator;
  1255. bool mReturnValue = false;
  1256. float mDistanceStack[cStackSize];
  1257. };
  1258. Visitor visitor(this, inRay, inSubShapeIDCreator, ioHit);
  1259. WalkHeightField(visitor);
  1260. return visitor.mReturnValue;
  1261. }
  1262. void HeightFieldShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  1263. {
  1264. JPH_PROFILE_FUNCTION();
  1265. // Test shape filter
  1266. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  1267. return;
  1268. struct Visitor
  1269. {
  1270. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) :
  1271. mCollector(ioCollector),
  1272. mRayOrigin(inRay.mOrigin),
  1273. mRayDirection(inRay.mDirection),
  1274. mRayInvDirection(inRay.mDirection),
  1275. mBackFaceMode(inRayCastSettings.mBackFaceMode),
  1276. mShape(inShape),
  1277. mSubShapeIDCreator(inSubShapeIDCreator)
  1278. {
  1279. }
  1280. JPH_INLINE bool ShouldAbort() const
  1281. {
  1282. return mCollector.ShouldEarlyOut();
  1283. }
  1284. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1285. {
  1286. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1287. }
  1288. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1289. {
  1290. // Test bounds of 4 children
  1291. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1292. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1293. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1294. }
  1295. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  1296. {
  1297. // Back facing check
  1298. if (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)
  1299. return;
  1300. // Check the triangle
  1301. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1302. if (fraction < mCollector.GetEarlyOutFraction())
  1303. {
  1304. RayCastResult hit;
  1305. hit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());
  1306. hit.mFraction = fraction;
  1307. hit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1308. mCollector.AddHit(hit);
  1309. }
  1310. }
  1311. CastRayCollector & mCollector;
  1312. Vec3 mRayOrigin;
  1313. Vec3 mRayDirection;
  1314. RayInvDirection mRayInvDirection;
  1315. EBackFaceMode mBackFaceMode;
  1316. const HeightFieldShape *mShape;
  1317. SubShapeIDCreator mSubShapeIDCreator;
  1318. float mDistanceStack[cStackSize];
  1319. };
  1320. Visitor visitor(this, inRay, inRayCastSettings, inSubShapeIDCreator, ioCollector);
  1321. WalkHeightField(visitor);
  1322. }
  1323. void HeightFieldShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  1324. {
  1325. // A height field doesn't have volume, so we can't test insideness
  1326. }
  1327. void HeightFieldShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, Array<SoftBodyVertex> &ioVertices, float inDeltaTime, Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  1328. {
  1329. sCollideSoftBodyVerticesUsingRayCast(*this, inCenterOfMassTransform, inScale, ioVertices, inDeltaTime, inDisplacementDueToGravity, inCollidingShapeIndex);
  1330. }
  1331. void HeightFieldShape::sCastConvexVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  1332. {
  1333. JPH_PROFILE_FUNCTION();
  1334. struct Visitor : public CastConvexVsTriangles
  1335. {
  1336. using CastConvexVsTriangles::CastConvexVsTriangles;
  1337. JPH_INLINE bool ShouldAbort() const
  1338. {
  1339. return mCollector.ShouldEarlyOut();
  1340. }
  1341. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1342. {
  1343. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  1344. }
  1345. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1346. {
  1347. // Scale the bounding boxes of this node
  1348. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1349. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1350. // Enlarge them by the casted shape's box extents
  1351. AABox4EnlargeWithExtent(mBoxExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1352. // Test bounds of 4 children
  1353. Vec4 distance = RayAABox4(mBoxCenter, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1354. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1355. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1356. }
  1357. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1358. {
  1359. // Create sub shape id for this part
  1360. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1361. // Determine active edges
  1362. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1363. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1364. }
  1365. const HeightFieldShape * mShape2;
  1366. RayInvDirection mInvDirection;
  1367. Vec3 mBoxCenter;
  1368. Vec3 mBoxExtent;
  1369. SubShapeIDCreator mSubShapeIDCreator2;
  1370. float mDistanceStack[cStackSize];
  1371. };
  1372. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);
  1373. const HeightFieldShape *shape = static_cast<const HeightFieldShape *>(inShape);
  1374. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  1375. visitor.mShape2 = shape;
  1376. visitor.mInvDirection.Set(inShapeCast.mDirection);
  1377. visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();
  1378. visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();
  1379. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1380. shape->WalkHeightField(visitor);
  1381. }
  1382. void HeightFieldShape::sCastSphereVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  1383. {
  1384. JPH_PROFILE_FUNCTION();
  1385. struct Visitor : public CastSphereVsTriangles
  1386. {
  1387. using CastSphereVsTriangles::CastSphereVsTriangles;
  1388. JPH_INLINE bool ShouldAbort() const
  1389. {
  1390. return mCollector.ShouldEarlyOut();
  1391. }
  1392. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1393. {
  1394. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  1395. }
  1396. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1397. {
  1398. // Scale the bounding boxes of this node
  1399. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1400. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1401. // Enlarge them by the radius of the sphere
  1402. AABox4EnlargeWithExtent(Vec3::sReplicate(mRadius), bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1403. // Test bounds of 4 children
  1404. Vec4 distance = RayAABox4(mStart, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1405. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1406. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1407. }
  1408. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1409. {
  1410. // Create sub shape id for this part
  1411. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1412. // Determine active edges
  1413. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1414. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1415. }
  1416. const HeightFieldShape * mShape2;
  1417. RayInvDirection mInvDirection;
  1418. SubShapeIDCreator mSubShapeIDCreator2;
  1419. float mDistanceStack[cStackSize];
  1420. };
  1421. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);
  1422. const HeightFieldShape *shape = static_cast<const HeightFieldShape *>(inShape);
  1423. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  1424. visitor.mShape2 = shape;
  1425. visitor.mInvDirection.Set(inShapeCast.mDirection);
  1426. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1427. shape->WalkHeightField(visitor);
  1428. }
  1429. struct HeightFieldShape::HSGetTrianglesContext
  1430. {
  1431. HSGetTrianglesContext(const HeightFieldShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  1432. mDecodeCtx(inShape),
  1433. mShape(inShape),
  1434. mLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),
  1435. mHeightFieldScale(inScale),
  1436. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  1437. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  1438. {
  1439. }
  1440. bool ShouldAbort() const
  1441. {
  1442. return mShouldAbort;
  1443. }
  1444. bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1445. {
  1446. return true;
  1447. }
  1448. int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1449. {
  1450. // Scale the bounding boxes of this node
  1451. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1452. AABox4Scale(mHeightFieldScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1453. // Test which nodes collide
  1454. UVec4 collides = AABox4VsBox(mLocalBox, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1455. return CountAndSortTrues(collides, ioProperties);
  1456. }
  1457. void VisitTriangle(uint inX, uint inY, [[maybe_unused]] uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1458. {
  1459. // When the buffer is full and we cannot process the triangles, abort the height field walk. The next time GetTrianglesNext is called we will continue here.
  1460. if (mNumTrianglesFound + 1 > mMaxTrianglesRequested)
  1461. {
  1462. mShouldAbort = true;
  1463. return;
  1464. }
  1465. // Store vertices as Float3
  1466. if (mIsInsideOut)
  1467. {
  1468. // Reverse vertices
  1469. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  1470. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  1471. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  1472. }
  1473. else
  1474. {
  1475. // Normal scale
  1476. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  1477. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  1478. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  1479. }
  1480. // Decode material
  1481. if (mMaterials != nullptr)
  1482. *mMaterials++ = mShape->GetMaterial(inX, inY);
  1483. // Accumulate triangles found
  1484. mNumTrianglesFound++;
  1485. }
  1486. DecodingContext mDecodeCtx;
  1487. const HeightFieldShape * mShape;
  1488. OrientedBox mLocalBox;
  1489. Vec3 mHeightFieldScale;
  1490. Mat44 mLocalToWorld;
  1491. int mMaxTrianglesRequested;
  1492. Float3 * mTriangleVertices;
  1493. int mNumTrianglesFound;
  1494. const PhysicsMaterial ** mMaterials;
  1495. bool mShouldAbort;
  1496. bool mIsInsideOut;
  1497. };
  1498. void HeightFieldShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  1499. {
  1500. static_assert(sizeof(HSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  1501. JPH_ASSERT(IsAligned(&ioContext, alignof(HSGetTrianglesContext)));
  1502. new (&ioContext) HSGetTrianglesContext(this, inBox, inPositionCOM, inRotation, inScale);
  1503. }
  1504. int HeightFieldShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  1505. {
  1506. static_assert(cGetTrianglesMinTrianglesRequested >= 1, "cGetTrianglesMinTrianglesRequested is too small");
  1507. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  1508. // Check if we're done
  1509. HSGetTrianglesContext &context = (HSGetTrianglesContext &)ioContext;
  1510. if (context.mDecodeCtx.IsDoneWalking())
  1511. return 0;
  1512. // Store parameters on context
  1513. context.mMaxTrianglesRequested = inMaxTrianglesRequested;
  1514. context.mTriangleVertices = outTriangleVertices;
  1515. context.mMaterials = outMaterials;
  1516. context.mShouldAbort = false; // Reset the abort flag
  1517. context.mNumTrianglesFound = 0;
  1518. // Continue (or start) walking the height field
  1519. context.mDecodeCtx.WalkHeightField(context);
  1520. return context.mNumTrianglesFound;
  1521. }
  1522. void HeightFieldShape::sCollideConvexVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  1523. {
  1524. JPH_PROFILE_FUNCTION();
  1525. // Get the shapes
  1526. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  1527. JPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);
  1528. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  1529. const HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);
  1530. struct Visitor : public CollideConvexVsTriangles
  1531. {
  1532. using CollideConvexVsTriangles::CollideConvexVsTriangles;
  1533. JPH_INLINE bool ShouldAbort() const
  1534. {
  1535. return mCollector.ShouldEarlyOut();
  1536. }
  1537. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1538. {
  1539. return true;
  1540. }
  1541. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1542. {
  1543. // Scale the bounding boxes of this node
  1544. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1545. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1546. // Test which nodes collide
  1547. UVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1548. return CountAndSortTrues(collides, ioProperties);
  1549. }
  1550. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1551. {
  1552. // Create ID for triangle
  1553. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1554. // Determine active edges
  1555. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1556. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1557. }
  1558. const HeightFieldShape * mShape2;
  1559. SubShapeIDCreator mSubShapeIDCreator2;
  1560. };
  1561. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  1562. visitor.mShape2 = shape2;
  1563. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1564. shape2->WalkHeightField(visitor);
  1565. }
  1566. void HeightFieldShape::sCollideSphereVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter)
  1567. {
  1568. JPH_PROFILE_FUNCTION();
  1569. // Get the shapes
  1570. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  1571. JPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);
  1572. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  1573. const HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);
  1574. struct Visitor : public CollideSphereVsTriangles
  1575. {
  1576. using CollideSphereVsTriangles::CollideSphereVsTriangles;
  1577. JPH_INLINE bool ShouldAbort() const
  1578. {
  1579. return mCollector.ShouldEarlyOut();
  1580. }
  1581. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1582. {
  1583. return true;
  1584. }
  1585. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1586. {
  1587. // Scale the bounding boxes of this node
  1588. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1589. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1590. // Test which nodes collide
  1591. UVec4 collides = AABox4VsSphere(mSphereCenterIn2, mRadiusPlusMaxSeparationSq, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1592. return CountAndSortTrues(collides, ioProperties);
  1593. }
  1594. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1595. {
  1596. // Create ID for triangle
  1597. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1598. // Determine active edges
  1599. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1600. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1601. }
  1602. const HeightFieldShape * mShape2;
  1603. SubShapeIDCreator mSubShapeIDCreator2;
  1604. };
  1605. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  1606. visitor.mShape2 = shape2;
  1607. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1608. shape2->WalkHeightField(visitor);
  1609. }
  1610. void HeightFieldShape::SaveBinaryState(StreamOut &inStream) const
  1611. {
  1612. Shape::SaveBinaryState(inStream);
  1613. inStream.Write(mOffset);
  1614. inStream.Write(mScale);
  1615. inStream.Write(mSampleCount);
  1616. inStream.Write(mBlockSize);
  1617. inStream.Write(mBitsPerSample);
  1618. inStream.Write(mMinSample);
  1619. inStream.Write(mMaxSample);
  1620. inStream.Write(mRangeBlocks);
  1621. inStream.Write(mHeightSamples);
  1622. inStream.Write(mActiveEdges);
  1623. inStream.Write(mMaterialIndices);
  1624. inStream.Write(mNumBitsPerMaterialIndex);
  1625. }
  1626. void HeightFieldShape::RestoreBinaryState(StreamIn &inStream)
  1627. {
  1628. Shape::RestoreBinaryState(inStream);
  1629. inStream.Read(mOffset);
  1630. inStream.Read(mScale);
  1631. inStream.Read(mSampleCount);
  1632. inStream.Read(mBlockSize);
  1633. inStream.Read(mBitsPerSample);
  1634. inStream.Read(mMinSample);
  1635. inStream.Read(mMaxSample);
  1636. inStream.Read(mRangeBlocks);
  1637. inStream.Read(mHeightSamples);
  1638. inStream.Read(mActiveEdges);
  1639. inStream.Read(mMaterialIndices);
  1640. inStream.Read(mNumBitsPerMaterialIndex);
  1641. CacheValues();
  1642. }
  1643. void HeightFieldShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  1644. {
  1645. outMaterials = mMaterials;
  1646. }
  1647. void HeightFieldShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  1648. {
  1649. mMaterials.assign(inMaterials, inMaterials + inNumMaterials);
  1650. }
  1651. Shape::Stats HeightFieldShape::GetStats() const
  1652. {
  1653. return Stats(
  1654. sizeof(*this)
  1655. + mMaterials.size() * sizeof(Ref<PhysicsMaterial>)
  1656. + mRangeBlocks.size() * sizeof(RangeBlock)
  1657. + mHeightSamples.size() * sizeof(uint8)
  1658. + mActiveEdges.size() * sizeof(uint8)
  1659. + mMaterialIndices.size() * sizeof(uint8),
  1660. mHeightSamples.empty()? 0 : Square(mSampleCount - 1) * 2);
  1661. }
  1662. void HeightFieldShape::sRegister()
  1663. {
  1664. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::HeightField);
  1665. f.mConstruct = []() -> Shape * { return new HeightFieldShape; };
  1666. f.mColor = Color::sPurple;
  1667. for (EShapeSubType s : sConvexSubShapeTypes)
  1668. {
  1669. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::HeightField, sCollideConvexVsHeightField);
  1670. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::HeightField, sCastConvexVsHeightField);
  1671. CollisionDispatch::sRegisterCastShape(EShapeSubType::HeightField, s, CollisionDispatch::sReversedCastShape);
  1672. CollisionDispatch::sRegisterCollideShape(EShapeSubType::HeightField, s, CollisionDispatch::sReversedCollideShape);
  1673. }
  1674. // Specialized collision functions
  1675. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::HeightField, sCollideSphereVsHeightField);
  1676. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::HeightField, sCastSphereVsHeightField);
  1677. }
  1678. JPH_NAMESPACE_END