HeightFieldShape.cpp 70 KB

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