HeightFieldShape.cpp 88 KB

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