HeightFieldShape.cpp 101 KB

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