SoftBodySharedSettings.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/SoftBody/SoftBodySharedSettings.h>
  6. #include <Jolt/Physics/SoftBody/SoftBodyUpdateContext.h>
  7. #include <Jolt/ObjectStream/TypeDeclarations.h>
  8. #include <Jolt/Core/StreamIn.h>
  9. #include <Jolt/Core/StreamOut.h>
  10. #include <Jolt/Core/QuickSort.h>
  11. #include <Jolt/Core/UnorderedMap.h>
  12. #include <Jolt/Core/UnorderedSet.h>
  13. #include <Jolt/Core/BinaryHeap.h>
  14. JPH_NAMESPACE_BEGIN
  15. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::Vertex)
  16. {
  17. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Vertex, mPosition)
  18. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Vertex, mVelocity)
  19. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Vertex, mInvMass)
  20. }
  21. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::Face)
  22. {
  23. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Face, mVertex)
  24. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Face, mMaterialIndex)
  25. }
  26. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::Edge)
  27. {
  28. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Edge, mVertex)
  29. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Edge, mRestLength)
  30. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Edge, mCompliance)
  31. }
  32. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::RodStretchShear)
  33. {
  34. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodStretchShear, mVertex)
  35. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodStretchShear, mLength)
  36. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodStretchShear, mInvMass)
  37. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodStretchShear, mCompliance)
  38. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodStretchShear, mBishop)
  39. }
  40. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::RodBendTwist)
  41. {
  42. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodBendTwist, mRod)
  43. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodBendTwist, mCompliance)
  44. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::RodBendTwist, mOmega0)
  45. }
  46. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::DihedralBend)
  47. {
  48. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::DihedralBend, mVertex)
  49. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::DihedralBend, mCompliance)
  50. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::DihedralBend, mInitialAngle)
  51. }
  52. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::Volume)
  53. {
  54. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Volume, mVertex)
  55. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Volume, mSixRestVolume)
  56. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Volume, mCompliance)
  57. }
  58. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::InvBind)
  59. {
  60. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::InvBind, mJointIndex)
  61. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::InvBind, mInvBind)
  62. }
  63. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::SkinWeight)
  64. {
  65. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::SkinWeight, mInvBindIndex)
  66. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::SkinWeight, mWeight)
  67. }
  68. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::Skinned)
  69. {
  70. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Skinned, mVertex)
  71. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Skinned, mWeights)
  72. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Skinned, mMaxDistance)
  73. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Skinned, mBackStopDistance)
  74. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::Skinned, mBackStopRadius)
  75. }
  76. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings::LRA)
  77. {
  78. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::LRA, mVertex)
  79. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings::LRA, mMaxDistance)
  80. }
  81. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(SoftBodySharedSettings)
  82. {
  83. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mVertices)
  84. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mFaces)
  85. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mEdgeConstraints)
  86. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mDihedralBendConstraints)
  87. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mVolumeConstraints)
  88. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mSkinnedConstraints)
  89. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mInvBindMatrices)
  90. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mLRAConstraints)
  91. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mRodStretchShearConstraints)
  92. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mRodBendTwistConstraints)
  93. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mMaterials)
  94. JPH_ADD_ATTRIBUTE(SoftBodySharedSettings, mVertexRadius)
  95. }
  96. void SoftBodySharedSettings::CalculateClosestKinematic()
  97. {
  98. // Check if we already calculated this
  99. if (!mClosestKinematic.empty())
  100. return;
  101. // Reserve output size
  102. mClosestKinematic.resize(mVertices.size());
  103. // Create a list of connected vertices
  104. Array<Array<uint32>> connectivity;
  105. connectivity.resize(mVertices.size());
  106. for (const Edge &e : mEdgeConstraints)
  107. {
  108. connectivity[e.mVertex[0]].push_back(e.mVertex[1]);
  109. connectivity[e.mVertex[1]].push_back(e.mVertex[0]);
  110. }
  111. for (const RodStretchShear &r : mRodStretchShearConstraints)
  112. {
  113. connectivity[r.mVertex[0]].push_back(r.mVertex[1]);
  114. connectivity[r.mVertex[1]].push_back(r.mVertex[0]);
  115. }
  116. // Use Dijkstra's algorithm to find the closest kinematic vertex for each vertex
  117. // See: https://en.wikipedia.org/wiki/Dijkstra's_algorithm
  118. //
  119. // An element in the open list
  120. struct Open
  121. {
  122. // Order so that we get the shortest distance first
  123. bool operator < (const Open &inRHS) const
  124. {
  125. return mDistance > inRHS.mDistance;
  126. }
  127. uint32 mVertex;
  128. float mDistance;
  129. };
  130. // Start with all kinematic elements
  131. Array<Open> to_visit;
  132. for (uint32 v = 0; v < mVertices.size(); ++v)
  133. if (mVertices[v].mInvMass == 0.0f)
  134. {
  135. mClosestKinematic[v].mVertex = v;
  136. mClosestKinematic[v].mDistance = 0.0f;
  137. to_visit.push_back({ v, 0.0f });
  138. BinaryHeapPush(to_visit.begin(), to_visit.end(), std::less<Open> { });
  139. }
  140. // Visit all vertices remembering the closest kinematic vertex and its distance
  141. JPH_IF_ENABLE_ASSERTS(float last_closest = 0.0f;)
  142. while (!to_visit.empty())
  143. {
  144. // Pop element from the open list
  145. BinaryHeapPop(to_visit.begin(), to_visit.end(), std::less<Open> { });
  146. Open current = to_visit.back();
  147. to_visit.pop_back();
  148. JPH_ASSERT(current.mDistance >= last_closest);
  149. JPH_IF_ENABLE_ASSERTS(last_closest = current.mDistance;)
  150. // Loop through all of its connected vertices
  151. for (uint32 v : connectivity[current.mVertex])
  152. {
  153. // Calculate distance from the current vertex to this target vertex and check if it is smaller
  154. float new_distance = current.mDistance + (Vec3(mVertices[v].mPosition) - Vec3(mVertices[current.mVertex].mPosition)).Length();
  155. if (new_distance < mClosestKinematic[v].mDistance)
  156. {
  157. // Remember new closest vertex
  158. mClosestKinematic[v].mVertex = mClosestKinematic[current.mVertex].mVertex;
  159. mClosestKinematic[v].mDistance = new_distance;
  160. to_visit.push_back({ v, new_distance });
  161. BinaryHeapPush(to_visit.begin(), to_visit.end(), std::less<Open> { });
  162. }
  163. }
  164. }
  165. }
  166. void SoftBodySharedSettings::CreateConstraints(const VertexAttributes *inVertexAttributes, uint inVertexAttributesLength, EBendType inBendType, float inAngleTolerance)
  167. {
  168. struct EdgeHelper
  169. {
  170. uint32 mVertex[2];
  171. uint32 mEdgeIdx;
  172. };
  173. // Create list of all edges
  174. Array<EdgeHelper> edges;
  175. edges.reserve(mFaces.size() * 3);
  176. for (const Face &f : mFaces)
  177. for (int i = 0; i < 3; ++i)
  178. {
  179. uint32 v0 = f.mVertex[i];
  180. uint32 v1 = f.mVertex[(i + 1) % 3];
  181. EdgeHelper e;
  182. e.mVertex[0] = min(v0, v1);
  183. e.mVertex[1] = max(v0, v1);
  184. e.mEdgeIdx = uint32(&f - mFaces.data()) * 3 + i;
  185. edges.push_back(e);
  186. }
  187. // Sort the edges
  188. QuickSort(edges.begin(), edges.end(), [](const EdgeHelper &inLHS, const EdgeHelper &inRHS) { return inLHS.mVertex[0] < inRHS.mVertex[0] || (inLHS.mVertex[0] == inRHS.mVertex[0] && inLHS.mVertex[1] < inRHS.mVertex[1]); });
  189. // Only add edges if one of the vertices is movable
  190. auto add_edge = [this](uint32 inVtx1, uint32 inVtx2, float inCompliance1, float inCompliance2) {
  191. if ((mVertices[inVtx1].mInvMass > 0.0f || mVertices[inVtx2].mInvMass > 0.0f)
  192. && inCompliance1 < FLT_MAX && inCompliance2 < FLT_MAX)
  193. {
  194. Edge temp_edge;
  195. temp_edge.mVertex[0] = inVtx1;
  196. temp_edge.mVertex[1] = inVtx2;
  197. temp_edge.mCompliance = 0.5f * (inCompliance1 + inCompliance2);
  198. temp_edge.mRestLength = (Vec3(mVertices[inVtx2].mPosition) - Vec3(mVertices[inVtx1].mPosition)).Length();
  199. JPH_ASSERT(temp_edge.mRestLength > 0.0f);
  200. mEdgeConstraints.push_back(temp_edge);
  201. }
  202. };
  203. // Helper function to get the attributes of a vertex
  204. auto attr = [inVertexAttributes, inVertexAttributesLength](uint32 inVertex) {
  205. return inVertexAttributes[min(inVertex, inVertexAttributesLength - 1)];
  206. };
  207. // Create the constraints
  208. float sq_sin_tolerance = Square(Sin(inAngleTolerance));
  209. float sq_cos_tolerance = Square(Cos(inAngleTolerance));
  210. mEdgeConstraints.clear();
  211. mEdgeConstraints.reserve(edges.size());
  212. for (Array<EdgeHelper>::size_type i = 0; i < edges.size(); ++i)
  213. {
  214. const EdgeHelper &e0 = edges[i];
  215. // Get attributes for the vertices of the edge
  216. const VertexAttributes &a0 = attr(e0.mVertex[0]);
  217. const VertexAttributes &a1 = attr(e0.mVertex[1]);
  218. // Flag that indicates if this edge is a shear edge (if 2 triangles form a quad-like shape and this edge is on the diagonal)
  219. bool is_shear = false;
  220. // Test if there are any shared edges
  221. for (Array<EdgeHelper>::size_type j = i + 1; j < edges.size(); ++j)
  222. {
  223. const EdgeHelper &e1 = edges[j];
  224. if (e0.mVertex[0] == e1.mVertex[0] && e0.mVertex[1] == e1.mVertex[1])
  225. {
  226. // Get opposing vertices
  227. const Face &f0 = mFaces[e0.mEdgeIdx / 3];
  228. const Face &f1 = mFaces[e1.mEdgeIdx / 3];
  229. uint32 vopposite0 = f0.mVertex[(e0.mEdgeIdx + 2) % 3];
  230. uint32 vopposite1 = f1.mVertex[(e1.mEdgeIdx + 2) % 3];
  231. const VertexAttributes &a_opposite0 = attr(vopposite0);
  232. const VertexAttributes &a_opposite1 = attr(vopposite1);
  233. // If the opposite vertices happen to be the same vertex then we have 2 triangles back to back and we skip creating shear / bend constraints
  234. if (vopposite0 == vopposite1)
  235. continue;
  236. // Faces should be roughly in a plane
  237. Vec3 n0 = (Vec3(mVertices[f0.mVertex[2]].mPosition) - Vec3(mVertices[f0.mVertex[0]].mPosition)).Cross(Vec3(mVertices[f0.mVertex[1]].mPosition) - Vec3(mVertices[f0.mVertex[0]].mPosition));
  238. Vec3 n1 = (Vec3(mVertices[f1.mVertex[2]].mPosition) - Vec3(mVertices[f1.mVertex[0]].mPosition)).Cross(Vec3(mVertices[f1.mVertex[1]].mPosition) - Vec3(mVertices[f1.mVertex[0]].mPosition));
  239. float n0_dot_n1 = n0.Dot(n1);
  240. if (n0_dot_n1 > 0.0f
  241. && Square(n0_dot_n1) > sq_cos_tolerance * n0.LengthSq() * n1.LengthSq())
  242. {
  243. // Faces should approximately form a quad
  244. Vec3 e0_dir = Vec3(mVertices[vopposite0].mPosition) - Vec3(mVertices[e0.mVertex[0]].mPosition);
  245. Vec3 e1_dir = Vec3(mVertices[vopposite1].mPosition) - Vec3(mVertices[e0.mVertex[0]].mPosition);
  246. if (Square(e0_dir.Dot(e1_dir)) < sq_sin_tolerance * e0_dir.LengthSq() * e1_dir.LengthSq())
  247. {
  248. // Shear constraint
  249. add_edge(vopposite0, vopposite1, a_opposite0.mShearCompliance, a_opposite1.mShearCompliance);
  250. is_shear = true;
  251. }
  252. }
  253. // Bend constraint
  254. switch (inBendType)
  255. {
  256. case EBendType::None:
  257. // Do nothing
  258. break;
  259. case EBendType::Distance:
  260. // Create an edge constraint to represent the bend constraint
  261. // Use the bend compliance of the shared edge
  262. if (!is_shear)
  263. add_edge(vopposite0, vopposite1, a0.mBendCompliance, a1.mBendCompliance);
  264. break;
  265. case EBendType::Dihedral:
  266. // Test if both opposite vertices are free to move
  267. if ((mVertices[vopposite0].mInvMass > 0.0f || mVertices[vopposite1].mInvMass > 0.0f)
  268. && a0.mBendCompliance < FLT_MAX && a1.mBendCompliance < FLT_MAX)
  269. {
  270. // Create a bend constraint
  271. // Use the bend compliance of the shared edge
  272. mDihedralBendConstraints.emplace_back(e0.mVertex[0], e0.mVertex[1], vopposite0, vopposite1, 0.5f * (a0.mBendCompliance + a1.mBendCompliance));
  273. }
  274. break;
  275. }
  276. }
  277. else
  278. {
  279. // Start iterating from the first non-shared edge
  280. i = j - 1;
  281. break;
  282. }
  283. }
  284. // Create a edge constraint for the current edge
  285. add_edge(e0.mVertex[0], e0.mVertex[1], is_shear? a0.mShearCompliance : a0.mCompliance, is_shear? a1.mShearCompliance : a1.mCompliance);
  286. }
  287. mEdgeConstraints.shrink_to_fit();
  288. // Calculate the initial angle for all bend constraints
  289. CalculateBendConstraintConstants();
  290. // Check if any vertices have LRA constraints
  291. bool has_lra_constraints = false;
  292. for (const VertexAttributes *va = inVertexAttributes; va < inVertexAttributes + inVertexAttributesLength; ++va)
  293. if (va->mLRAType != ELRAType::None)
  294. {
  295. has_lra_constraints = true;
  296. break;
  297. }
  298. if (has_lra_constraints)
  299. {
  300. // Ensure we have calculated the closest kinematic vertex for each vertex
  301. CalculateClosestKinematic();
  302. // Find non-kinematic vertices
  303. for (uint32 v = 0; v < (uint32)mVertices.size(); ++v)
  304. if (mVertices[v].mInvMass > 0.0f)
  305. {
  306. // Check if a closest vertex was found
  307. uint32 closest = mClosestKinematic[v].mVertex;
  308. if (closest != 0xffffffff)
  309. {
  310. // Check which LRA constraint to create
  311. const VertexAttributes &va = attr(v);
  312. switch (va.mLRAType)
  313. {
  314. case ELRAType::None:
  315. break;
  316. case ELRAType::EuclideanDistance:
  317. mLRAConstraints.emplace_back(closest, v, va.mLRAMaxDistanceMultiplier * (Vec3(mVertices[closest].mPosition) - Vec3(mVertices[v].mPosition)).Length());
  318. break;
  319. case ELRAType::GeodesicDistance:
  320. mLRAConstraints.emplace_back(closest, v, va.mLRAMaxDistanceMultiplier * mClosestKinematic[v].mDistance);
  321. break;
  322. }
  323. }
  324. }
  325. }
  326. }
  327. void SoftBodySharedSettings::CalculateEdgeLengths()
  328. {
  329. for (Edge &e : mEdgeConstraints)
  330. {
  331. JPH_ASSERT(e.mVertex[0] != e.mVertex[1], "Edges need to connect 2 different vertices");
  332. e.mRestLength = (Vec3(mVertices[e.mVertex[1]].mPosition) - Vec3(mVertices[e.mVertex[0]].mPosition)).Length();
  333. JPH_ASSERT(e.mRestLength > 0.0f);
  334. }
  335. }
  336. void SoftBodySharedSettings::CalculateRodProperties()
  337. {
  338. // Mark connections through bend twist constraints
  339. Array<Array<uint32>> connections;
  340. connections.resize(mRodStretchShearConstraints.size());
  341. for (const RodBendTwist &c : mRodBendTwistConstraints)
  342. {
  343. JPH_ASSERT(c.mRod[0] != c.mRod[1], "A bend twist constraint needs to be attached to different rods");
  344. connections[c.mRod[1]].push_back(c.mRod[0]);
  345. connections[c.mRod[0]].push_back(c.mRod[1]);
  346. }
  347. // Now calculate the Bishop frames for all rods
  348. struct Entry
  349. {
  350. uint32 mFrom; // Rod we're coming from
  351. uint32 mTo; // Rod we're going to
  352. };
  353. Array<Entry> stack;
  354. stack.reserve(mRodStretchShearConstraints.size());
  355. for (uint32 r0_idx = 0; r0_idx < mRodStretchShearConstraints.size(); ++r0_idx)
  356. {
  357. RodStretchShear &r0 = mRodStretchShearConstraints[r0_idx];
  358. // Do not calculate a 2nd time
  359. if (r0.mBishop == Quat::sZero())
  360. {
  361. // Calculate the frame for this rod
  362. {
  363. Vec3 tangent = Vec3(mVertices[r0.mVertex[1]].mPosition) - Vec3(mVertices[r0.mVertex[0]].mPosition);
  364. r0.mLength = tangent.Length();
  365. JPH_ASSERT(r0.mLength > 0.0f, "Rods of zero length are not supported!");
  366. tangent /= r0.mLength;
  367. Vec3 normal = tangent.GetNormalizedPerpendicular();
  368. Vec3 binormal = tangent.Cross(normal);
  369. r0.mBishop = Mat44(Vec4(normal, 0), Vec4(binormal, 0), Vec4(tangent, 0), Vec4(0, 0, 0, 1)).GetQuaternion().Normalized();
  370. }
  371. // Add connected rods to the stack if they haven't been calculated yet
  372. for (uint32 r1_idx : connections[r0_idx])
  373. if (mRodStretchShearConstraints[r1_idx].mBishop == Quat::sZero())
  374. stack.push_back({ r0_idx, r1_idx });
  375. // Now connect the bishop frame for all connected rods on the stack
  376. // This follows the procedure outlined in "Discrete Elastic Rods" - M. Bergou et al.
  377. // See: https://www.cs.columbia.edu/cg/pdfs/143-rods.pdf
  378. while (!stack.empty())
  379. {
  380. uint32 r1_idx = stack.back().mFrom;
  381. uint32 r2_idx = stack.back().mTo;
  382. stack.pop_back();
  383. const RodStretchShear &r1 = mRodStretchShearConstraints[r1_idx];
  384. RodStretchShear &r2 = mRodStretchShearConstraints[r2_idx];
  385. // Get the normal and tangent of the first rod's Bishop frame (that was already calculated)
  386. Mat44 r1_frame = Mat44::sRotation(r1.mBishop);
  387. Vec3 tangent1 = r1_frame.GetAxisZ();
  388. Vec3 normal1 = r1_frame.GetAxisX();
  389. // Calculate the Bishop frame for the 2nd rod
  390. Vec3 tangent2 = Vec3(mVertices[r2.mVertex[1]].mPosition) - Vec3(mVertices[r2.mVertex[0]].mPosition);
  391. if (tangent1.Dot(tangent2) < 0.0f)
  392. {
  393. // Edge is oriented in the opposite direction of the previous edge, flip it
  394. std::swap(r2.mVertex[0], r2.mVertex[1]);
  395. tangent2 = -tangent2;
  396. }
  397. r2.mLength = tangent2.Length();
  398. JPH_ASSERT(r2.mLength > 0.0f, "Rods of zero length are not supported!");
  399. tangent2 /= r2.mLength;
  400. Vec3 t1_cross_t2 = tangent1.Cross(tangent2);
  401. float sin_angle = t1_cross_t2.Length();
  402. Vec3 normal2 = normal1;
  403. if (sin_angle > 0.0f)
  404. {
  405. t1_cross_t2 /= sin_angle;
  406. normal2 = Quat::sRotation(t1_cross_t2, ASin(sin_angle)) * normal2;
  407. }
  408. Vec3 binormal2 = tangent2.Cross(normal2);
  409. r2.mBishop = Mat44(Vec4(normal2, 0), Vec4(binormal2, 0), Vec4(tangent2, 0), Vec4(0, 0, 0, 1)).GetQuaternion().Normalized();
  410. // Add connected rods to the stack if they haven't been calculated yet
  411. for (uint32 r3_idx : connections[r2_idx])
  412. if (mRodStretchShearConstraints[r3_idx].mBishop == Quat::sZero())
  413. stack.push_back({ r2_idx, r3_idx });
  414. }
  415. }
  416. }
  417. // Calculate inverse mass for all rods by taking the minimum inverse mass (aka the heaviest vertex) of both vertices
  418. for (RodStretchShear &r : mRodStretchShearConstraints)
  419. {
  420. JPH_ASSERT(r.mVertex[0] != r.mVertex[1], "A rod stretch shear constraint requires two different vertices");
  421. r.mInvMass = min(mVertices[r.mVertex[0]].mInvMass, mVertices[r.mVertex[1]].mInvMass);
  422. }
  423. // Calculate the initial rotation between the rods
  424. for (RodBendTwist &r : mRodBendTwistConstraints)
  425. r.mOmega0 = (mRodStretchShearConstraints[r.mRod[0]].mBishop.Conjugated() * mRodStretchShearConstraints[r.mRod[1]].mBishop).Normalized();
  426. }
  427. void SoftBodySharedSettings::CalculateLRALengths(float inMaxDistanceMultiplier)
  428. {
  429. for (LRA &l : mLRAConstraints)
  430. {
  431. JPH_ASSERT(l.mVertex[0] != l.mVertex[1], "LRA constraints need to connect 2 different vertices");
  432. l.mMaxDistance = inMaxDistanceMultiplier * (Vec3(mVertices[l.mVertex[1]].mPosition) - Vec3(mVertices[l.mVertex[0]].mPosition)).Length();
  433. JPH_ASSERT(l.mMaxDistance > 0.0f);
  434. }
  435. }
  436. void SoftBodySharedSettings::CalculateBendConstraintConstants()
  437. {
  438. for (DihedralBend &b : mDihedralBendConstraints)
  439. {
  440. JPH_ASSERT(b.mVertex[0] != b.mVertex[1] && b.mVertex[0] != b.mVertex[2] && b.mVertex[0] != b.mVertex[3]
  441. && b.mVertex[1] != b.mVertex[2] && b.mVertex[1] != b.mVertex[3]
  442. && b.mVertex[2] != b.mVertex[3], "Bend constraints need 4 different vertices");
  443. // Get positions
  444. Vec3 x0 = Vec3(mVertices[b.mVertex[0]].mPosition);
  445. Vec3 x1 = Vec3(mVertices[b.mVertex[1]].mPosition);
  446. Vec3 x2 = Vec3(mVertices[b.mVertex[2]].mPosition);
  447. Vec3 x3 = Vec3(mVertices[b.mVertex[3]].mPosition);
  448. /*
  449. x2
  450. e1/ \e3
  451. / \
  452. x0----x1
  453. \ e0 /
  454. e2\ /e4
  455. x3
  456. */
  457. // Calculate edges
  458. Vec3 e0 = x1 - x0;
  459. Vec3 e1 = x2 - x0;
  460. Vec3 e2 = x3 - x0;
  461. // Normals of both triangles
  462. Vec3 n1 = e0.Cross(e1);
  463. Vec3 n2 = e2.Cross(e0);
  464. float denom = sqrt(n1.LengthSq() * n2.LengthSq());
  465. if (denom < 1.0e-12f)
  466. b.mInitialAngle = 0.0f;
  467. else
  468. {
  469. float sign = Sign(n2.Cross(n1).Dot(e0));
  470. b.mInitialAngle = sign * ACosApproximate(n1.Dot(n2) / denom); // Runtime uses the approximation too
  471. }
  472. }
  473. }
  474. void SoftBodySharedSettings::CalculateVolumeConstraintVolumes()
  475. {
  476. for (Volume &v : mVolumeConstraints)
  477. {
  478. JPH_ASSERT(v.mVertex[0] != v.mVertex[1] && v.mVertex[0] != v.mVertex[2] && v.mVertex[0] != v.mVertex[3]
  479. && v.mVertex[1] != v.mVertex[2] && v.mVertex[1] != v.mVertex[3]
  480. && v.mVertex[2] != v.mVertex[3], "Volume constraints need 4 different vertices");
  481. Vec3 x1(mVertices[v.mVertex[0]].mPosition);
  482. Vec3 x2(mVertices[v.mVertex[1]].mPosition);
  483. Vec3 x3(mVertices[v.mVertex[2]].mPosition);
  484. Vec3 x4(mVertices[v.mVertex[3]].mPosition);
  485. Vec3 x1x2 = x2 - x1;
  486. Vec3 x1x3 = x3 - x1;
  487. Vec3 x1x4 = x4 - x1;
  488. v.mSixRestVolume = abs(x1x2.Cross(x1x3).Dot(x1x4));
  489. }
  490. }
  491. void SoftBodySharedSettings::CalculateSkinnedConstraintNormals()
  492. {
  493. // Clear any previous results
  494. mSkinnedConstraintNormals.clear();
  495. // If there are no skinned constraints, we're done
  496. if (mSkinnedConstraints.empty())
  497. return;
  498. // First collect all vertices that are skinned
  499. using VertexIndexSet = UnorderedSet<uint32>;
  500. VertexIndexSet skinned_vertices;
  501. skinned_vertices.reserve(VertexIndexSet::size_type(mSkinnedConstraints.size()));
  502. for (const Skinned &s : mSkinnedConstraints)
  503. skinned_vertices.insert(s.mVertex);
  504. // Now collect all faces that connect only to skinned vertices
  505. using ConnectedFacesMap = UnorderedMap<uint32, VertexIndexSet>;
  506. ConnectedFacesMap connected_faces;
  507. connected_faces.reserve(ConnectedFacesMap::size_type(mVertices.size()));
  508. for (const Face &f : mFaces)
  509. {
  510. // Must connect to only skinned vertices
  511. bool valid = true;
  512. for (uint32 v : f.mVertex)
  513. valid &= skinned_vertices.find(v) != skinned_vertices.end();
  514. if (!valid)
  515. continue;
  516. // Store faces that connect to vertices
  517. for (uint32 v : f.mVertex)
  518. connected_faces[v].insert(uint32(&f - mFaces.data()));
  519. }
  520. // Populate the list of connecting faces per skinned vertex
  521. mSkinnedConstraintNormals.reserve(mFaces.size());
  522. for (Skinned &s : mSkinnedConstraints)
  523. {
  524. uint32 start = uint32(mSkinnedConstraintNormals.size());
  525. JPH_ASSERT((start >> 24) == 0);
  526. ConnectedFacesMap::const_iterator connected_faces_it = connected_faces.find(s.mVertex);
  527. if (connected_faces_it != connected_faces.cend())
  528. {
  529. const VertexIndexSet &faces = connected_faces_it->second;
  530. uint32 num = uint32(faces.size());
  531. JPH_ASSERT(num < 256);
  532. mSkinnedConstraintNormals.insert(mSkinnedConstraintNormals.end(), faces.begin(), faces.end());
  533. QuickSort(mSkinnedConstraintNormals.begin() + start, mSkinnedConstraintNormals.begin() + start + num);
  534. s.mNormalInfo = start + (num << 24);
  535. }
  536. else
  537. s.mNormalInfo = 0;
  538. }
  539. mSkinnedConstraintNormals.shrink_to_fit();
  540. }
  541. void SoftBodySharedSettings::Optimize(OptimizationResults &outResults)
  542. {
  543. // Clear any previous results
  544. mUpdateGroups.clear();
  545. // Create a list of connected vertices
  546. struct Connection
  547. {
  548. uint32 mVertex;
  549. uint32 mCount;
  550. };
  551. Array<Array<Connection>> connectivity;
  552. connectivity.resize(mVertices.size());
  553. auto add_connection = [&connectivity](uint inV1, uint inV2) {
  554. for (int i = 0; i < 2; ++i)
  555. {
  556. bool found = false;
  557. for (Connection &c : connectivity[inV1])
  558. if (c.mVertex == inV2)
  559. {
  560. c.mCount++;
  561. found = true;
  562. break;
  563. }
  564. if (!found)
  565. connectivity[inV1].push_back({ inV2, 1 });
  566. std::swap(inV1, inV2);
  567. }
  568. };
  569. for (const Edge &c : mEdgeConstraints)
  570. add_connection(c.mVertex[0], c.mVertex[1]);
  571. for (const LRA &c : mLRAConstraints)
  572. add_connection(c.mVertex[0], c.mVertex[1]);
  573. for (const RodStretchShear &c : mRodStretchShearConstraints)
  574. add_connection(c.mVertex[0], c.mVertex[1]);
  575. for (const RodBendTwist &c : mRodBendTwistConstraints)
  576. {
  577. add_connection(mRodStretchShearConstraints[c.mRod[0]].mVertex[0], mRodStretchShearConstraints[c.mRod[1]].mVertex[0]);
  578. add_connection(mRodStretchShearConstraints[c.mRod[0]].mVertex[1], mRodStretchShearConstraints[c.mRod[1]].mVertex[0]);
  579. add_connection(mRodStretchShearConstraints[c.mRod[0]].mVertex[0], mRodStretchShearConstraints[c.mRod[1]].mVertex[1]);
  580. add_connection(mRodStretchShearConstraints[c.mRod[0]].mVertex[1], mRodStretchShearConstraints[c.mRod[1]].mVertex[1]);
  581. }
  582. for (const DihedralBend &c : mDihedralBendConstraints)
  583. {
  584. add_connection(c.mVertex[0], c.mVertex[1]);
  585. add_connection(c.mVertex[0], c.mVertex[2]);
  586. add_connection(c.mVertex[0], c.mVertex[3]);
  587. add_connection(c.mVertex[1], c.mVertex[2]);
  588. add_connection(c.mVertex[1], c.mVertex[3]);
  589. add_connection(c.mVertex[2], c.mVertex[3]);
  590. }
  591. for (const Volume &c : mVolumeConstraints)
  592. {
  593. add_connection(c.mVertex[0], c.mVertex[1]);
  594. add_connection(c.mVertex[0], c.mVertex[2]);
  595. add_connection(c.mVertex[0], c.mVertex[3]);
  596. add_connection(c.mVertex[1], c.mVertex[2]);
  597. add_connection(c.mVertex[1], c.mVertex[3]);
  598. add_connection(c.mVertex[2], c.mVertex[3]);
  599. }
  600. // Skinned constraints only update 1 vertex, so we don't need special logic here
  601. // Maps each of the vertices to a group index
  602. Array<int> group_idx;
  603. group_idx.resize(mVertices.size(), -1);
  604. // Which group we are currently filling and its vertices
  605. int current_group_idx = 0;
  606. Array<uint> current_group;
  607. // Start greedy algorithm to group vertices
  608. for (;;)
  609. {
  610. // Find the bounding box of the ungrouped vertices
  611. AABox bounds;
  612. for (uint i = 0; i < (uint)mVertices.size(); ++i)
  613. if (group_idx[i] == -1)
  614. bounds.Encapsulate(Vec3(mVertices[i].mPosition));
  615. // If the bounds are invalid, it means that there were no ungrouped vertices
  616. if (!bounds.IsValid())
  617. break;
  618. // Determine longest and shortest axis
  619. Vec3 bounds_size = bounds.GetSize();
  620. uint max_axis = bounds_size.GetHighestComponentIndex();
  621. uint min_axis = bounds_size.GetLowestComponentIndex();
  622. if (min_axis == max_axis)
  623. min_axis = (min_axis + 1) % 3;
  624. uint mid_axis = 3 - min_axis - max_axis;
  625. // Find the vertex that has the lowest value on the axis with the largest extent
  626. uint current_vertex = UINT_MAX;
  627. Float3 current_vertex_position { FLT_MAX, FLT_MAX, FLT_MAX };
  628. for (uint i = 0; i < (uint)mVertices.size(); ++i)
  629. if (group_idx[i] == -1)
  630. {
  631. const Float3 &vertex_position = mVertices[i].mPosition;
  632. float max_axis_value = vertex_position[max_axis];
  633. float mid_axis_value = vertex_position[mid_axis];
  634. float min_axis_value = vertex_position[min_axis];
  635. if (max_axis_value < current_vertex_position[max_axis]
  636. || (max_axis_value == current_vertex_position[max_axis]
  637. && (mid_axis_value < current_vertex_position[mid_axis]
  638. || (mid_axis_value == current_vertex_position[mid_axis]
  639. && min_axis_value < current_vertex_position[min_axis]))))
  640. {
  641. current_vertex_position = mVertices[i].mPosition;
  642. current_vertex = i;
  643. }
  644. }
  645. if (current_vertex == UINT_MAX)
  646. break;
  647. // Initialize the current group with 1 vertex
  648. current_group.push_back(current_vertex);
  649. group_idx[current_vertex] = current_group_idx;
  650. // Fill up the group
  651. for (;;)
  652. {
  653. // Find the vertex that is most connected to the current group
  654. uint best_vertex = UINT_MAX;
  655. uint best_num_connections = 0;
  656. float best_dist_sq = FLT_MAX;
  657. for (uint i = 0; i < (uint)current_group.size(); ++i) // For all vertices in the current group
  658. for (const Connection &c : connectivity[current_group[i]]) // For all connections to other vertices
  659. {
  660. uint v = c.mVertex;
  661. if (group_idx[v] == -1) // Ungrouped vertices only
  662. {
  663. // Count the number of connections to this group
  664. uint num_connections = 0;
  665. for (const Connection &v2 : connectivity[v])
  666. if (group_idx[v2.mVertex] == current_group_idx)
  667. num_connections += v2.mCount;
  668. // Calculate distance to group centroid
  669. float dist_sq = (Vec3(mVertices[v].mPosition) - Vec3(mVertices[current_group.front()].mPosition)).LengthSq();
  670. if (best_vertex == UINT_MAX
  671. || num_connections > best_num_connections
  672. || (num_connections == best_num_connections && dist_sq < best_dist_sq))
  673. {
  674. best_vertex = v;
  675. best_num_connections = num_connections;
  676. best_dist_sq = dist_sq;
  677. }
  678. }
  679. }
  680. // Add the best vertex to the current group
  681. if (best_vertex != UINT_MAX)
  682. {
  683. current_group.push_back(best_vertex);
  684. group_idx[best_vertex] = current_group_idx;
  685. }
  686. // Create a new group?
  687. if (current_group.size() >= SoftBodyUpdateContext::cVertexConstraintBatch // If full, yes
  688. || (current_group.size() > SoftBodyUpdateContext::cVertexConstraintBatch / 2 && best_vertex == UINT_MAX)) // If half full and we found no connected vertex, yes
  689. {
  690. current_group.clear();
  691. current_group_idx++;
  692. break;
  693. }
  694. // If we didn't find a connected vertex, we need to find a new starting vertex
  695. if (best_vertex == UINT_MAX)
  696. break;
  697. }
  698. }
  699. // If the last group is more than half full, we'll keep it as a separate group, otherwise we merge it with the 'non parallel' group
  700. if (current_group.size() > SoftBodyUpdateContext::cVertexConstraintBatch / 2)
  701. ++current_group_idx;
  702. // We no longer need the current group array, free the memory
  703. current_group.clear();
  704. current_group.shrink_to_fit();
  705. // We're done with the connectivity list, free the memory
  706. connectivity.clear();
  707. connectivity.shrink_to_fit();
  708. // Assign the constraints to their groups
  709. struct Group
  710. {
  711. uint GetSize() const
  712. {
  713. return (uint)mEdgeConstraints.size() + (uint)mLRAConstraints.size() + (uint)mRodStretchShearConstraints.size() + (uint)mRodBendTwistConstraints.size() + (uint)mDihedralBendConstraints.size() + (uint)mVolumeConstraints.size() + (uint)mSkinnedConstraints.size();
  714. }
  715. Array<uint> mEdgeConstraints;
  716. Array<uint> mLRAConstraints;
  717. Array<uint> mRodStretchShearConstraints;
  718. Array<uint> mRodBendTwistConstraints;
  719. Array<uint> mDihedralBendConstraints;
  720. Array<uint> mVolumeConstraints;
  721. Array<uint> mSkinnedConstraints;
  722. };
  723. Array<Group> groups;
  724. groups.resize(current_group_idx + 1); // + non parallel group
  725. for (const Edge &e : mEdgeConstraints)
  726. {
  727. int g1 = group_idx[e.mVertex[0]];
  728. int g2 = group_idx[e.mVertex[1]];
  729. JPH_ASSERT(g1 >= 0 && g2 >= 0);
  730. if (g1 == g2) // In the same group
  731. groups[g1].mEdgeConstraints.push_back(uint(&e - mEdgeConstraints.data()));
  732. else // In different groups -> parallel group
  733. groups.back().mEdgeConstraints.push_back(uint(&e - mEdgeConstraints.data()));
  734. }
  735. for (const LRA &l : mLRAConstraints)
  736. {
  737. int g1 = group_idx[l.mVertex[0]];
  738. int g2 = group_idx[l.mVertex[1]];
  739. JPH_ASSERT(g1 >= 0 && g2 >= 0);
  740. if (g1 == g2) // In the same group
  741. groups[g1].mLRAConstraints.push_back(uint(&l - mLRAConstraints.data()));
  742. else // In different groups -> parallel group
  743. groups.back().mLRAConstraints.push_back(uint(&l - mLRAConstraints.data()));
  744. }
  745. for (const RodStretchShear &r : mRodStretchShearConstraints)
  746. {
  747. int g1 = group_idx[r.mVertex[0]];
  748. int g2 = group_idx[r.mVertex[1]];
  749. JPH_ASSERT(g1 >= 0 && g2 >= 0);
  750. if (g1 == g2) // In the same group
  751. groups[g1].mRodStretchShearConstraints.push_back(uint(&r - mRodStretchShearConstraints.data()));
  752. else // In different groups -> parallel group
  753. groups.back().mRodStretchShearConstraints.push_back(uint(&r - mRodStretchShearConstraints.data()));
  754. }
  755. for (const RodBendTwist &r : mRodBendTwistConstraints)
  756. {
  757. int g1 = group_idx[mRodStretchShearConstraints[r.mRod[0]].mVertex[0]];
  758. int g2 = group_idx[mRodStretchShearConstraints[r.mRod[0]].mVertex[1]];
  759. int g3 = group_idx[mRodStretchShearConstraints[r.mRod[1]].mVertex[0]];
  760. int g4 = group_idx[mRodStretchShearConstraints[r.mRod[1]].mVertex[1]];
  761. JPH_ASSERT(g1 >= 0 && g2 >= 0 && g3 >= 0 && g4 >= 0);
  762. if (g1 == g2 && g1 == g3 && g1 == g4) // In the same group
  763. groups[g1].mRodBendTwistConstraints.push_back(uint(&r - mRodBendTwistConstraints.data()));
  764. else // In different groups -> parallel group
  765. groups.back().mRodBendTwistConstraints.push_back(uint(&r - mRodBendTwistConstraints.data()));
  766. }
  767. for (const DihedralBend &d : mDihedralBendConstraints)
  768. {
  769. int g1 = group_idx[d.mVertex[0]];
  770. int g2 = group_idx[d.mVertex[1]];
  771. int g3 = group_idx[d.mVertex[2]];
  772. int g4 = group_idx[d.mVertex[3]];
  773. JPH_ASSERT(g1 >= 0 && g2 >= 0 && g3 >= 0 && g4 >= 0);
  774. if (g1 == g2 && g1 == g3 && g1 == g4) // In the same group
  775. groups[g1].mDihedralBendConstraints.push_back(uint(&d - mDihedralBendConstraints.data()));
  776. else // In different groups -> parallel group
  777. groups.back().mDihedralBendConstraints.push_back(uint(&d - mDihedralBendConstraints.data()));
  778. }
  779. for (const Volume &v : mVolumeConstraints)
  780. {
  781. int g1 = group_idx[v.mVertex[0]];
  782. int g2 = group_idx[v.mVertex[1]];
  783. int g3 = group_idx[v.mVertex[2]];
  784. int g4 = group_idx[v.mVertex[3]];
  785. JPH_ASSERT(g1 >= 0 && g2 >= 0 && g3 >= 0 && g4 >= 0);
  786. if (g1 == g2 && g1 == g3 && g1 == g4) // In the same group
  787. groups[g1].mVolumeConstraints.push_back(uint(&v - mVolumeConstraints.data()));
  788. else // In different groups -> parallel group
  789. groups.back().mVolumeConstraints.push_back(uint(&v - mVolumeConstraints.data()));
  790. }
  791. for (const Skinned &s : mSkinnedConstraints)
  792. {
  793. int g1 = group_idx[s.mVertex];
  794. JPH_ASSERT(g1 >= 0);
  795. groups[g1].mSkinnedConstraints.push_back(uint(&s - mSkinnedConstraints.data()));
  796. }
  797. // Sort the parallel groups from big to small (this means the big groups will be scheduled first and have more time to complete)
  798. QuickSort(groups.begin(), groups.end() - 1, [](const Group &inLHS, const Group &inRHS) { return inLHS.GetSize() > inRHS.GetSize(); });
  799. // Make sure we know the closest kinematic vertex so we can sort
  800. CalculateClosestKinematic();
  801. // Sort within each group
  802. for (Group &group : groups)
  803. {
  804. // Sort the edge constraints
  805. QuickSort(group.mEdgeConstraints.begin(), group.mEdgeConstraints.end(), [this](uint inLHS, uint inRHS)
  806. {
  807. const Edge &e1 = mEdgeConstraints[inLHS];
  808. const Edge &e2 = mEdgeConstraints[inRHS];
  809. // First sort so that the edge with the smallest distance to a kinematic vertex comes first
  810. float d1 = min(mClosestKinematic[e1.mVertex[0]].mDistance, mClosestKinematic[e1.mVertex[1]].mDistance);
  811. float d2 = min(mClosestKinematic[e2.mVertex[0]].mDistance, mClosestKinematic[e2.mVertex[1]].mDistance);
  812. if (d1 != d2)
  813. return d1 < d2;
  814. // Order the edges so that the ones with the smallest index go first (hoping to get better cache locality when we process the edges).
  815. // Note we could also re-order the vertices but that would be much more of a burden to the end user
  816. uint32 m1 = e1.GetMinVertexIndex();
  817. uint32 m2 = e2.GetMinVertexIndex();
  818. if (m1 != m2)
  819. return m1 < m2;
  820. return inLHS < inRHS;
  821. });
  822. // Sort the LRA constraints
  823. QuickSort(group.mLRAConstraints.begin(), group.mLRAConstraints.end(), [this](uint inLHS, uint inRHS)
  824. {
  825. const LRA &l1 = mLRAConstraints[inLHS];
  826. const LRA &l2 = mLRAConstraints[inRHS];
  827. // First sort so that the longest constraint comes first (meaning the shortest constraint has the most influence on the end result)
  828. // Most of the time there will be a single LRA constraint per vertex and since the LRA constraint only modifies a single vertex,
  829. // updating one constraint will not violate another constraint.
  830. if (l1.mMaxDistance != l2.mMaxDistance)
  831. return l1.mMaxDistance > l2.mMaxDistance;
  832. // Order constraints so that the ones with the smallest index go first
  833. uint32 m1 = l1.GetMinVertexIndex();
  834. uint32 m2 = l2.GetMinVertexIndex();
  835. if (m1 != m2)
  836. return m1 < m2;
  837. return inLHS < inRHS;
  838. });
  839. // Sort the rod stretch shear constraints
  840. QuickSort(group.mRodStretchShearConstraints.begin(), group.mRodStretchShearConstraints.end(), [this](uint inLHS, uint inRHS)
  841. {
  842. const RodStretchShear &r1 = mRodStretchShearConstraints[inLHS];
  843. const RodStretchShear &r2 = mRodStretchShearConstraints[inRHS];
  844. // First sort so that the rod with the smallest distance to a kinematic vertex comes first
  845. float d1 = min(mClosestKinematic[r1.mVertex[0]].mDistance, mClosestKinematic[r1.mVertex[1]].mDistance);
  846. float d2 = min(mClosestKinematic[r2.mVertex[0]].mDistance, mClosestKinematic[r2.mVertex[1]].mDistance);
  847. if (d1 != d2)
  848. return d1 < d2;
  849. // Order the rods so that the ones with the smallest index go first (hoping to get better cache locality when we process the rods).
  850. uint32 m1 = r1.GetMinVertexIndex();
  851. uint32 m2 = r2.GetMinVertexIndex();
  852. if (m1 != m2)
  853. return m1 < m2;
  854. return inLHS < inRHS;
  855. });
  856. // Sort the rod bend twist constraints
  857. QuickSort(group.mRodBendTwistConstraints.begin(), group.mRodBendTwistConstraints.end(), [this](uint inLHS, uint inRHS)
  858. {
  859. const RodBendTwist &b1 = mRodBendTwistConstraints[inLHS];
  860. const RodStretchShear &b1_r1 = mRodStretchShearConstraints[b1.mRod[0]];
  861. const RodStretchShear &b1_r2 = mRodStretchShearConstraints[b1.mRod[1]];
  862. const RodBendTwist &b2 = mRodBendTwistConstraints[inRHS];
  863. const RodStretchShear &b2_r1 = mRodStretchShearConstraints[b2.mRod[0]];
  864. const RodStretchShear &b2_r2 = mRodStretchShearConstraints[b2.mRod[1]];
  865. // First sort so that the rod with the smallest distance to a kinematic vertex comes first
  866. float d1 = min(
  867. min(mClosestKinematic[b1_r1.mVertex[0]].mDistance, mClosestKinematic[b1_r1.mVertex[1]].mDistance),
  868. min(mClosestKinematic[b1_r2.mVertex[0]].mDistance, mClosestKinematic[b1_r2.mVertex[1]].mDistance));
  869. float d2 = min(
  870. min(mClosestKinematic[b2_r1.mVertex[0]].mDistance, mClosestKinematic[b2_r1.mVertex[1]].mDistance),
  871. min(mClosestKinematic[b2_r2.mVertex[0]].mDistance, mClosestKinematic[b2_r2.mVertex[1]].mDistance));
  872. if (d1 != d2)
  873. return d1 < d2;
  874. // Order the rods so that the ones with the smallest index go first
  875. uint32 m1 = min(b1_r1.GetMinVertexIndex(), b1_r2.GetMinVertexIndex());
  876. uint32 m2 = min(b2_r1.GetMinVertexIndex(), b2_r2.GetMinVertexIndex());
  877. if (m1 != m2)
  878. return m1 < m2;
  879. return inLHS < inRHS;
  880. });
  881. // Bilateral interleaving, see figure 4 of "Position and Orientation Based Cosserat Rods" - Kugelstadt and Schoemer - SIGGRAPH 2016
  882. // Keeping the twist constraints sorted often results in an unstable simulation
  883. for (Array<uint>::size_type i = 1, s = group.mRodBendTwistConstraints.size(), s2 = s >> 1; i < s2; i += 2)
  884. std::swap(group.mRodBendTwistConstraints[i], group.mRodBendTwistConstraints[s - 1 - i]);
  885. // Sort the dihedral bend constraints
  886. QuickSort(group.mDihedralBendConstraints.begin(), group.mDihedralBendConstraints.end(), [this](uint inLHS, uint inRHS)
  887. {
  888. const DihedralBend &b1 = mDihedralBendConstraints[inLHS];
  889. const DihedralBend &b2 = mDihedralBendConstraints[inRHS];
  890. // First sort so that the constraint with the smallest distance to a kinematic vertex comes first
  891. float d1 = min(
  892. min(mClosestKinematic[b1.mVertex[0]].mDistance, mClosestKinematic[b1.mVertex[1]].mDistance),
  893. min(mClosestKinematic[b1.mVertex[2]].mDistance, mClosestKinematic[b1.mVertex[3]].mDistance));
  894. float d2 = min(
  895. min(mClosestKinematic[b2.mVertex[0]].mDistance, mClosestKinematic[b2.mVertex[1]].mDistance),
  896. min(mClosestKinematic[b2.mVertex[2]].mDistance, mClosestKinematic[b2.mVertex[3]].mDistance));
  897. if (d1 != d2)
  898. return d1 < d2;
  899. // Order constraints so that the ones with the smallest index go first
  900. uint32 m1 = b1.GetMinVertexIndex();
  901. uint32 m2 = b2.GetMinVertexIndex();
  902. if (m1 != m2)
  903. return m1 < m2;
  904. return inLHS < inRHS;
  905. });
  906. // Sort the volume constraints
  907. QuickSort(group.mVolumeConstraints.begin(), group.mVolumeConstraints.end(), [this](uint inLHS, uint inRHS)
  908. {
  909. const Volume &v1 = mVolumeConstraints[inLHS];
  910. const Volume &v2 = mVolumeConstraints[inRHS];
  911. // First sort so that the constraint with the smallest distance to a kinematic vertex comes first
  912. float d1 = min(
  913. min(mClosestKinematic[v1.mVertex[0]].mDistance, mClosestKinematic[v1.mVertex[1]].mDistance),
  914. min(mClosestKinematic[v1.mVertex[2]].mDistance, mClosestKinematic[v1.mVertex[3]].mDistance));
  915. float d2 = min(
  916. min(mClosestKinematic[v2.mVertex[0]].mDistance, mClosestKinematic[v2.mVertex[1]].mDistance),
  917. min(mClosestKinematic[v2.mVertex[2]].mDistance, mClosestKinematic[v2.mVertex[3]].mDistance));
  918. if (d1 != d2)
  919. return d1 < d2;
  920. // Order constraints so that the ones with the smallest index go first
  921. uint32 m1 = v1.GetMinVertexIndex();
  922. uint32 m2 = v2.GetMinVertexIndex();
  923. if (m1 != m2)
  924. return m1 < m2;
  925. return inLHS < inRHS;
  926. });
  927. // Sort the skinned constraints
  928. QuickSort(group.mSkinnedConstraints.begin(), group.mSkinnedConstraints.end(), [this](uint inLHS, uint inRHS)
  929. {
  930. const Skinned &s1 = mSkinnedConstraints[inLHS];
  931. const Skinned &s2 = mSkinnedConstraints[inRHS];
  932. // Order the skinned constraints so that the ones with the smallest index go first (hoping to get better cache locality when we process the edges).
  933. if (s1.mVertex != s2.mVertex)
  934. return s1.mVertex < s2.mVertex;
  935. return inLHS < inRHS;
  936. });
  937. }
  938. // Temporary store constraints as we reorder them
  939. Array<Edge> temp_edges;
  940. temp_edges.swap(mEdgeConstraints);
  941. mEdgeConstraints.reserve(temp_edges.size());
  942. outResults.mEdgeRemap.resize(temp_edges.size(), ~uint(0));
  943. Array<LRA> temp_lra;
  944. temp_lra.swap(mLRAConstraints);
  945. mLRAConstraints.reserve(temp_lra.size());
  946. outResults.mLRARemap.resize(temp_lra.size(), ~uint(0));
  947. Array<RodStretchShear> temp_rod_stretch_shear;
  948. temp_rod_stretch_shear.swap(mRodStretchShearConstraints);
  949. mRodStretchShearConstraints.reserve(temp_rod_stretch_shear.size());
  950. outResults.mRodStretchShearConstraintRemap.resize(temp_rod_stretch_shear.size(), ~uint(0));
  951. Array<RodBendTwist> temp_rod_bend_twist;
  952. temp_rod_bend_twist.swap(mRodBendTwistConstraints);
  953. mRodBendTwistConstraints.reserve(temp_rod_bend_twist.size());
  954. outResults.mRodBendTwistConstraintRemap.resize(temp_rod_bend_twist.size(), ~uint(0));
  955. Array<DihedralBend> temp_dihedral_bend;
  956. temp_dihedral_bend.swap(mDihedralBendConstraints);
  957. mDihedralBendConstraints.reserve(temp_dihedral_bend.size());
  958. outResults.mDihedralBendRemap.resize(temp_dihedral_bend.size(), ~uint(0));
  959. Array<Volume> temp_volume;
  960. temp_volume.swap(mVolumeConstraints);
  961. mVolumeConstraints.reserve(temp_volume.size());
  962. outResults.mVolumeRemap.resize(temp_volume.size(), ~uint(0));
  963. Array<Skinned> temp_skinned;
  964. temp_skinned.swap(mSkinnedConstraints);
  965. mSkinnedConstraints.reserve(temp_skinned.size());
  966. outResults.mSkinnedRemap.resize(temp_skinned.size(), ~uint(0));
  967. // Finalize update groups
  968. for (const Group &group : groups)
  969. {
  970. // Reorder edge constraints for this group
  971. for (uint idx : group.mEdgeConstraints)
  972. {
  973. outResults.mEdgeRemap[idx] = (uint)mEdgeConstraints.size();
  974. mEdgeConstraints.push_back(temp_edges[idx]);
  975. }
  976. // Reorder LRA constraints for this group
  977. for (uint idx : group.mLRAConstraints)
  978. {
  979. outResults.mLRARemap[idx] = (uint)mLRAConstraints.size();
  980. mLRAConstraints.push_back(temp_lra[idx]);
  981. }
  982. // Reorder rod stretch shear constraints for this group
  983. for (uint idx : group.mRodStretchShearConstraints)
  984. {
  985. outResults.mRodStretchShearConstraintRemap[idx] = (uint)mRodStretchShearConstraints.size();
  986. mRodStretchShearConstraints.push_back(temp_rod_stretch_shear[idx]);
  987. }
  988. // Reorder rod bend twist constraints for this group
  989. for (uint idx : group.mRodBendTwistConstraints)
  990. {
  991. outResults.mRodBendTwistConstraintRemap[idx] = (uint)mRodBendTwistConstraints.size();
  992. mRodBendTwistConstraints.push_back(temp_rod_bend_twist[idx]);
  993. }
  994. // Reorder dihedral bend constraints for this group
  995. for (uint idx : group.mDihedralBendConstraints)
  996. {
  997. outResults.mDihedralBendRemap[idx] = (uint)mDihedralBendConstraints.size();
  998. mDihedralBendConstraints.push_back(temp_dihedral_bend[idx]);
  999. }
  1000. // Reorder volume constraints for this group
  1001. for (uint idx : group.mVolumeConstraints)
  1002. {
  1003. outResults.mVolumeRemap[idx] = (uint)mVolumeConstraints.size();
  1004. mVolumeConstraints.push_back(temp_volume[idx]);
  1005. }
  1006. // Reorder skinned constraints for this group
  1007. for (uint idx : group.mSkinnedConstraints)
  1008. {
  1009. outResults.mSkinnedRemap[idx] = (uint)mSkinnedConstraints.size();
  1010. mSkinnedConstraints.push_back(temp_skinned[idx]);
  1011. }
  1012. // Store end indices
  1013. mUpdateGroups.push_back({ (uint)mEdgeConstraints.size(), (uint)mLRAConstraints.size(), (uint)mRodStretchShearConstraints.size(), (uint)mRodBendTwistConstraints.size(), (uint)mDihedralBendConstraints.size(), (uint)mVolumeConstraints.size(), (uint)mSkinnedConstraints.size() });
  1014. }
  1015. // Remap bend twist indices because mRodStretchShearConstraints has been reordered
  1016. for (RodBendTwist &r : mRodBendTwistConstraints)
  1017. for (int i = 0; i < 2; ++i)
  1018. r.mRod[i] = outResults.mRodStretchShearConstraintRemap[r.mRod[i]];
  1019. // Free closest kinematic buffer
  1020. mClosestKinematic.clear();
  1021. mClosestKinematic.shrink_to_fit();
  1022. }
  1023. Ref<SoftBodySharedSettings> SoftBodySharedSettings::Clone() const
  1024. {
  1025. Ref<SoftBodySharedSettings> clone = new SoftBodySharedSettings;
  1026. clone->mVertices = mVertices;
  1027. clone->mFaces = mFaces;
  1028. clone->mEdgeConstraints = mEdgeConstraints;
  1029. clone->mDihedralBendConstraints = mDihedralBendConstraints;
  1030. clone->mVolumeConstraints = mVolumeConstraints;
  1031. clone->mSkinnedConstraints = mSkinnedConstraints;
  1032. clone->mSkinnedConstraintNormals = mSkinnedConstraintNormals;
  1033. clone->mInvBindMatrices = mInvBindMatrices;
  1034. clone->mLRAConstraints = mLRAConstraints;
  1035. clone->mRodStretchShearConstraints = mRodStretchShearConstraints;
  1036. clone->mRodBendTwistConstraints = mRodBendTwistConstraints;
  1037. clone->mMaterials = mMaterials;
  1038. clone->mVertexRadius = mVertexRadius;
  1039. clone->mUpdateGroups = mUpdateGroups;
  1040. return clone;
  1041. }
  1042. void SoftBodySharedSettings::SaveBinaryState(StreamOut &inStream) const
  1043. {
  1044. inStream.Write(mVertices);
  1045. inStream.Write(mFaces);
  1046. inStream.Write(mEdgeConstraints);
  1047. inStream.Write(mDihedralBendConstraints);
  1048. inStream.Write(mVolumeConstraints);
  1049. inStream.Write(mSkinnedConstraints);
  1050. inStream.Write(mSkinnedConstraintNormals);
  1051. inStream.Write(mLRAConstraints);
  1052. inStream.Write(mVertexRadius);
  1053. inStream.Write(mUpdateGroups);
  1054. // Can't write mRodStretchShearConstraints directly because the class contains padding
  1055. inStream.Write(mRodStretchShearConstraints, [](const RodStretchShear &inElement, StreamOut &inS) {
  1056. inS.Write(inElement.mVertex);
  1057. inS.Write(inElement.mLength);
  1058. inS.Write(inElement.mInvMass);
  1059. inS.Write(inElement.mCompliance);
  1060. inS.Write(inElement.mBishop);
  1061. });
  1062. // Can't write mRodBendTwistConstraints directly because the class contains padding
  1063. inStream.Write(mRodBendTwistConstraints, [](const RodBendTwist &inElement, StreamOut &inS) {
  1064. inS.Write(inElement.mRod);
  1065. inS.Write(inElement.mCompliance);
  1066. inS.Write(inElement.mOmega0);
  1067. });
  1068. // Can't write mInvBindMatrices directly because the class contains padding
  1069. inStream.Write(mInvBindMatrices, [](const InvBind &inElement, StreamOut &inS) {
  1070. inS.Write(inElement.mJointIndex);
  1071. inS.Write(inElement.mInvBind);
  1072. });
  1073. }
  1074. void SoftBodySharedSettings::RestoreBinaryState(StreamIn &inStream)
  1075. {
  1076. inStream.Read(mVertices);
  1077. inStream.Read(mFaces);
  1078. inStream.Read(mEdgeConstraints);
  1079. inStream.Read(mDihedralBendConstraints);
  1080. inStream.Read(mVolumeConstraints);
  1081. inStream.Read(mSkinnedConstraints);
  1082. inStream.Read(mSkinnedConstraintNormals);
  1083. inStream.Read(mLRAConstraints);
  1084. inStream.Read(mVertexRadius);
  1085. inStream.Read(mUpdateGroups);
  1086. inStream.Read(mRodStretchShearConstraints, [](StreamIn &inS, RodStretchShear &outElement) {
  1087. inS.Read(outElement.mVertex);
  1088. inS.Read(outElement.mLength);
  1089. inS.Read(outElement.mInvMass);
  1090. inS.Read(outElement.mCompliance);
  1091. inS.Read(outElement.mBishop);
  1092. });
  1093. inStream.Read(mRodBendTwistConstraints, [](StreamIn &inS, RodBendTwist &outElement) {
  1094. inS.Read(outElement.mRod);
  1095. inS.Read(outElement.mCompliance);
  1096. inS.Read(outElement.mOmega0);
  1097. });
  1098. inStream.Read(mInvBindMatrices, [](StreamIn &inS, InvBind &outElement) {
  1099. inS.Read(outElement.mJointIndex);
  1100. inS.Read(outElement.mInvBind);
  1101. });
  1102. }
  1103. void SoftBodySharedSettings::SaveWithMaterials(StreamOut &inStream, SharedSettingsToIDMap &ioSettingsMap, MaterialToIDMap &ioMaterialMap) const
  1104. {
  1105. SharedSettingsToIDMap::const_iterator settings_iter = ioSettingsMap.find(this);
  1106. if (settings_iter == ioSettingsMap.end())
  1107. {
  1108. // Write settings ID
  1109. uint32 settings_id = ioSettingsMap.size();
  1110. ioSettingsMap[this] = settings_id;
  1111. inStream.Write(settings_id);
  1112. // Write the settings
  1113. SaveBinaryState(inStream);
  1114. // Write materials
  1115. StreamUtils::SaveObjectArray(inStream, mMaterials, &ioMaterialMap);
  1116. }
  1117. else
  1118. {
  1119. // Known settings, just write the ID
  1120. inStream.Write(settings_iter->second);
  1121. }
  1122. }
  1123. SoftBodySharedSettings::SettingsResult SoftBodySharedSettings::sRestoreWithMaterials(StreamIn &inStream, IDToSharedSettingsMap &ioSettingsMap, IDToMaterialMap &ioMaterialMap)
  1124. {
  1125. SettingsResult result;
  1126. // Read settings id
  1127. uint32 settings_id;
  1128. inStream.Read(settings_id);
  1129. if (inStream.IsEOF() || inStream.IsFailed())
  1130. {
  1131. result.SetError("Failed to read settings id");
  1132. return result;
  1133. }
  1134. // Check nullptr settings
  1135. if (settings_id == ~uint32(0))
  1136. {
  1137. result.Set(nullptr);
  1138. return result;
  1139. }
  1140. // Check if we already read this settings
  1141. if (settings_id < ioSettingsMap.size())
  1142. {
  1143. result.Set(ioSettingsMap[settings_id]);
  1144. return result;
  1145. }
  1146. // Create new object
  1147. Ref<SoftBodySharedSettings> settings = new SoftBodySharedSettings;
  1148. // Read state
  1149. settings->RestoreBinaryState(inStream);
  1150. // Read materials
  1151. Result mlresult = StreamUtils::RestoreObjectArray<PhysicsMaterialList>(inStream, ioMaterialMap);
  1152. if (mlresult.HasError())
  1153. {
  1154. result.SetError(mlresult.GetError());
  1155. return result;
  1156. }
  1157. settings->mMaterials = mlresult.Get();
  1158. // Add the settings to the map
  1159. ioSettingsMap.push_back(settings);
  1160. result.Set(settings);
  1161. return result;
  1162. }
  1163. Ref<SoftBodySharedSettings> SoftBodySharedSettings::sCreateCube(uint inGridSize, float inGridSpacing)
  1164. {
  1165. const Vec3 cOffset = Vec3::sReplicate(-0.5f * inGridSpacing * (inGridSize - 1));
  1166. // Create settings
  1167. SoftBodySharedSettings *settings = new SoftBodySharedSettings;
  1168. for (uint z = 0; z < inGridSize; ++z)
  1169. for (uint y = 0; y < inGridSize; ++y)
  1170. for (uint x = 0; x < inGridSize; ++x)
  1171. {
  1172. SoftBodySharedSettings::Vertex v;
  1173. (cOffset + Vec3::sReplicate(inGridSpacing) * Vec3(float(x), float(y), float(z))).StoreFloat3(&v.mPosition);
  1174. settings->mVertices.push_back(v);
  1175. }
  1176. // Function to get the vertex index of a point on the cube
  1177. auto vertex_index = [inGridSize](uint inX, uint inY, uint inZ)
  1178. {
  1179. return inX + inY * inGridSize + inZ * inGridSize * inGridSize;
  1180. };
  1181. // Create edges
  1182. for (uint z = 0; z < inGridSize; ++z)
  1183. for (uint y = 0; y < inGridSize; ++y)
  1184. for (uint x = 0; x < inGridSize; ++x)
  1185. {
  1186. SoftBodySharedSettings::Edge e;
  1187. e.mVertex[0] = vertex_index(x, y, z);
  1188. if (x < inGridSize - 1)
  1189. {
  1190. e.mVertex[1] = vertex_index(x + 1, y, z);
  1191. settings->mEdgeConstraints.push_back(e);
  1192. }
  1193. if (y < inGridSize - 1)
  1194. {
  1195. e.mVertex[1] = vertex_index(x, y + 1, z);
  1196. settings->mEdgeConstraints.push_back(e);
  1197. }
  1198. if (z < inGridSize - 1)
  1199. {
  1200. e.mVertex[1] = vertex_index(x, y, z + 1);
  1201. settings->mEdgeConstraints.push_back(e);
  1202. }
  1203. }
  1204. settings->CalculateEdgeLengths();
  1205. // Tetrahedrons to fill a cube
  1206. const int tetra_indices[6][4][3] = {
  1207. { {0, 0, 0}, {0, 1, 1}, {0, 0, 1}, {1, 1, 1} },
  1208. { {0, 0, 0}, {0, 1, 0}, {0, 1, 1}, {1, 1, 1} },
  1209. { {0, 0, 0}, {0, 0, 1}, {1, 0, 1}, {1, 1, 1} },
  1210. { {0, 0, 0}, {1, 0, 1}, {1, 0, 0}, {1, 1, 1} },
  1211. { {0, 0, 0}, {1, 1, 0}, {0, 1, 0}, {1, 1, 1} },
  1212. { {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {1, 1, 1} }
  1213. };
  1214. // Create volume constraints
  1215. for (uint z = 0; z < inGridSize - 1; ++z)
  1216. for (uint y = 0; y < inGridSize - 1; ++y)
  1217. for (uint x = 0; x < inGridSize - 1; ++x)
  1218. for (uint t = 0; t < 6; ++t)
  1219. {
  1220. SoftBodySharedSettings::Volume v;
  1221. for (uint i = 0; i < 4; ++i)
  1222. v.mVertex[i] = vertex_index(x + tetra_indices[t][i][0], y + tetra_indices[t][i][1], z + tetra_indices[t][i][2]);
  1223. settings->mVolumeConstraints.push_back(v);
  1224. }
  1225. settings->CalculateVolumeConstraintVolumes();
  1226. // Create faces
  1227. for (uint y = 0; y < inGridSize - 1; ++y)
  1228. for (uint x = 0; x < inGridSize - 1; ++x)
  1229. {
  1230. SoftBodySharedSettings::Face f;
  1231. // Face 1
  1232. f.mVertex[0] = vertex_index(x, y, 0);
  1233. f.mVertex[1] = vertex_index(x, y + 1, 0);
  1234. f.mVertex[2] = vertex_index(x + 1, y + 1, 0);
  1235. settings->AddFace(f);
  1236. f.mVertex[1] = vertex_index(x + 1, y + 1, 0);
  1237. f.mVertex[2] = vertex_index(x + 1, y, 0);
  1238. settings->AddFace(f);
  1239. // Face 2
  1240. f.mVertex[0] = vertex_index(x, y, inGridSize - 1);
  1241. f.mVertex[1] = vertex_index(x + 1, y + 1, inGridSize - 1);
  1242. f.mVertex[2] = vertex_index(x, y + 1, inGridSize - 1);
  1243. settings->AddFace(f);
  1244. f.mVertex[1] = vertex_index(x + 1, y, inGridSize - 1);
  1245. f.mVertex[2] = vertex_index(x + 1, y + 1, inGridSize - 1);
  1246. settings->AddFace(f);
  1247. // Face 3
  1248. f.mVertex[0] = vertex_index(x, 0, y);
  1249. f.mVertex[1] = vertex_index(x + 1, 0, y + 1);
  1250. f.mVertex[2] = vertex_index(x, 0, y + 1);
  1251. settings->AddFace(f);
  1252. f.mVertex[1] = vertex_index(x + 1, 0, y);
  1253. f.mVertex[2] = vertex_index(x + 1, 0, y + 1);
  1254. settings->AddFace(f);
  1255. // Face 4
  1256. f.mVertex[0] = vertex_index(x, inGridSize - 1, y);
  1257. f.mVertex[1] = vertex_index(x, inGridSize - 1, y + 1);
  1258. f.mVertex[2] = vertex_index(x + 1, inGridSize - 1, y + 1);
  1259. settings->AddFace(f);
  1260. f.mVertex[1] = vertex_index(x + 1, inGridSize - 1, y + 1);
  1261. f.mVertex[2] = vertex_index(x + 1, inGridSize - 1, y);
  1262. settings->AddFace(f);
  1263. // Face 5
  1264. f.mVertex[0] = vertex_index(0, x, y);
  1265. f.mVertex[1] = vertex_index(0, x, y + 1);
  1266. f.mVertex[2] = vertex_index(0, x + 1, y + 1);
  1267. settings->AddFace(f);
  1268. f.mVertex[1] = vertex_index(0, x + 1, y + 1);
  1269. f.mVertex[2] = vertex_index(0, x + 1, y);
  1270. settings->AddFace(f);
  1271. // Face 6
  1272. f.mVertex[0] = vertex_index(inGridSize - 1, x, y);
  1273. f.mVertex[1] = vertex_index(inGridSize - 1, x + 1, y + 1);
  1274. f.mVertex[2] = vertex_index(inGridSize - 1, x, y + 1);
  1275. settings->AddFace(f);
  1276. f.mVertex[1] = vertex_index(inGridSize - 1, x + 1, y);
  1277. f.mVertex[2] = vertex_index(inGridSize - 1, x + 1, y + 1);
  1278. settings->AddFace(f);
  1279. }
  1280. // Optimize the settings
  1281. settings->Optimize();
  1282. return settings;
  1283. }
  1284. JPH_NAMESPACE_END