b2ParticleSystem.cpp 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650
  1. /*
  2. * Copyright (c) 2013 Google, Inc.
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. * Permission is granted to anyone to use this software for any purpose,
  8. * including commercial applications, and to alter it and redistribute it
  9. * freely, subject to the following restrictions:
  10. * 1. The origin of this software must not be misrepresented; you must not
  11. * claim that you wrote the original software. If you use this software
  12. * in a product, an acknowledgment in the product documentation would be
  13. * appreciated but is not required.
  14. * 2. Altered source versions must be plainly marked as such, and must not be
  15. * misrepresented as being the original software.
  16. * 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include <Box2D/Particle/b2ParticleSystem.h>
  19. #include <Box2D/Particle/b2ParticleGroup.h>
  20. #include <Box2D/Particle/b2VoronoiDiagram.h>
  21. #include <Box2D/Particle/b2ParticleAssembly.h>
  22. #include <Box2D/Common/b2BlockAllocator.h>
  23. #include <Box2D/Dynamics/b2World.h>
  24. #include <Box2D/Dynamics/b2WorldCallbacks.h>
  25. #include <Box2D/Dynamics/b2Body.h>
  26. #include <Box2D/Dynamics/b2Fixture.h>
  27. #include <Box2D/Collision/Shapes/b2Shape.h>
  28. #include <Box2D/Collision/Shapes/b2EdgeShape.h>
  29. #include <Box2D/Collision/Shapes/b2ChainShape.h>
  30. #include <algorithm>
  31. // Define LIQUIDFUN_SIMD_TEST_VS_REFERENCE to run both SIMD and reference
  32. // versions, and assert that the results are identical. This is useful when
  33. // modifying one of the functions, to help verify correctness.
  34. // #define LIQUIDFUN_SIMD_TEST_VS_REFERENCE
  35. // For ease of debugging, remove 'inline'. Then, when an assert hits in the
  36. // test-vs-reference functions, you can easily jump the instruction pointer
  37. // to the top of the function to re-run the test.
  38. #define LIQUIDFUN_SIMD_INLINE inline
  39. static const uint32 xTruncBits = 12;
  40. static const uint32 yTruncBits = 12;
  41. static const uint32 tagBits = 8u * sizeof(uint32);
  42. static const uint32 yOffset = 1u << (yTruncBits - 1u);
  43. static const uint32 yShift = tagBits - yTruncBits;
  44. static const uint32 xShift = tagBits - yTruncBits - xTruncBits;
  45. static const uint32 xScale = 1u << xShift;
  46. static const uint32 xOffset = xScale * (1u << (xTruncBits - 1u));
  47. static const uint32 yMask = ((1u << yTruncBits) - 1u) << yShift;
  48. static const uint32 xMask = ~yMask;
  49. static const uint32 relativeTagRight = 1u << xShift;
  50. static const uint32 relativeTagBottomLeft = (uint32)((1 << yShift) +
  51. (-1 << xShift));
  52. static const uint32 relativeTagBottomRight = (1u << yShift) + (1u << xShift);
  53. // This functor is passed to std::remove_if in RemoveSpuriousBodyContacts
  54. // to implement the algorithm described there. It was hoisted out and friended
  55. // as it would not compile with g++ 4.6.3 as a local class. It is only used in
  56. // that function.
  57. class b2ParticleBodyContactRemovePredicate
  58. {
  59. public:
  60. b2ParticleBodyContactRemovePredicate(b2ParticleSystem* system,
  61. int32* discarded)
  62. : m_system(system), m_lastIndex(-1), m_currentContacts(0),
  63. m_discarded(discarded) {}
  64. bool operator()(const b2ParticleBodyContact& contact)
  65. {
  66. // This implements the selection criteria described in
  67. // RemoveSpuriousBodyContacts().
  68. // This functor is iterating through a list of Body contacts per
  69. // Particle, ordered from near to far. For up to the maximum number of
  70. // contacts we allow per point per step, we verify that the contact
  71. // normal of the Body that genenerated the contact makes physical sense
  72. // by projecting a point back along that normal and seeing if it
  73. // intersects the fixture generating the contact.
  74. if (contact.index != m_lastIndex)
  75. {
  76. m_currentContacts = 0;
  77. m_lastIndex = contact.index;
  78. }
  79. if (m_currentContacts++ > k_maxContactsPerPoint)
  80. {
  81. ++(*m_discarded);
  82. return true;
  83. }
  84. // Project along inverse normal (as returned in the contact) to get the
  85. // point to check.
  86. b2Vec2 n = contact.normal;
  87. // weight is 1-(inv(diameter) * distance)
  88. n *= m_system->m_particleDiameter * (1 - contact.weight);
  89. b2Vec2 pos = m_system->m_positionBuffer.data[contact.index] + n;
  90. // pos is now a point projected back along the contact normal to the
  91. // contact distance. If the surface makes sense for a contact, pos will
  92. // now lie on or in the fixture generating
  93. if (!contact.fixture->TestPoint(pos))
  94. {
  95. int32 childCount = contact.fixture->GetShape()->GetChildCount();
  96. for (int32 childIndex = 0; childIndex < childCount; childIndex++)
  97. {
  98. float32 distance;
  99. b2Vec2 normal;
  100. contact.fixture->ComputeDistance(pos, &distance, &normal,
  101. childIndex);
  102. if (distance < b2_linearSlop)
  103. {
  104. return false;
  105. }
  106. }
  107. ++(*m_discarded);
  108. return true;
  109. }
  110. return false;
  111. }
  112. private:
  113. // Max number of contacts processed per particle, from nearest to farthest.
  114. // This must be at least 2 for correctness with concave shapes; 3 was
  115. // experimentally arrived at as looking reasonable.
  116. static const int32 k_maxContactsPerPoint = 3;
  117. const b2ParticleSystem* m_system;
  118. // Index of last particle processed.
  119. int32 m_lastIndex;
  120. // Number of contacts processed for the current particle.
  121. int32 m_currentContacts;
  122. // Output the number of discarded contacts.
  123. int32* m_discarded;
  124. };
  125. namespace {
  126. // Compares the expiration time of two particle indices.
  127. class ExpirationTimeComparator
  128. {
  129. public:
  130. // Initialize the class with a pointer to an array of particle
  131. // lifetimes.
  132. ExpirationTimeComparator(const int32* const expirationTimes) :
  133. m_expirationTimes(expirationTimes)
  134. {
  135. }
  136. // Empty destructor.
  137. ~ExpirationTimeComparator() { }
  138. // Compare the lifetime of particleIndexA and particleIndexB
  139. // returning true if the lifetime of A is greater than B for particles
  140. // that will expire. If either particle's lifetime is infinite (<= 0.0f)
  141. // this function return true if the lifetime of A is lesser than B.
  142. // When used with std::sort() this results in an array of particle
  143. // indicies sorted in reverse order by particle lifetime.
  144. // For example, the set of lifetimes
  145. // (1.0, 0.7, 0.3, 0.0, -1.0, -2.0)
  146. // would be sorted as
  147. // (0.0, -1.0, -2.0, 1.0, 0.7, 0.3)
  148. bool operator() (const int32 particleIndexA,
  149. const int32 particleIndexB) const
  150. {
  151. const int32 expirationTimeA = m_expirationTimes[particleIndexA];
  152. const int32 expirationTimeB = m_expirationTimes[particleIndexB];
  153. const bool infiniteExpirationTimeA = expirationTimeA <= 0.0f;
  154. const bool infiniteExpirationTimeB = expirationTimeB <= 0.0f;
  155. return infiniteExpirationTimeA == infiniteExpirationTimeB ?
  156. expirationTimeA > expirationTimeB : infiniteExpirationTimeA;
  157. }
  158. private:
  159. const int32* m_expirationTimes;
  160. };
  161. // *Very* lightweight pair implementation.
  162. template<typename A, typename B>
  163. struct LightweightPair
  164. {
  165. A first;
  166. B second;
  167. // Compares the value of two FixtureParticle objects returning
  168. // true if left is a smaller value than right.
  169. static bool Compare(const LightweightPair& left,
  170. const LightweightPair& right)
  171. {
  172. return left.first < right.first &&
  173. left.second < right.second;
  174. }
  175. };
  176. // Allocator for a fixed set of items.
  177. class FixedSetAllocator
  178. {
  179. public:
  180. // Associate a memory allocator with this object.
  181. FixedSetAllocator(b2StackAllocator* allocator);
  182. // Deallocate storage for this class.
  183. ~FixedSetAllocator()
  184. {
  185. Clear();
  186. }
  187. // Allocate internal storage for this object returning the size.
  188. int32 Allocate(const int32 itemSize, const int32 count);
  189. // Deallocate the internal buffer if it's allocated.
  190. void Clear();
  191. // Get the number of items in the set.
  192. int32 GetCount() const { return m_count; }
  193. // Invalidate an item from the set by index.
  194. void Invalidate(const int32 itemIndex)
  195. {
  196. b2Assert(m_valid);
  197. m_valid[itemIndex] = 0;
  198. }
  199. // Get the buffer which indicates whether items are valid in the set.
  200. const int8* GetValidBuffer() const { return m_valid; }
  201. protected:
  202. // Get the internal buffer.
  203. void* GetBuffer() const { return m_buffer; }
  204. void* GetBuffer() { return m_buffer; }
  205. // Reduce the number of items in the set.
  206. void SetCount(int32 count)
  207. {
  208. b2Assert(count <= m_count);
  209. m_count = count;
  210. }
  211. private:
  212. // Set buffer.
  213. void* m_buffer;
  214. // Array of size m_count which indicates whether an item is in the
  215. // corresponding index of m_set (1) or the item is invalid (0).
  216. int8* m_valid;
  217. // Number of items in m_set.
  218. int32 m_count;
  219. // Allocator used to allocate / free the set.
  220. b2StackAllocator* m_allocator;
  221. };
  222. // Allocator for a fixed set of objects.
  223. template<typename T>
  224. class TypedFixedSetAllocator : public FixedSetAllocator
  225. {
  226. public:
  227. // Initialize members of this class.
  228. TypedFixedSetAllocator(b2StackAllocator* allocator) :
  229. FixedSetAllocator(allocator) { }
  230. // Allocate a set of objects, returning the new size of the set.
  231. int32 Allocate(const int32 numberOfObjects)
  232. {
  233. Clear();
  234. return FixedSetAllocator::Allocate(sizeof(T), numberOfObjects);
  235. }
  236. // Get the index of an item in the set if it's valid return an index
  237. // >= 0, -1 otherwise.
  238. int32 GetIndex(const T* item) const
  239. {
  240. if (item)
  241. {
  242. b2Assert(item >= GetBuffer() &&
  243. item < GetBuffer() + GetCount());
  244. const int32 index =
  245. (int32)(((uint8*)item - (uint8*)GetBuffer()) /
  246. sizeof(*item));
  247. if (GetValidBuffer()[index])
  248. {
  249. return index;
  250. }
  251. }
  252. return -1;
  253. }
  254. // Get the internal buffer.
  255. const T* GetBuffer() const
  256. {
  257. return (const T*)FixedSetAllocator::GetBuffer();
  258. }
  259. T* GetBuffer() { return (T*)FixedSetAllocator::GetBuffer(); }
  260. };
  261. // Associates a fixture with a particle index.
  262. typedef LightweightPair<b2Fixture*,int32> FixtureParticle;
  263. // Associates a fixture with a particle index.
  264. typedef LightweightPair<int32,int32> ParticlePair;
  265. } // namespace
  266. // Set of fixture / particle indices.
  267. class FixtureParticleSet :
  268. public TypedFixedSetAllocator<FixtureParticle>
  269. {
  270. public:
  271. // Initialize members of this class.
  272. FixtureParticleSet(b2StackAllocator* allocator) :
  273. TypedFixedSetAllocator<FixtureParticle>(allocator) { }
  274. // Initialize from a set of particle / body contacts for particles
  275. // that have the b2_fixtureContactListenerParticle flag set.
  276. void Initialize(const b2ParticleBodyContact * const bodyContacts,
  277. const int32 numBodyContacts,
  278. const uint32 * const particleFlagsBuffer);
  279. // Find the index of a particle / fixture pair in the set or -1
  280. // if it's not present.
  281. // NOTE: This was not written as a template function to avoid
  282. // exposing any dependencies via this header.
  283. int32 Find(const FixtureParticle& fixtureParticle) const;
  284. };
  285. // Set of particle / particle pairs.
  286. class b2ParticlePairSet : public TypedFixedSetAllocator<ParticlePair>
  287. {
  288. public:
  289. // Initialize members of this class.
  290. b2ParticlePairSet(b2StackAllocator* allocator) :
  291. TypedFixedSetAllocator<ParticlePair>(allocator) { }
  292. // Initialize from a set of particle contacts.
  293. void Initialize(const b2ParticleContact * const contacts,
  294. const int32 numContacts,
  295. const uint32 * const particleFlagsBuffer);
  296. // Find the index of a particle pair in the set or -1
  297. // if it's not present.
  298. // NOTE: This was not written as a template function to avoid
  299. // exposing any dependencies via this header.
  300. int32 Find(const ParticlePair& pair) const;
  301. };
  302. static inline uint32 computeTag(float32 x, float32 y)
  303. {
  304. return ((uint32)(y + yOffset) << yShift) + (uint32)(xScale * x + xOffset);
  305. }
  306. static inline uint32 computeRelativeTag(uint32 tag, int32 x, int32 y)
  307. {
  308. return tag + (y << yShift) + (x << xShift);
  309. }
  310. b2ParticleSystem::InsideBoundsEnumerator::InsideBoundsEnumerator(
  311. uint32 lower, uint32 upper, const Proxy* first, const Proxy* last)
  312. {
  313. m_xLower = lower & xMask;
  314. m_xUpper = upper & xMask;
  315. m_yLower = lower & yMask;
  316. m_yUpper = upper & yMask;
  317. m_first = first;
  318. m_last = last;
  319. b2Assert(m_first <= m_last);
  320. }
  321. int32 b2ParticleSystem::InsideBoundsEnumerator::GetNext()
  322. {
  323. while (m_first < m_last)
  324. {
  325. uint32 xTag = m_first->tag & xMask;
  326. #if B2_ASSERT_ENABLED
  327. uint32 yTag = m_first->tag & yMask;
  328. b2Assert(yTag >= m_yLower);
  329. b2Assert(yTag <= m_yUpper);
  330. #endif
  331. if (xTag >= m_xLower && xTag <= m_xUpper)
  332. {
  333. return (m_first++)->index;
  334. }
  335. m_first++;
  336. }
  337. return b2_invalidParticleIndex;
  338. }
  339. b2ParticleSystem::b2ParticleSystem(const b2ParticleSystemDef* def,
  340. b2World* world) :
  341. m_handleAllocator(b2_minParticleSystemBufferCapacity),
  342. m_stuckParticleBuffer(world->m_blockAllocator),
  343. m_proxyBuffer(world->m_blockAllocator),
  344. m_contactBuffer(world->m_blockAllocator),
  345. m_bodyContactBuffer(world->m_blockAllocator),
  346. m_pairBuffer(world->m_blockAllocator),
  347. m_triadBuffer(world->m_blockAllocator)
  348. {
  349. b2Assert(def);
  350. m_paused = false;
  351. m_timestamp = 0;
  352. m_allParticleFlags = 0;
  353. m_needsUpdateAllParticleFlags = false;
  354. m_allGroupFlags = 0;
  355. m_needsUpdateAllGroupFlags = false;
  356. m_hasForce = false;
  357. m_iterationIndex = 0;
  358. SetStrictContactCheck(def->strictContactCheck);
  359. SetDensity(def->density);
  360. SetGravityScale(def->gravityScale);
  361. SetRadius(def->radius);
  362. SetMaxParticleCount(def->maxCount);
  363. m_count = 0;
  364. m_internalAllocatedCapacity = 0;
  365. m_forceBuffer = NULL;
  366. m_weightBuffer = NULL;
  367. m_staticPressureBuffer = NULL;
  368. m_accumulationBuffer = NULL;
  369. m_accumulation2Buffer = NULL;
  370. m_depthBuffer = NULL;
  371. m_groupBuffer = NULL;
  372. m_groupCount = 0;
  373. m_groupList = NULL;
  374. b2Assert(def->lifetimeGranularity > 0.0f);
  375. m_def = *def;
  376. m_world = world;
  377. m_stuckThreshold = 0;
  378. m_timeElapsed = 0;
  379. m_expirationTimeBufferRequiresSorting = false;
  380. SetDestructionByAge(m_def.destroyByAge);
  381. }
  382. b2ParticleSystem::~b2ParticleSystem()
  383. {
  384. while (m_groupList)
  385. {
  386. DestroyParticleGroup(m_groupList);
  387. }
  388. FreeUserOverridableBuffer(&m_handleIndexBuffer);
  389. FreeUserOverridableBuffer(&m_flagsBuffer);
  390. FreeUserOverridableBuffer(&m_lastBodyContactStepBuffer);
  391. FreeUserOverridableBuffer(&m_bodyContactCountBuffer);
  392. FreeUserOverridableBuffer(&m_consecutiveContactStepsBuffer);
  393. FreeUserOverridableBuffer(&m_positionBuffer);
  394. FreeUserOverridableBuffer(&m_velocityBuffer);
  395. FreeUserOverridableBuffer(&m_colorBuffer);
  396. FreeUserOverridableBuffer(&m_userDataBuffer);
  397. FreeUserOverridableBuffer(&m_expirationTimeBuffer);
  398. FreeUserOverridableBuffer(&m_indexByExpirationTimeBuffer);
  399. FreeBuffer(&m_forceBuffer, m_internalAllocatedCapacity);
  400. FreeBuffer(&m_weightBuffer, m_internalAllocatedCapacity);
  401. FreeBuffer(&m_staticPressureBuffer, m_internalAllocatedCapacity);
  402. FreeBuffer(&m_accumulationBuffer, m_internalAllocatedCapacity);
  403. FreeBuffer(&m_accumulation2Buffer, m_internalAllocatedCapacity);
  404. FreeBuffer(&m_depthBuffer, m_internalAllocatedCapacity);
  405. FreeBuffer(&m_groupBuffer, m_internalAllocatedCapacity);
  406. }
  407. template <typename T> void b2ParticleSystem::FreeBuffer(T** b, int capacity)
  408. {
  409. if (*b == NULL)
  410. return;
  411. m_world->m_blockAllocator.Free(*b, sizeof(**b) * capacity);
  412. *b = NULL;
  413. }
  414. // Free buffer, if it was allocated with b2World's block allocator
  415. template <typename T> void b2ParticleSystem::FreeUserOverridableBuffer(
  416. UserOverridableBuffer<T>* b)
  417. {
  418. if (b->userSuppliedCapacity == 0)
  419. {
  420. FreeBuffer(&b->data, m_internalAllocatedCapacity);
  421. }
  422. }
  423. // Reallocate a buffer
  424. template <typename T> T* b2ParticleSystem::ReallocateBuffer(
  425. T* oldBuffer, int32 oldCapacity, int32 newCapacity)
  426. {
  427. b2Assert(newCapacity > oldCapacity);
  428. T* newBuffer = (T*) m_world->m_blockAllocator.Allocate(
  429. sizeof(T) * newCapacity);
  430. if (oldBuffer)
  431. {
  432. memcpy(newBuffer, oldBuffer, sizeof(T) * oldCapacity);
  433. m_world->m_blockAllocator.Free(oldBuffer, sizeof(T) * oldCapacity);
  434. }
  435. return newBuffer;
  436. }
  437. // Reallocate a buffer
  438. template <typename T> T* b2ParticleSystem::ReallocateBuffer(
  439. T* buffer, int32 userSuppliedCapacity, int32 oldCapacity,
  440. int32 newCapacity, bool deferred)
  441. {
  442. b2Assert(newCapacity > oldCapacity);
  443. // A 'deferred' buffer is reallocated only if it is not NULL.
  444. // If 'userSuppliedCapacity' is not zero, buffer is user supplied and must
  445. // be kept.
  446. b2Assert(!userSuppliedCapacity || newCapacity <= userSuppliedCapacity);
  447. if ((!deferred || buffer) && !userSuppliedCapacity)
  448. {
  449. buffer = ReallocateBuffer(buffer, oldCapacity, newCapacity);
  450. }
  451. return buffer;
  452. }
  453. // Reallocate a buffer
  454. template <typename T> T* b2ParticleSystem::ReallocateBuffer(
  455. UserOverridableBuffer<T>* buffer, int32 oldCapacity, int32 newCapacity,
  456. bool deferred)
  457. {
  458. b2Assert(newCapacity > oldCapacity);
  459. return ReallocateBuffer(buffer->data, buffer->userSuppliedCapacity,
  460. oldCapacity, newCapacity, deferred);
  461. }
  462. /// Reallocate the handle / index map and schedule the allocation of a new
  463. /// pool for handle allocation.
  464. void b2ParticleSystem::ReallocateHandleBuffers(int32 newCapacity)
  465. {
  466. b2Assert(newCapacity > m_internalAllocatedCapacity);
  467. // Reallocate a new handle / index map buffer, copying old handle pointers
  468. // is fine since they're kept around.
  469. m_handleIndexBuffer.data = ReallocateBuffer(
  470. &m_handleIndexBuffer, m_internalAllocatedCapacity, newCapacity,
  471. true);
  472. // Set the size of the next handle allocation.
  473. m_handleAllocator.SetItemsPerSlab(newCapacity -
  474. m_internalAllocatedCapacity);
  475. }
  476. template <typename T> T* b2ParticleSystem::RequestBuffer(T* buffer)
  477. {
  478. if (!buffer)
  479. {
  480. if (m_internalAllocatedCapacity == 0)
  481. {
  482. ReallocateInternalAllocatedBuffers(
  483. b2_minParticleSystemBufferCapacity);
  484. }
  485. buffer = (T*) (m_world->m_blockAllocator.Allocate(
  486. sizeof(T) * m_internalAllocatedCapacity));
  487. b2Assert(buffer);
  488. memset(buffer, 0, sizeof(T) * m_internalAllocatedCapacity);
  489. }
  490. return buffer;
  491. }
  492. b2ParticleColor* b2ParticleSystem::GetColorBuffer()
  493. {
  494. m_colorBuffer.data = RequestBuffer(m_colorBuffer.data);
  495. return m_colorBuffer.data;
  496. }
  497. void** b2ParticleSystem::GetUserDataBuffer()
  498. {
  499. m_userDataBuffer.data = RequestBuffer(m_userDataBuffer.data);
  500. return m_userDataBuffer.data;
  501. }
  502. static int32 LimitCapacity(int32 capacity, int32 maxCount)
  503. {
  504. return maxCount && capacity > maxCount ? maxCount : capacity;
  505. }
  506. void b2ParticleSystem::ReallocateInternalAllocatedBuffers(int32 capacity)
  507. {
  508. // Don't increase capacity beyond the smallest user-supplied buffer size.
  509. capacity = LimitCapacity(capacity, m_def.maxCount);
  510. capacity = LimitCapacity(capacity, m_flagsBuffer.userSuppliedCapacity);
  511. capacity = LimitCapacity(capacity, m_positionBuffer.userSuppliedCapacity);
  512. capacity = LimitCapacity(capacity, m_velocityBuffer.userSuppliedCapacity);
  513. capacity = LimitCapacity(capacity, m_colorBuffer.userSuppliedCapacity);
  514. capacity = LimitCapacity(capacity, m_userDataBuffer.userSuppliedCapacity);
  515. if (m_internalAllocatedCapacity < capacity)
  516. {
  517. ReallocateHandleBuffers(capacity);
  518. m_flagsBuffer.data = ReallocateBuffer(
  519. &m_flagsBuffer, m_internalAllocatedCapacity, capacity, false);
  520. // Conditionally defer these as they are optional if the feature is
  521. // not enabled.
  522. const bool stuck = m_stuckThreshold > 0;
  523. m_lastBodyContactStepBuffer.data = ReallocateBuffer(
  524. &m_lastBodyContactStepBuffer, m_internalAllocatedCapacity,
  525. capacity, stuck);
  526. m_bodyContactCountBuffer.data = ReallocateBuffer(
  527. &m_bodyContactCountBuffer, m_internalAllocatedCapacity, capacity,
  528. stuck);
  529. m_consecutiveContactStepsBuffer.data = ReallocateBuffer(
  530. &m_consecutiveContactStepsBuffer, m_internalAllocatedCapacity,
  531. capacity, stuck);
  532. m_positionBuffer.data = ReallocateBuffer(
  533. &m_positionBuffer, m_internalAllocatedCapacity, capacity, false);
  534. m_velocityBuffer.data = ReallocateBuffer(
  535. &m_velocityBuffer, m_internalAllocatedCapacity, capacity, false);
  536. m_forceBuffer = ReallocateBuffer(
  537. m_forceBuffer, 0, m_internalAllocatedCapacity, capacity, false);
  538. m_weightBuffer = ReallocateBuffer(
  539. m_weightBuffer, 0, m_internalAllocatedCapacity, capacity, false);
  540. m_staticPressureBuffer = ReallocateBuffer(
  541. m_staticPressureBuffer, 0, m_internalAllocatedCapacity, capacity,
  542. true);
  543. m_accumulationBuffer = ReallocateBuffer(
  544. m_accumulationBuffer, 0, m_internalAllocatedCapacity, capacity,
  545. false);
  546. m_accumulation2Buffer = ReallocateBuffer(
  547. m_accumulation2Buffer, 0, m_internalAllocatedCapacity, capacity,
  548. true);
  549. m_depthBuffer = ReallocateBuffer(
  550. m_depthBuffer, 0, m_internalAllocatedCapacity, capacity, true);
  551. m_colorBuffer.data = ReallocateBuffer(
  552. &m_colorBuffer, m_internalAllocatedCapacity, capacity, true);
  553. m_groupBuffer = ReallocateBuffer(
  554. m_groupBuffer, 0, m_internalAllocatedCapacity, capacity, false);
  555. m_userDataBuffer.data = ReallocateBuffer(
  556. &m_userDataBuffer, m_internalAllocatedCapacity, capacity, true);
  557. m_expirationTimeBuffer.data = ReallocateBuffer(
  558. &m_expirationTimeBuffer, m_internalAllocatedCapacity, capacity,
  559. true);
  560. m_indexByExpirationTimeBuffer.data = ReallocateBuffer(
  561. &m_indexByExpirationTimeBuffer, m_internalAllocatedCapacity,
  562. capacity, true);
  563. m_internalAllocatedCapacity = capacity;
  564. }
  565. }
  566. int32 b2ParticleSystem::CreateParticle(const b2ParticleDef& def)
  567. {
  568. b2Assert(m_world->IsLocked() == false);
  569. if (m_world->IsLocked())
  570. {
  571. return 0;
  572. }
  573. if (m_count >= m_internalAllocatedCapacity)
  574. {
  575. // Double the particle capacity.
  576. int32 capacity =
  577. m_count ? 2 * m_count : b2_minParticleSystemBufferCapacity;
  578. ReallocateInternalAllocatedBuffers(capacity);
  579. }
  580. if (m_count >= m_internalAllocatedCapacity)
  581. {
  582. // If the oldest particle should be destroyed...
  583. if (m_def.destroyByAge)
  584. {
  585. DestroyOldestParticle(0, false);
  586. // Need to destroy this particle *now* so that it's possible to
  587. // create a new particle.
  588. SolveZombie();
  589. }
  590. else
  591. {
  592. return b2_invalidParticleIndex;
  593. }
  594. }
  595. int32 index = m_count++;
  596. m_flagsBuffer.data[index] = 0;
  597. if (m_lastBodyContactStepBuffer.data)
  598. {
  599. m_lastBodyContactStepBuffer.data[index] = 0;
  600. }
  601. if (m_bodyContactCountBuffer.data)
  602. {
  603. m_bodyContactCountBuffer.data[index] = 0;
  604. }
  605. if (m_consecutiveContactStepsBuffer.data)
  606. {
  607. m_consecutiveContactStepsBuffer.data[index] = 0;
  608. }
  609. m_positionBuffer.data[index] = def.position;
  610. m_velocityBuffer.data[index] = def.velocity;
  611. m_weightBuffer[index] = 0;
  612. m_forceBuffer[index] = b2Vec2_zero;
  613. if (m_staticPressureBuffer)
  614. {
  615. m_staticPressureBuffer[index] = 0;
  616. }
  617. if (m_depthBuffer)
  618. {
  619. m_depthBuffer[index] = 0;
  620. }
  621. if (m_colorBuffer.data || !def.color.IsZero())
  622. {
  623. m_colorBuffer.data = RequestBuffer(m_colorBuffer.data);
  624. m_colorBuffer.data[index] = def.color;
  625. }
  626. if (m_userDataBuffer.data || def.userData)
  627. {
  628. m_userDataBuffer.data= RequestBuffer(m_userDataBuffer.data);
  629. m_userDataBuffer.data[index] = def.userData;
  630. }
  631. if (m_handleIndexBuffer.data)
  632. {
  633. m_handleIndexBuffer.data[index] = NULL;
  634. }
  635. Proxy& proxy = m_proxyBuffer.Append();
  636. // If particle lifetimes are enabled or the lifetime is set in the particle
  637. // definition, initialize the lifetime.
  638. const bool finiteLifetime = def.lifetime > 0;
  639. if (m_expirationTimeBuffer.data || finiteLifetime)
  640. {
  641. SetParticleLifetime(index, finiteLifetime ? def.lifetime :
  642. ExpirationTimeToLifetime(
  643. -GetQuantizedTimeElapsed()));
  644. // Add a reference to the newly added particle to the end of the
  645. // queue.
  646. m_indexByExpirationTimeBuffer.data[index] = index;
  647. }
  648. proxy.index = index;
  649. b2ParticleGroup* group = def.group;
  650. m_groupBuffer[index] = group;
  651. if (group)
  652. {
  653. if (group->m_firstIndex < group->m_lastIndex)
  654. {
  655. // Move particles in the group just before the new particle.
  656. RotateBuffer(group->m_firstIndex, group->m_lastIndex, index);
  657. b2Assert(group->m_lastIndex == index);
  658. // Update the index range of the group to contain the new particle.
  659. group->m_lastIndex = index + 1;
  660. }
  661. else
  662. {
  663. // If the group is empty, reset the index range to contain only the
  664. // new particle.
  665. group->m_firstIndex = index;
  666. group->m_lastIndex = index + 1;
  667. }
  668. }
  669. SetParticleFlags(index, def.flags);
  670. return index;
  671. }
  672. /// Retrieve a handle to the particle at the specified index.
  673. const b2ParticleHandle* b2ParticleSystem::GetParticleHandleFromIndex(
  674. const int32 index)
  675. {
  676. b2Assert(index >= 0 && index < GetParticleCount() &&
  677. index != b2_invalidParticleIndex);
  678. m_handleIndexBuffer.data = RequestBuffer(m_handleIndexBuffer.data);
  679. b2ParticleHandle* handle = m_handleIndexBuffer.data[index];
  680. if (handle)
  681. {
  682. return handle;
  683. }
  684. // Create a handle.
  685. handle = m_handleAllocator.Allocate();
  686. b2Assert(handle);
  687. handle->SetIndex(index);
  688. m_handleIndexBuffer.data[index] = handle;
  689. return handle;
  690. }
  691. void b2ParticleSystem::DestroyParticle(
  692. int32 index, bool callDestructionListener)
  693. {
  694. uint32 flags = b2_zombieParticle;
  695. if (callDestructionListener)
  696. {
  697. flags |= b2_destructionListenerParticle;
  698. }
  699. SetParticleFlags(index, m_flagsBuffer.data[index] | flags);
  700. }
  701. void b2ParticleSystem::DestroyOldestParticle(
  702. const int32 index, const bool callDestructionListener)
  703. {
  704. const int32 particleCount = GetParticleCount();
  705. b2Assert(index >= 0 && index < particleCount);
  706. // Make sure particle lifetime tracking is enabled.
  707. b2Assert(m_indexByExpirationTimeBuffer.data);
  708. // Destroy the oldest particle (preferring to destroy finite
  709. // lifetime particles first) to free a slot in the buffer.
  710. const int32 oldestFiniteLifetimeParticle =
  711. m_indexByExpirationTimeBuffer.data[particleCount - (index + 1)];
  712. const int32 oldestInfiniteLifetimeParticle =
  713. m_indexByExpirationTimeBuffer.data[index];
  714. DestroyParticle(
  715. m_expirationTimeBuffer.data[oldestFiniteLifetimeParticle] > 0.0f ?
  716. oldestFiniteLifetimeParticle : oldestInfiniteLifetimeParticle,
  717. callDestructionListener);
  718. }
  719. int32 b2ParticleSystem::DestroyParticlesInShape(
  720. const b2Shape& shape, const b2Transform& xf,
  721. bool callDestructionListener)
  722. {
  723. b2Assert(m_world->IsLocked() == false);
  724. if (m_world->IsLocked())
  725. {
  726. return 0;
  727. }
  728. class DestroyParticlesInShapeCallback : public b2QueryCallback
  729. {
  730. public:
  731. DestroyParticlesInShapeCallback(
  732. b2ParticleSystem* system, const b2Shape& shape,
  733. const b2Transform& xf, bool callDestructionListener)
  734. {
  735. m_system = system;
  736. m_shape = &shape;
  737. m_xf = xf;
  738. m_callDestructionListener = callDestructionListener;
  739. m_destroyed = 0;
  740. }
  741. bool ReportFixture(b2Fixture* fixture)
  742. {
  743. B2_NOT_USED(fixture);
  744. return false;
  745. }
  746. bool ReportParticle(const b2ParticleSystem* particleSystem, int32 index)
  747. {
  748. if (particleSystem != m_system)
  749. return false;
  750. b2Assert(index >=0 && index < m_system->m_count);
  751. if (m_shape->TestPoint(m_xf,
  752. m_system->m_positionBuffer.data[index]))
  753. {
  754. m_system->DestroyParticle(index, m_callDestructionListener);
  755. m_destroyed++;
  756. }
  757. return true;
  758. }
  759. int32 Destroyed() { return m_destroyed; }
  760. private:
  761. b2ParticleSystem* m_system;
  762. const b2Shape* m_shape;
  763. b2Transform m_xf;
  764. bool m_callDestructionListener;
  765. int32 m_destroyed;
  766. } callback(this, shape, xf, callDestructionListener);
  767. b2AABB aabb;
  768. shape.ComputeAABB(&aabb, xf, 0);
  769. m_world->QueryAABB(&callback, aabb);
  770. return callback.Destroyed();
  771. }
  772. int32 b2ParticleSystem::CreateParticleForGroup(
  773. const b2ParticleGroupDef& groupDef, const b2Transform& xf, const b2Vec2& p)
  774. {
  775. b2ParticleDef particleDef;
  776. particleDef.flags = groupDef.flags;
  777. particleDef.position = b2Mul(xf, p);
  778. particleDef.velocity =
  779. groupDef.linearVelocity +
  780. b2Cross(groupDef.angularVelocity,
  781. particleDef.position - groupDef.position);
  782. particleDef.color = groupDef.color;
  783. particleDef.lifetime = groupDef.lifetime;
  784. particleDef.userData = groupDef.userData;
  785. return CreateParticle(particleDef);
  786. }
  787. void b2ParticleSystem::CreateParticlesStrokeShapeForGroup(
  788. const b2Shape *shape,
  789. const b2ParticleGroupDef& groupDef, const b2Transform& xf)
  790. {
  791. float32 stride = groupDef.stride;
  792. if (stride == 0)
  793. {
  794. stride = GetParticleStride();
  795. }
  796. float32 positionOnEdge = 0;
  797. int32 childCount = shape->GetChildCount();
  798. for (int32 childIndex = 0; childIndex < childCount; childIndex++)
  799. {
  800. b2EdgeShape edge;
  801. if (shape->GetType() == b2Shape::e_edge)
  802. {
  803. edge = *(b2EdgeShape*) shape;
  804. }
  805. else
  806. {
  807. b2Assert(shape->GetType() == b2Shape::e_chain);
  808. ((b2ChainShape*) shape)->GetChildEdge(&edge, childIndex);
  809. }
  810. b2Vec2 d = edge.m_vertex2 - edge.m_vertex1;
  811. float32 edgeLength = d.Length();
  812. while (positionOnEdge < edgeLength)
  813. {
  814. b2Vec2 p = edge.m_vertex1 + positionOnEdge / edgeLength * d;
  815. CreateParticleForGroup(groupDef, xf, p);
  816. positionOnEdge += stride;
  817. }
  818. positionOnEdge -= edgeLength;
  819. }
  820. }
  821. void b2ParticleSystem::CreateParticlesFillShapeForGroup(
  822. const b2Shape *shape,
  823. const b2ParticleGroupDef& groupDef, const b2Transform& xf)
  824. {
  825. float32 stride = groupDef.stride;
  826. if (stride == 0)
  827. {
  828. stride = GetParticleStride();
  829. }
  830. b2Transform identity;
  831. identity.SetIdentity();
  832. b2AABB aabb;
  833. b2Assert(shape->GetChildCount() == 1);
  834. shape->ComputeAABB(&aabb, identity, 0);
  835. for (float32 y = floorf(aabb.lowerBound.y / stride) * stride;
  836. y < aabb.upperBound.y; y += stride)
  837. {
  838. for (float32 x = floorf(aabb.lowerBound.x / stride) * stride;
  839. x < aabb.upperBound.x; x += stride)
  840. {
  841. b2Vec2 p(x, y);
  842. if (shape->TestPoint(identity, p))
  843. {
  844. CreateParticleForGroup(groupDef, xf, p);
  845. }
  846. }
  847. }
  848. }
  849. void b2ParticleSystem::CreateParticlesWithShapeForGroup(
  850. const b2Shape* shape,
  851. const b2ParticleGroupDef& groupDef, const b2Transform& xf)
  852. {
  853. switch (shape->GetType()) {
  854. case b2Shape::e_edge:
  855. case b2Shape::e_chain:
  856. CreateParticlesStrokeShapeForGroup(shape, groupDef, xf);
  857. break;
  858. case b2Shape::e_polygon:
  859. case b2Shape::e_circle:
  860. CreateParticlesFillShapeForGroup(shape, groupDef, xf);
  861. break;
  862. default:
  863. b2Assert(false);
  864. break;
  865. }
  866. }
  867. void b2ParticleSystem::CreateParticlesWithShapesForGroup(
  868. const b2Shape* const* shapes, int32 shapeCount,
  869. const b2ParticleGroupDef& groupDef, const b2Transform& xf)
  870. {
  871. class CompositeShape : public b2Shape
  872. {
  873. public:
  874. CompositeShape(const b2Shape* const* shapes, int32 shapeCount)
  875. {
  876. m_shapes = shapes;
  877. m_shapeCount = shapeCount;
  878. }
  879. b2Shape* Clone(b2BlockAllocator* allocator) const
  880. {
  881. b2Assert(false);
  882. B2_NOT_USED(allocator);
  883. return NULL;
  884. }
  885. int32 GetChildCount() const
  886. {
  887. return 1;
  888. }
  889. bool TestPoint(const b2Transform& xf, const b2Vec2& p) const
  890. {
  891. for (int32 i = 0; i < m_shapeCount; i++)
  892. {
  893. if (m_shapes[i]->TestPoint(xf, p))
  894. {
  895. return true;
  896. }
  897. }
  898. return false;
  899. }
  900. void ComputeDistance(const b2Transform& xf, const b2Vec2& p,
  901. float32* distance, b2Vec2* normal, int32 childIndex) const
  902. {
  903. b2Assert(false);
  904. B2_NOT_USED(xf);
  905. B2_NOT_USED(p);
  906. B2_NOT_USED(distance);
  907. B2_NOT_USED(normal);
  908. B2_NOT_USED(childIndex);
  909. }
  910. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  911. const b2Transform& transform, int32 childIndex) const
  912. {
  913. b2Assert(false);
  914. B2_NOT_USED(output);
  915. B2_NOT_USED(input);
  916. B2_NOT_USED(transform);
  917. B2_NOT_USED(childIndex);
  918. return false;
  919. }
  920. void ComputeAABB(
  921. b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
  922. {
  923. B2_NOT_USED(childIndex);
  924. aabb->lowerBound.x = +FLT_MAX;
  925. aabb->lowerBound.y = +FLT_MAX;
  926. aabb->upperBound.x = -FLT_MAX;
  927. aabb->upperBound.y = -FLT_MAX;
  928. b2Assert(childIndex == 0);
  929. for (int32 i = 0; i < m_shapeCount; i++)
  930. {
  931. int32 childCount = m_shapes[i]->GetChildCount();
  932. for (int32 j = 0; j < childCount; j++)
  933. {
  934. b2AABB subaabb;
  935. m_shapes[i]->ComputeAABB(&subaabb, xf, j);
  936. aabb->Combine(subaabb);
  937. }
  938. }
  939. }
  940. void ComputeMass(b2MassData* massData, float32 density) const
  941. {
  942. b2Assert(false);
  943. B2_NOT_USED(massData);
  944. B2_NOT_USED(density);
  945. }
  946. private:
  947. const b2Shape* const* m_shapes;
  948. int32 m_shapeCount;
  949. } compositeShape(shapes, shapeCount);
  950. CreateParticlesFillShapeForGroup(&compositeShape, groupDef, xf);
  951. }
  952. b2ParticleGroup* b2ParticleSystem::CreateParticleGroup(
  953. const b2ParticleGroupDef& groupDef)
  954. {
  955. b2Assert(m_world->IsLocked() == false);
  956. if (m_world->IsLocked())
  957. {
  958. return 0;
  959. }
  960. b2Transform transform;
  961. transform.Set(groupDef.position, groupDef.angle);
  962. int32 firstIndex = m_count;
  963. if (groupDef.shape)
  964. {
  965. CreateParticlesWithShapeForGroup(groupDef.shape, groupDef, transform);
  966. }
  967. if (groupDef.shapes)
  968. {
  969. CreateParticlesWithShapesForGroup(
  970. groupDef.shapes, groupDef.shapeCount, groupDef, transform);
  971. }
  972. if (groupDef.particleCount)
  973. {
  974. b2Assert(groupDef.positionData);
  975. for (int32 i = 0; i < groupDef.particleCount; i++)
  976. {
  977. b2Vec2 p = groupDef.positionData[i];
  978. CreateParticleForGroup(groupDef, transform, p);
  979. }
  980. }
  981. int32 lastIndex = m_count;
  982. void* mem = m_world->m_blockAllocator.Allocate(sizeof(b2ParticleGroup));
  983. b2ParticleGroup* group = new (mem) b2ParticleGroup();
  984. group->m_system = this;
  985. group->m_firstIndex = firstIndex;
  986. group->m_lastIndex = lastIndex;
  987. group->m_strength = groupDef.strength;
  988. group->m_userData = groupDef.userData;
  989. group->m_transform = transform;
  990. group->m_prev = NULL;
  991. group->m_next = m_groupList;
  992. if (m_groupList)
  993. {
  994. m_groupList->m_prev = group;
  995. }
  996. m_groupList = group;
  997. ++m_groupCount;
  998. for (int32 i = firstIndex; i < lastIndex; i++)
  999. {
  1000. m_groupBuffer[i] = group;
  1001. }
  1002. SetGroupFlags(group, groupDef.groupFlags);
  1003. // Create pairs and triads between particles in the group.
  1004. ConnectionFilter filter;
  1005. UpdateContacts(true);
  1006. UpdatePairsAndTriads(firstIndex, lastIndex, filter);
  1007. if (groupDef.group)
  1008. {
  1009. JoinParticleGroups(groupDef.group, group);
  1010. group = groupDef.group;
  1011. }
  1012. return group;
  1013. }
  1014. void b2ParticleSystem::JoinParticleGroups(b2ParticleGroup* groupA,
  1015. b2ParticleGroup* groupB)
  1016. {
  1017. b2Assert(m_world->IsLocked() == false);
  1018. if (m_world->IsLocked())
  1019. {
  1020. return;
  1021. }
  1022. b2Assert(groupA != groupB);
  1023. RotateBuffer(groupB->m_firstIndex, groupB->m_lastIndex, m_count);
  1024. b2Assert(groupB->m_lastIndex == m_count);
  1025. RotateBuffer(groupA->m_firstIndex, groupA->m_lastIndex,
  1026. groupB->m_firstIndex);
  1027. b2Assert(groupA->m_lastIndex == groupB->m_firstIndex);
  1028. // Create pairs and triads connecting groupA and groupB.
  1029. class JoinParticleGroupsFilter : public ConnectionFilter
  1030. {
  1031. bool ShouldCreatePair(int32 a, int32 b) const
  1032. {
  1033. return
  1034. (a < m_threshold && m_threshold <= b) ||
  1035. (b < m_threshold && m_threshold <= a);
  1036. }
  1037. bool ShouldCreateTriad(int32 a, int32 b, int32 c) const
  1038. {
  1039. return
  1040. (a < m_threshold || b < m_threshold || c < m_threshold) &&
  1041. (m_threshold <= a || m_threshold <= b || m_threshold <= c);
  1042. }
  1043. int32 m_threshold;
  1044. public:
  1045. JoinParticleGroupsFilter(int32 threshold)
  1046. {
  1047. m_threshold = threshold;
  1048. }
  1049. } filter(groupB->m_firstIndex);
  1050. UpdateContacts(true);
  1051. UpdatePairsAndTriads(groupA->m_firstIndex, groupB->m_lastIndex, filter);
  1052. for (int32 i = groupB->m_firstIndex; i < groupB->m_lastIndex; i++)
  1053. {
  1054. m_groupBuffer[i] = groupA;
  1055. }
  1056. uint32 groupFlags = groupA->m_groupFlags | groupB->m_groupFlags;
  1057. SetGroupFlags(groupA, groupFlags);
  1058. groupA->m_lastIndex = groupB->m_lastIndex;
  1059. groupB->m_firstIndex = groupB->m_lastIndex;
  1060. DestroyParticleGroup(groupB);
  1061. }
  1062. void b2ParticleSystem::SplitParticleGroup(b2ParticleGroup* group)
  1063. {
  1064. UpdateContacts(true);
  1065. int32 particleCount = group->GetParticleCount();
  1066. // We create several linked lists. Each list represents a set of connected
  1067. // particles.
  1068. ParticleListNode* nodeBuffer =
  1069. (ParticleListNode*) m_world->m_stackAllocator.Allocate(
  1070. sizeof(ParticleListNode) * particleCount);
  1071. InitializeParticleLists(group, nodeBuffer);
  1072. MergeParticleListsInContact(group, nodeBuffer);
  1073. ParticleListNode* survivingList =
  1074. FindLongestParticleList(group, nodeBuffer);
  1075. MergeZombieParticleListNodes(group, nodeBuffer, survivingList);
  1076. CreateParticleGroupsFromParticleList(group, nodeBuffer, survivingList);
  1077. UpdatePairsAndTriadsWithParticleList(group, nodeBuffer);
  1078. m_world->m_stackAllocator.Free(nodeBuffer);
  1079. }
  1080. void b2ParticleSystem::InitializeParticleLists(
  1081. const b2ParticleGroup* group, ParticleListNode* nodeBuffer)
  1082. {
  1083. int32 bufferIndex = group->GetBufferIndex();
  1084. int32 particleCount = group->GetParticleCount();
  1085. for (int32 i = 0; i < particleCount; i++)
  1086. {
  1087. ParticleListNode* node = &nodeBuffer[i];
  1088. node->list = node;
  1089. node->next = NULL;
  1090. node->count = 1;
  1091. node->index = i + bufferIndex;
  1092. }
  1093. }
  1094. void b2ParticleSystem::MergeParticleListsInContact(
  1095. const b2ParticleGroup* group, ParticleListNode* nodeBuffer) const
  1096. {
  1097. int32 bufferIndex = group->GetBufferIndex();
  1098. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  1099. {
  1100. const b2ParticleContact& contact = m_contactBuffer[k];
  1101. int32 a = contact.GetIndexA();
  1102. int32 b = contact.GetIndexB();
  1103. if (!group->ContainsParticle(a) || !group->ContainsParticle(b)) {
  1104. continue;
  1105. }
  1106. ParticleListNode* listA = nodeBuffer[a - bufferIndex].list;
  1107. ParticleListNode* listB = nodeBuffer[b - bufferIndex].list;
  1108. if (listA == listB) {
  1109. continue;
  1110. }
  1111. // To minimize the cost of insertion, make sure listA is longer than
  1112. // listB.
  1113. if (listA->count < listB->count)
  1114. {
  1115. b2Swap(listA, listB);
  1116. }
  1117. b2Assert(listA->count >= listB->count);
  1118. MergeParticleLists(listA, listB);
  1119. }
  1120. }
  1121. void b2ParticleSystem::MergeParticleLists(
  1122. ParticleListNode* listA, ParticleListNode* listB)
  1123. {
  1124. // Insert listB between index 0 and 1 of listA
  1125. // Example:
  1126. // listA => a1 => a2 => a3 => NULL
  1127. // listB => b1 => b2 => NULL
  1128. // to
  1129. // listA => listB => b1 => b2 => a1 => a2 => a3 => NULL
  1130. b2Assert(listA != listB);
  1131. for (ParticleListNode* b = listB;;)
  1132. {
  1133. b->list = listA;
  1134. ParticleListNode* nextB = b->next;
  1135. if (nextB)
  1136. {
  1137. b = nextB;
  1138. }
  1139. else
  1140. {
  1141. b->next = listA->next;
  1142. break;
  1143. }
  1144. }
  1145. listA->next = listB;
  1146. listA->count += listB->count;
  1147. listB->count = 0;
  1148. }
  1149. b2ParticleSystem::ParticleListNode* b2ParticleSystem::FindLongestParticleList(
  1150. const b2ParticleGroup* group, ParticleListNode* nodeBuffer)
  1151. {
  1152. int32 particleCount = group->GetParticleCount();
  1153. ParticleListNode* result = nodeBuffer;
  1154. for (int32 i = 0; i < particleCount; i++)
  1155. {
  1156. ParticleListNode* node = &nodeBuffer[i];
  1157. if (result->count < node->count)
  1158. {
  1159. result = node;
  1160. }
  1161. }
  1162. return result;
  1163. }
  1164. void b2ParticleSystem::MergeZombieParticleListNodes(
  1165. const b2ParticleGroup* group, ParticleListNode* nodeBuffer,
  1166. ParticleListNode* survivingList) const
  1167. {
  1168. int32 particleCount = group->GetParticleCount();
  1169. for (int32 i = 0; i < particleCount; i++)
  1170. {
  1171. ParticleListNode* node = &nodeBuffer[i];
  1172. if (node != survivingList &&
  1173. (m_flagsBuffer.data[node->index] & b2_zombieParticle))
  1174. {
  1175. MergeParticleListAndNode(survivingList, node);
  1176. }
  1177. }
  1178. }
  1179. void b2ParticleSystem::MergeParticleListAndNode(
  1180. ParticleListNode* list, ParticleListNode* node)
  1181. {
  1182. // Insert node between index 0 and 1 of list
  1183. // Example:
  1184. // list => a1 => a2 => a3 => NULL
  1185. // node => NULL
  1186. // to
  1187. // list => node => a1 => a2 => a3 => NULL
  1188. b2Assert(node != list);
  1189. b2Assert(node->list == node);
  1190. b2Assert(node->count == 1);
  1191. node->list = list;
  1192. node->next = list->next;
  1193. list->next = node;
  1194. list->count++;
  1195. node->count = 0;
  1196. }
  1197. void b2ParticleSystem::CreateParticleGroupsFromParticleList(
  1198. const b2ParticleGroup* group, ParticleListNode* nodeBuffer,
  1199. const ParticleListNode* survivingList)
  1200. {
  1201. int32 particleCount = group->GetParticleCount();
  1202. b2ParticleGroupDef def;
  1203. def.groupFlags = group->GetGroupFlags();
  1204. def.userData = group->GetUserData();
  1205. for (int32 i = 0; i < particleCount; i++)
  1206. {
  1207. ParticleListNode* list = &nodeBuffer[i];
  1208. if (!list->count || list == survivingList)
  1209. {
  1210. continue;
  1211. }
  1212. b2Assert(list->list == list);
  1213. b2ParticleGroup* newGroup = CreateParticleGroup(def);
  1214. for (ParticleListNode* node = list; node; node = node->next)
  1215. {
  1216. int32 oldIndex = node->index;
  1217. uint32& flags = m_flagsBuffer.data[oldIndex];
  1218. b2Assert(!(flags & b2_zombieParticle));
  1219. int32 newIndex = CloneParticle(oldIndex, newGroup);
  1220. flags |= b2_zombieParticle;
  1221. node->index = newIndex;
  1222. }
  1223. }
  1224. }
  1225. void b2ParticleSystem::UpdatePairsAndTriadsWithParticleList(
  1226. const b2ParticleGroup* group, const ParticleListNode* nodeBuffer)
  1227. {
  1228. int32 bufferIndex = group->GetBufferIndex();
  1229. // Update indices in pairs and triads. If an index belongs to the group,
  1230. // replace it with the corresponding value in nodeBuffer.
  1231. // Note that nodeBuffer is allocated only for the group and the index should
  1232. // be shifted by bufferIndex.
  1233. for (int32 k = 0; k < m_pairBuffer.GetCount(); k++)
  1234. {
  1235. b2ParticlePair& pair = m_pairBuffer[k];
  1236. int32 a = pair.indexA;
  1237. int32 b = pair.indexB;
  1238. if (group->ContainsParticle(a))
  1239. {
  1240. pair.indexA = nodeBuffer[a - bufferIndex].index;
  1241. }
  1242. if (group->ContainsParticle(b))
  1243. {
  1244. pair.indexB = nodeBuffer[b - bufferIndex].index;
  1245. }
  1246. }
  1247. for (int32 k = 0; k < m_triadBuffer.GetCount(); k++)
  1248. {
  1249. b2ParticleTriad& triad = m_triadBuffer[k];
  1250. int32 a = triad.indexA;
  1251. int32 b = triad.indexB;
  1252. int32 c = triad.indexC;
  1253. if (group->ContainsParticle(a))
  1254. {
  1255. triad.indexA = nodeBuffer[a - bufferIndex].index;
  1256. }
  1257. if (group->ContainsParticle(b))
  1258. {
  1259. triad.indexB = nodeBuffer[b - bufferIndex].index;
  1260. }
  1261. if (group->ContainsParticle(c))
  1262. {
  1263. triad.indexC = nodeBuffer[c - bufferIndex].index;
  1264. }
  1265. }
  1266. }
  1267. int32 b2ParticleSystem::CloneParticle(int32 oldIndex, b2ParticleGroup* group)
  1268. {
  1269. b2ParticleDef def;
  1270. def.flags = m_flagsBuffer.data[oldIndex];
  1271. def.position = m_positionBuffer.data[oldIndex];
  1272. def.velocity = m_velocityBuffer.data[oldIndex];
  1273. if (m_colorBuffer.data)
  1274. {
  1275. def.color = m_colorBuffer.data[oldIndex];
  1276. }
  1277. if (m_userDataBuffer.data)
  1278. {
  1279. def.userData = m_userDataBuffer.data[oldIndex];
  1280. }
  1281. def.group = group;
  1282. int32 newIndex = CreateParticle(def);
  1283. if (m_handleIndexBuffer.data)
  1284. {
  1285. b2ParticleHandle* handle = m_handleIndexBuffer.data[oldIndex];
  1286. if (handle) handle->SetIndex(newIndex);
  1287. m_handleIndexBuffer.data[newIndex] = handle;
  1288. m_handleIndexBuffer.data[oldIndex] = NULL;
  1289. }
  1290. if (m_lastBodyContactStepBuffer.data)
  1291. {
  1292. m_lastBodyContactStepBuffer.data[newIndex] =
  1293. m_lastBodyContactStepBuffer.data[oldIndex];
  1294. }
  1295. if (m_bodyContactCountBuffer.data)
  1296. {
  1297. m_bodyContactCountBuffer.data[newIndex] =
  1298. m_bodyContactCountBuffer.data[oldIndex];
  1299. }
  1300. if (m_consecutiveContactStepsBuffer.data)
  1301. {
  1302. m_consecutiveContactStepsBuffer.data[newIndex] =
  1303. m_consecutiveContactStepsBuffer.data[oldIndex];
  1304. }
  1305. if (m_hasForce)
  1306. {
  1307. m_forceBuffer[newIndex] = m_forceBuffer[oldIndex];
  1308. }
  1309. if (m_staticPressureBuffer)
  1310. {
  1311. m_staticPressureBuffer[newIndex] = m_staticPressureBuffer[oldIndex];
  1312. }
  1313. if (m_depthBuffer)
  1314. {
  1315. m_depthBuffer[newIndex] = m_depthBuffer[oldIndex];
  1316. }
  1317. if (m_expirationTimeBuffer.data)
  1318. {
  1319. m_expirationTimeBuffer.data[newIndex] =
  1320. m_expirationTimeBuffer.data[oldIndex];
  1321. }
  1322. return newIndex;
  1323. }
  1324. void b2ParticleSystem::UpdatePairsAndTriadsWithReactiveParticles()
  1325. {
  1326. class ReactiveFilter : public ConnectionFilter
  1327. {
  1328. bool IsNecessary(int32 index) const
  1329. {
  1330. return (m_flagsBuffer[index] & b2_reactiveParticle) != 0;
  1331. }
  1332. const uint32* m_flagsBuffer;
  1333. public:
  1334. ReactiveFilter(uint32* flagsBuffer)
  1335. {
  1336. m_flagsBuffer = flagsBuffer;
  1337. }
  1338. } filter(m_flagsBuffer.data);
  1339. UpdatePairsAndTriads(0, m_count, filter);
  1340. for (int32 i = 0; i < m_count; i++)
  1341. {
  1342. m_flagsBuffer.data[i] &= ~b2_reactiveParticle;
  1343. }
  1344. m_allParticleFlags &= ~b2_reactiveParticle;
  1345. }
  1346. static bool ParticleCanBeConnected(
  1347. uint32 flags, b2ParticleGroup* group)
  1348. {
  1349. return
  1350. (flags & (b2_wallParticle | b2_springParticle | b2_elasticParticle)) ||
  1351. (group && group->GetGroupFlags() & b2_rigidParticleGroup);
  1352. }
  1353. void b2ParticleSystem::UpdatePairsAndTriads(
  1354. int32 firstIndex, int32 lastIndex, const ConnectionFilter& filter)
  1355. {
  1356. // Create pairs or triads.
  1357. // All particles in each pair/triad should satisfy the following:
  1358. // * firstIndex <= index < lastIndex
  1359. // * don't have b2_zombieParticle
  1360. // * ParticleCanBeConnected returns true
  1361. // * ShouldCreatePair/ShouldCreateTriad returns true
  1362. // Any particles in each pair/triad should satisfy the following:
  1363. // * filter.IsNeeded returns true
  1364. // * have one of k_pairFlags/k_triadsFlags
  1365. b2Assert(firstIndex <= lastIndex);
  1366. uint32 particleFlags = 0;
  1367. for (int32 i = firstIndex; i < lastIndex; i++)
  1368. {
  1369. particleFlags |= m_flagsBuffer.data[i];
  1370. }
  1371. if (particleFlags & k_pairFlags)
  1372. {
  1373. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  1374. {
  1375. const b2ParticleContact& contact = m_contactBuffer[k];
  1376. int32 a = contact.GetIndexA();
  1377. int32 b = contact.GetIndexB();
  1378. uint32 af = m_flagsBuffer.data[a];
  1379. uint32 bf = m_flagsBuffer.data[b];
  1380. b2ParticleGroup* groupA = m_groupBuffer[a];
  1381. b2ParticleGroup* groupB = m_groupBuffer[b];
  1382. if (a >= firstIndex && a < lastIndex &&
  1383. b >= firstIndex && b < lastIndex &&
  1384. !((af | bf) & b2_zombieParticle) &&
  1385. ((af | bf) & k_pairFlags) &&
  1386. (filter.IsNecessary(a) || filter.IsNecessary(b)) &&
  1387. ParticleCanBeConnected(af, groupA) &&
  1388. ParticleCanBeConnected(bf, groupB) &&
  1389. filter.ShouldCreatePair(a, b))
  1390. {
  1391. b2ParticlePair& pair = m_pairBuffer.Append();
  1392. pair.indexA = a;
  1393. pair.indexB = b;
  1394. pair.flags = contact.GetFlags();
  1395. pair.strength = b2Min(
  1396. groupA ? groupA->m_strength : 1,
  1397. groupB ? groupB->m_strength : 1);
  1398. pair.distance = b2Distance(m_positionBuffer.data[a],
  1399. m_positionBuffer.data[b]);
  1400. }
  1401. }
  1402. std::stable_sort(
  1403. m_pairBuffer.Begin(), m_pairBuffer.End(), ComparePairIndices);
  1404. m_pairBuffer.Unique(MatchPairIndices);
  1405. }
  1406. if (particleFlags & k_triadFlags)
  1407. {
  1408. b2VoronoiDiagram diagram(
  1409. &m_world->m_stackAllocator, lastIndex - firstIndex);
  1410. for (int32 i = firstIndex; i < lastIndex; i++)
  1411. {
  1412. uint32 flags = m_flagsBuffer.data[i];
  1413. b2ParticleGroup* group = m_groupBuffer[i];
  1414. if (!(flags & b2_zombieParticle) &&
  1415. ParticleCanBeConnected(flags, group))
  1416. {
  1417. diagram.AddGenerator(
  1418. m_positionBuffer.data[i], i, filter.IsNecessary(i));
  1419. }
  1420. }
  1421. float32 stride = GetParticleStride();
  1422. diagram.Generate(stride / 2, stride * 2);
  1423. class UpdateTriadsCallback : public b2VoronoiDiagram::NodeCallback
  1424. {
  1425. void operator()(int32 a, int32 b, int32 c)
  1426. {
  1427. uint32 af = m_system->m_flagsBuffer.data[a];
  1428. uint32 bf = m_system->m_flagsBuffer.data[b];
  1429. uint32 cf = m_system->m_flagsBuffer.data[c];
  1430. if (((af | bf | cf) & k_triadFlags) &&
  1431. m_filter->ShouldCreateTriad(a, b, c))
  1432. {
  1433. const b2Vec2& pa = m_system->m_positionBuffer.data[a];
  1434. const b2Vec2& pb = m_system->m_positionBuffer.data[b];
  1435. const b2Vec2& pc = m_system->m_positionBuffer.data[c];
  1436. b2Vec2 dab = pa - pb;
  1437. b2Vec2 dbc = pb - pc;
  1438. b2Vec2 dca = pc - pa;
  1439. float32 maxDistanceSquared = b2_maxTriadDistanceSquared *
  1440. m_system->m_squaredDiameter;
  1441. if (b2Dot(dab, dab) > maxDistanceSquared ||
  1442. b2Dot(dbc, dbc) > maxDistanceSquared ||
  1443. b2Dot(dca, dca) > maxDistanceSquared)
  1444. {
  1445. return;
  1446. }
  1447. b2ParticleGroup* groupA = m_system->m_groupBuffer[a];
  1448. b2ParticleGroup* groupB = m_system->m_groupBuffer[b];
  1449. b2ParticleGroup* groupC = m_system->m_groupBuffer[c];
  1450. b2ParticleTriad& triad = m_system->m_triadBuffer.Append();
  1451. triad.indexA = a;
  1452. triad.indexB = b;
  1453. triad.indexC = c;
  1454. triad.flags = af | bf | cf;
  1455. triad.strength = b2Min(b2Min(
  1456. groupA ? groupA->m_strength : 1,
  1457. groupB ? groupB->m_strength : 1),
  1458. groupC ? groupC->m_strength : 1);
  1459. b2Vec2 midPoint = (float32) 1 / 3 * (pa + pb + pc);
  1460. triad.pa = pa - midPoint;
  1461. triad.pb = pb - midPoint;
  1462. triad.pc = pc - midPoint;
  1463. triad.ka = -b2Dot(dca, dab);
  1464. triad.kb = -b2Dot(dab, dbc);
  1465. triad.kc = -b2Dot(dbc, dca);
  1466. triad.s = b2Cross(pa, pb) + b2Cross(pb, pc) + b2Cross(pc, pa);
  1467. }
  1468. }
  1469. b2ParticleSystem* m_system;
  1470. const ConnectionFilter* m_filter;
  1471. public:
  1472. UpdateTriadsCallback(
  1473. b2ParticleSystem* system, const ConnectionFilter* filter)
  1474. {
  1475. m_system = system;
  1476. m_filter = filter;
  1477. }
  1478. } callback(this, &filter);
  1479. diagram.GetNodes(callback);
  1480. std::stable_sort(
  1481. m_triadBuffer.Begin(), m_triadBuffer.End(), CompareTriadIndices);
  1482. m_triadBuffer.Unique(MatchTriadIndices);
  1483. }
  1484. }
  1485. bool b2ParticleSystem::ComparePairIndices(
  1486. const b2ParticlePair& a, const b2ParticlePair& b)
  1487. {
  1488. int32 diffA = a.indexA - b.indexA;
  1489. if (diffA != 0) return diffA < 0;
  1490. return a.indexB < b.indexB;
  1491. }
  1492. bool b2ParticleSystem::MatchPairIndices(
  1493. const b2ParticlePair& a, const b2ParticlePair& b)
  1494. {
  1495. return a.indexA == b.indexA && a.indexB == b.indexB;
  1496. }
  1497. bool b2ParticleSystem::CompareTriadIndices(
  1498. const b2ParticleTriad& a, const b2ParticleTriad& b)
  1499. {
  1500. int32 diffA = a.indexA - b.indexA;
  1501. if (diffA != 0) return diffA < 0;
  1502. int32 diffB = a.indexB - b.indexB;
  1503. if (diffB != 0) return diffB < 0;
  1504. return a.indexC < b.indexC;
  1505. }
  1506. bool b2ParticleSystem::MatchTriadIndices(
  1507. const b2ParticleTriad& a, const b2ParticleTriad& b)
  1508. {
  1509. return a.indexA == b.indexA && a.indexB == b.indexB && a.indexC == b.indexC;
  1510. }
  1511. // Only called from SolveZombie() or JoinParticleGroups().
  1512. void b2ParticleSystem::DestroyParticleGroup(b2ParticleGroup* group)
  1513. {
  1514. b2Assert(m_groupCount > 0);
  1515. b2Assert(group);
  1516. if (m_world->m_destructionListener)
  1517. {
  1518. m_world->m_destructionListener->SayGoodbye(group);
  1519. }
  1520. SetGroupFlags(group, 0);
  1521. for (int32 i = group->m_firstIndex; i < group->m_lastIndex; i++)
  1522. {
  1523. m_groupBuffer[i] = NULL;
  1524. }
  1525. if (group->m_prev)
  1526. {
  1527. group->m_prev->m_next = group->m_next;
  1528. }
  1529. if (group->m_next)
  1530. {
  1531. group->m_next->m_prev = group->m_prev;
  1532. }
  1533. if (group == m_groupList)
  1534. {
  1535. m_groupList = group->m_next;
  1536. }
  1537. --m_groupCount;
  1538. group->~b2ParticleGroup();
  1539. m_world->m_blockAllocator.Free(group, sizeof(b2ParticleGroup));
  1540. }
  1541. void b2ParticleSystem::ComputeWeight()
  1542. {
  1543. // calculates the sum of contact-weights for each particle
  1544. // that means dimensionless density
  1545. memset(m_weightBuffer, 0, sizeof(*m_weightBuffer) * m_count);
  1546. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  1547. {
  1548. const b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  1549. int32 a = contact.index;
  1550. float32 w = contact.weight;
  1551. m_weightBuffer[a] += w;
  1552. }
  1553. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  1554. {
  1555. const b2ParticleContact& contact = m_contactBuffer[k];
  1556. int32 a = contact.GetIndexA();
  1557. int32 b = contact.GetIndexB();
  1558. float32 w = contact.GetWeight();
  1559. m_weightBuffer[a] += w;
  1560. m_weightBuffer[b] += w;
  1561. }
  1562. }
  1563. void b2ParticleSystem::ComputeDepth()
  1564. {
  1565. b2ParticleContact* contactGroups = (b2ParticleContact*) m_world->
  1566. m_stackAllocator.Allocate(sizeof(b2ParticleContact) * m_contactBuffer.GetCount());
  1567. int32 contactGroupsCount = 0;
  1568. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  1569. {
  1570. const b2ParticleContact& contact = m_contactBuffer[k];
  1571. int32 a = contact.GetIndexA();
  1572. int32 b = contact.GetIndexB();
  1573. const b2ParticleGroup* groupA = m_groupBuffer[a];
  1574. const b2ParticleGroup* groupB = m_groupBuffer[b];
  1575. if (groupA && groupA == groupB &&
  1576. (groupA->m_groupFlags & b2_particleGroupNeedsUpdateDepth))
  1577. {
  1578. contactGroups[contactGroupsCount++] = contact;
  1579. }
  1580. }
  1581. b2ParticleGroup** groupsToUpdate = (b2ParticleGroup**) m_world->
  1582. m_stackAllocator.Allocate(sizeof(b2ParticleGroup*) * m_groupCount);
  1583. int32 groupsToUpdateCount = 0;
  1584. for (b2ParticleGroup* group = m_groupList; group; group = group->GetNext())
  1585. {
  1586. if (group->m_groupFlags & b2_particleGroupNeedsUpdateDepth)
  1587. {
  1588. groupsToUpdate[groupsToUpdateCount++] = group;
  1589. SetGroupFlags(group,
  1590. group->m_groupFlags &
  1591. ~b2_particleGroupNeedsUpdateDepth);
  1592. for (int32 i = group->m_firstIndex; i < group->m_lastIndex; i++)
  1593. {
  1594. m_accumulationBuffer[i] = 0;
  1595. }
  1596. }
  1597. }
  1598. // Compute sum of weight of contacts except between different groups.
  1599. for (int32 k = 0; k < contactGroupsCount; k++)
  1600. {
  1601. const b2ParticleContact& contact = contactGroups[k];
  1602. int32 a = contact.GetIndexA();
  1603. int32 b = contact.GetIndexB();
  1604. float32 w = contact.GetWeight();
  1605. m_accumulationBuffer[a] += w;
  1606. m_accumulationBuffer[b] += w;
  1607. }
  1608. b2Assert(m_depthBuffer);
  1609. for (int32 i = 0; i < groupsToUpdateCount; i++)
  1610. {
  1611. const b2ParticleGroup* group = groupsToUpdate[i];
  1612. for (int32 i = group->m_firstIndex; i < group->m_lastIndex; i++)
  1613. {
  1614. float32 w = m_accumulationBuffer[i];
  1615. m_depthBuffer[i] = w < 0.8f ? 0 : b2_maxFloat;
  1616. }
  1617. }
  1618. // The number of iterations is equal to particle number from the deepest
  1619. // particle to the nearest surface particle, and in general it is smaller
  1620. // than sqrt of total particle number.
  1621. int32 iterationCount = (int32)b2Sqrt((float)m_count);
  1622. for (int32 t = 0; t < iterationCount; t++)
  1623. {
  1624. bool updated = false;
  1625. for (int32 k = 0; k < contactGroupsCount; k++)
  1626. {
  1627. const b2ParticleContact& contact = contactGroups[k];
  1628. int32 a = contact.GetIndexA();
  1629. int32 b = contact.GetIndexB();
  1630. float32 r = 1 - contact.GetWeight();
  1631. float32& ap0 = m_depthBuffer[a];
  1632. float32& bp0 = m_depthBuffer[b];
  1633. float32 ap1 = bp0 + r;
  1634. float32 bp1 = ap0 + r;
  1635. if (ap0 > ap1)
  1636. {
  1637. ap0 = ap1;
  1638. updated = true;
  1639. }
  1640. if (bp0 > bp1)
  1641. {
  1642. bp0 = bp1;
  1643. updated = true;
  1644. }
  1645. }
  1646. if (!updated)
  1647. {
  1648. break;
  1649. }
  1650. }
  1651. for (int32 i = 0; i < groupsToUpdateCount; i++)
  1652. {
  1653. const b2ParticleGroup* group = groupsToUpdate[i];
  1654. for (int32 i = group->m_firstIndex; i < group->m_lastIndex; i++)
  1655. {
  1656. float32& p = m_depthBuffer[i];
  1657. if (p < b2_maxFloat)
  1658. {
  1659. p *= m_particleDiameter;
  1660. }
  1661. else
  1662. {
  1663. p = 0;
  1664. }
  1665. }
  1666. }
  1667. m_world->m_stackAllocator.Free(groupsToUpdate);
  1668. m_world->m_stackAllocator.Free(contactGroups);
  1669. }
  1670. b2ParticleSystem::InsideBoundsEnumerator
  1671. b2ParticleSystem::GetInsideBoundsEnumerator(const b2AABB& aabb) const
  1672. {
  1673. uint32 lowerTag = computeTag(m_inverseDiameter * aabb.lowerBound.x - 1,
  1674. m_inverseDiameter * aabb.lowerBound.y - 1);
  1675. uint32 upperTag = computeTag(m_inverseDiameter * aabb.upperBound.x + 1,
  1676. m_inverseDiameter * aabb.upperBound.y + 1);
  1677. const Proxy* beginProxy = m_proxyBuffer.Begin();
  1678. const Proxy* endProxy = m_proxyBuffer.End();
  1679. const Proxy* firstProxy = std::lower_bound(beginProxy, endProxy, lowerTag);
  1680. const Proxy* lastProxy = std::upper_bound(firstProxy, endProxy, upperTag);
  1681. return InsideBoundsEnumerator(lowerTag, upperTag, firstProxy, lastProxy);
  1682. }
  1683. inline void b2ParticleSystem::AddContact(int32 a, int32 b,
  1684. b2GrowableBuffer<b2ParticleContact>& contacts) const
  1685. {
  1686. b2Vec2 d = m_positionBuffer.data[b] - m_positionBuffer.data[a];
  1687. float32 distBtParticlesSq = b2Dot(d, d);
  1688. if (distBtParticlesSq < m_squaredDiameter)
  1689. {
  1690. float32 invD = b2InvSqrt(distBtParticlesSq);
  1691. b2ParticleContact& contact = contacts.Append();
  1692. contact.SetIndices(a, b);
  1693. contact.SetFlags(m_flagsBuffer.data[a] | m_flagsBuffer.data[b]);
  1694. // 1 - distBtParticles / diameter
  1695. contact.SetWeight(1 - distBtParticlesSq * invD * m_inverseDiameter);
  1696. contact.SetNormal(invD * d);
  1697. }
  1698. }
  1699. void b2ParticleSystem::FindContacts_Reference(
  1700. b2GrowableBuffer<b2ParticleContact>& contacts) const
  1701. {
  1702. const Proxy* beginProxy = m_proxyBuffer.Begin();
  1703. const Proxy* endProxy = m_proxyBuffer.End();
  1704. contacts.SetCount(0);
  1705. for (const Proxy *a = beginProxy, *c = beginProxy; a < endProxy; a++)
  1706. {
  1707. uint32 rightTag = computeRelativeTag(a->tag, 1, 0);
  1708. for (const Proxy* b = a + 1; b < endProxy; b++)
  1709. {
  1710. if (rightTag < b->tag) break;
  1711. AddContact(a->index, b->index, contacts);
  1712. }
  1713. uint32 bottomLeftTag = computeRelativeTag(a->tag, -1, 1);
  1714. for (; c < endProxy; c++)
  1715. {
  1716. if (bottomLeftTag <= c->tag) break;
  1717. }
  1718. uint32 bottomRightTag = computeRelativeTag(a->tag, 1, 1);
  1719. for (const Proxy* b = c; b < endProxy; b++)
  1720. {
  1721. if (bottomRightTag < b->tag) break;
  1722. AddContact(a->index, b->index, contacts);
  1723. }
  1724. }
  1725. }
  1726. // Put the positions and indices in proxy-order. This allows us to process
  1727. // particles with SIMD, since adjacent particles are adjacent in memory.
  1728. void b2ParticleSystem::ReorderForFindContact(FindContactInput* reordered,
  1729. int alignedCount) const
  1730. {
  1731. int i = 0;
  1732. for (; i < m_count; ++i)
  1733. {
  1734. const int proxyIndex = m_proxyBuffer[i].index;
  1735. FindContactInput& r = reordered[i];
  1736. r.proxyIndex = proxyIndex;
  1737. r.position = m_positionBuffer.data[proxyIndex];
  1738. }
  1739. // We process multiple elements at a time, so we may read off the end of
  1740. // the array. Pad the array with a few elements, so we don't end up
  1741. // outputing spurious contacts.
  1742. for (; i < alignedCount; ++i)
  1743. {
  1744. FindContactInput& r = reordered[i];
  1745. r.proxyIndex = 0;
  1746. r.position = b2Vec2(b2_maxFloat, b2_maxFloat);
  1747. }
  1748. }
  1749. // Check particles to the right of 'startIndex', outputing FindContactChecks
  1750. // until we find an index that is greater than 'bound'. We skip over the
  1751. // indices NUM_V32_SLOTS at a time, because they are processed in groups
  1752. // in the SIMD function.
  1753. inline void b2ParticleSystem::GatherChecksOneParticle(
  1754. const uint32 bound,
  1755. const int startIndex,
  1756. const int particleIndex,
  1757. int* nextUncheckedIndex,
  1758. b2GrowableBuffer<FindContactCheck>& checks) const
  1759. {
  1760. // The particles have to be heavily packed together in order for this
  1761. // loop to iterate more than once. In almost all situations, it will
  1762. // iterate less than twice.
  1763. for (int comparatorIndex = startIndex;
  1764. comparatorIndex < m_count;
  1765. comparatorIndex += NUM_V32_SLOTS)
  1766. {
  1767. if (m_proxyBuffer[comparatorIndex].tag > bound)
  1768. break;
  1769. FindContactCheck& out = checks.Append();
  1770. out.particleIndex = (uint16)particleIndex;
  1771. out.comparatorIndex = (uint16)comparatorIndex;
  1772. // This is faster inside the 'for' since there are so few iterations.
  1773. if (nextUncheckedIndex != NULL)
  1774. {
  1775. *nextUncheckedIndex = comparatorIndex + NUM_V32_SLOTS;
  1776. }
  1777. }
  1778. }
  1779. void b2ParticleSystem::GatherChecks(
  1780. b2GrowableBuffer<FindContactCheck>& checks) const
  1781. {
  1782. int bottomLeftIndex = 0;
  1783. for (int particleIndex = 0; particleIndex < m_count; ++particleIndex)
  1784. {
  1785. const uint32 particleTag = m_proxyBuffer[particleIndex].tag;
  1786. // Add checks for particles to the right.
  1787. const uint32 rightBound = particleTag + relativeTagRight;
  1788. int nextUncheckedIndex = particleIndex + 1;
  1789. GatherChecksOneParticle(rightBound,
  1790. particleIndex + 1,
  1791. particleIndex,
  1792. &nextUncheckedIndex,
  1793. checks);
  1794. // Find comparator index below and to left of particle.
  1795. const uint32 bottomLeftTag = particleTag + relativeTagBottomLeft;
  1796. for (; bottomLeftIndex < m_count; ++bottomLeftIndex)
  1797. {
  1798. if (bottomLeftTag <= m_proxyBuffer[bottomLeftIndex].tag)
  1799. break;
  1800. }
  1801. // Add checks for particles below.
  1802. const uint32 bottomRightBound = particleTag + relativeTagBottomRight;
  1803. const int bottomStartIndex = b2Max(bottomLeftIndex, nextUncheckedIndex);
  1804. GatherChecksOneParticle(bottomRightBound,
  1805. bottomStartIndex,
  1806. particleIndex,
  1807. NULL,
  1808. checks);
  1809. }
  1810. }
  1811. #if defined(LIQUIDFUN_SIMD_NEON)
  1812. void b2ParticleSystem::FindContacts_Simd(
  1813. b2GrowableBuffer<b2ParticleContact>& contacts) const
  1814. {
  1815. contacts.SetCount(0);
  1816. const int alignedCount = m_count + NUM_V32_SLOTS;
  1817. FindContactInput* reordered = (FindContactInput*)
  1818. m_world->m_stackAllocator.Allocate(
  1819. sizeof(FindContactInput) * alignedCount);
  1820. // Put positions and indices into proxy-order.
  1821. // This allows us to efficiently check for contacts using SIMD.
  1822. ReorderForFindContact(reordered, alignedCount);
  1823. // Perform broad-band contact check using tags to approximate
  1824. // positions. This reduces the number of narrow-band contact checks
  1825. // that use actual positions.
  1826. static const int MAX_EXPECTED_CHECKS_PER_PARTICLE = 3;
  1827. b2GrowableBuffer<FindContactCheck> checks(m_world->m_blockAllocator);
  1828. checks.Reserve(MAX_EXPECTED_CHECKS_PER_PARTICLE * m_count);
  1829. GatherChecks(checks);
  1830. // Perform narrow-band contact checks using actual positions.
  1831. // Any particles whose centers are within one diameter of each other are
  1832. // considered contacting.
  1833. FindContactsFromChecks_Simd(reordered, checks.Data(), checks.GetCount(),
  1834. m_squaredDiameter, m_inverseDiameter,
  1835. m_flagsBuffer.data, contacts);
  1836. m_world->m_stackAllocator.Free(reordered);
  1837. }
  1838. #endif // defined(LIQUIDFUN_SIMD_NEON)
  1839. LIQUIDFUN_SIMD_INLINE
  1840. void b2ParticleSystem::FindContacts(
  1841. b2GrowableBuffer<b2ParticleContact>& contacts) const
  1842. {
  1843. #if defined(LIQUIDFUN_SIMD_NEON)
  1844. FindContacts_Simd(contacts);
  1845. #else
  1846. FindContacts_Reference(contacts);
  1847. #endif
  1848. #if defined(LIQUIDFUN_SIMD_TEST_VS_REFERENCE)
  1849. b2GrowableBuffer<b2ParticleContact>
  1850. reference(m_world->m_blockAllocator);
  1851. FindContacts_Reference(reference);
  1852. b2Assert(contacts.GetCount() == reference.GetCount());
  1853. for (int32 i = 0; i < contacts.GetCount(); ++i)
  1854. {
  1855. b2Assert(contacts[i].ApproximatelyEqual(reference[i]));
  1856. }
  1857. #endif // defined(LIQUIDFUN_SIMD_TEST_VS_REFERENCE)
  1858. }
  1859. static inline bool b2ParticleContactIsZombie(const b2ParticleContact& contact)
  1860. {
  1861. return (contact.GetFlags() & b2_zombieParticle) == b2_zombieParticle;
  1862. }
  1863. // Get the world's contact filter if any particles with the
  1864. // b2_particleContactFilterParticle flag are present in the system.
  1865. inline b2ContactFilter* b2ParticleSystem::GetParticleContactFilter() const
  1866. {
  1867. return (m_allParticleFlags & b2_particleContactFilterParticle) ?
  1868. m_world->m_contactManager.m_contactFilter : NULL;
  1869. }
  1870. // Get the world's contact listener if any particles with the
  1871. // b2_particleContactListenerParticle flag are present in the system.
  1872. inline b2ContactListener* b2ParticleSystem::GetParticleContactListener() const
  1873. {
  1874. return (m_allParticleFlags & b2_particleContactListenerParticle) ?
  1875. m_world->m_contactManager.m_contactListener : NULL;
  1876. }
  1877. // Recalculate 'tag' in proxies using m_positionBuffer.
  1878. // The 'tag' is an approximation of position, in left-right, top-bottom order.
  1879. void b2ParticleSystem::UpdateProxies_Reference(
  1880. b2GrowableBuffer<Proxy>& proxies) const
  1881. {
  1882. const Proxy* const endProxy = proxies.End();
  1883. for (Proxy* proxy = proxies.Begin(); proxy < endProxy; ++proxy)
  1884. {
  1885. int32 i = proxy->index;
  1886. b2Vec2 p = m_positionBuffer.data[i];
  1887. proxy->tag = computeTag(m_inverseDiameter * p.x,
  1888. m_inverseDiameter * p.y);
  1889. }
  1890. }
  1891. #if defined(LIQUIDFUN_SIMD_NEON)
  1892. // static
  1893. void b2ParticleSystem::UpdateProxyTags(
  1894. const uint32* const tags,
  1895. b2GrowableBuffer<Proxy>& proxies)
  1896. {
  1897. const Proxy* const endProxy = proxies.End();
  1898. for (Proxy* proxy = proxies.Begin(); proxy < endProxy; ++proxy)
  1899. {
  1900. proxy->tag = tags[proxy->index];
  1901. }
  1902. }
  1903. void b2ParticleSystem::UpdateProxies_Simd(
  1904. b2GrowableBuffer<Proxy>& proxies) const
  1905. {
  1906. uint32* tags = (uint32*)
  1907. m_world->m_stackAllocator.Allocate(m_count * sizeof(uint32));
  1908. // Calculate tag for every position.
  1909. // 'tags' array is in position-order.
  1910. CalculateTags_Simd(m_positionBuffer.data, m_count,
  1911. m_inverseDiameter, tags);
  1912. // Update 'tag' element in the 'proxies' array to the new values.
  1913. UpdateProxyTags(tags, proxies);
  1914. m_world->m_stackAllocator.Free(tags);
  1915. }
  1916. #endif // defined(LIQUIDFUN_SIMD_NEON)
  1917. // static
  1918. bool b2ParticleSystem::ProxyBufferHasIndex(
  1919. int32 index, const Proxy* const a, int count)
  1920. {
  1921. for (int j = 0; j < count; ++j)
  1922. {
  1923. if (a[j].index == index)
  1924. return true;
  1925. }
  1926. return false;
  1927. }
  1928. // static
  1929. int b2ParticleSystem::NumProxiesWithSameTag(
  1930. const Proxy* const a, const Proxy* const b, int count)
  1931. {
  1932. const uint32 tag = a[0].tag;
  1933. for (int num = 0; num < count; ++num)
  1934. {
  1935. if (a[num].tag != tag || b[num].tag != tag)
  1936. return num;
  1937. }
  1938. return count;
  1939. }
  1940. // Precondition: both 'a' and 'b' should be sorted by tag, but don't need to be
  1941. // sorted by index.
  1942. // static
  1943. bool b2ParticleSystem::AreProxyBuffersTheSame(const b2GrowableBuffer<Proxy>& a,
  1944. const b2GrowableBuffer<Proxy>& b)
  1945. {
  1946. if (a.GetCount() != b.GetCount())
  1947. return false;
  1948. // A given tag may have several indices. The order of these indices is
  1949. // not important, but the set must be equivalent.
  1950. for (int i = 0; i < a.GetCount();)
  1951. {
  1952. const int numWithSameTag = NumProxiesWithSameTag(
  1953. &a[i], &b[i], a.GetCount() - i);
  1954. if (numWithSameTag == 0)
  1955. return false;
  1956. for (int j = 0; j < numWithSameTag; ++j)
  1957. {
  1958. const bool hasIndex = ProxyBufferHasIndex(
  1959. a[i + j].index, &b[i], numWithSameTag);
  1960. if (!hasIndex)
  1961. return false;
  1962. }
  1963. i += numWithSameTag;
  1964. }
  1965. return true;
  1966. }
  1967. LIQUIDFUN_SIMD_INLINE
  1968. void b2ParticleSystem::UpdateProxies(
  1969. b2GrowableBuffer<Proxy>& proxies) const
  1970. {
  1971. #if defined(LIQUIDFUN_SIMD_TEST_VS_REFERENCE)
  1972. b2GrowableBuffer<Proxy> reference(proxies);
  1973. #endif
  1974. #if defined(LIQUIDFUN_SIMD_NEON)
  1975. UpdateProxies_Simd(proxies);
  1976. #else
  1977. UpdateProxies_Reference(proxies);
  1978. #endif
  1979. #if defined(LIQUIDFUN_SIMD_TEST_VS_REFERENCE)
  1980. UpdateProxies_Reference(reference);
  1981. b2Assert(AreProxyBuffersTheSame(proxies, reference));
  1982. #endif
  1983. }
  1984. // Sort the proxy array by 'tag'. This orders the particles into rows that
  1985. // run left-to-right, top-to-bottom. The rows are spaced m_particleDiameter
  1986. // apart, such that a particle in one row can only collide with the rows
  1987. // immediately above and below it. This ordering makes collision computation
  1988. // tractable.
  1989. //
  1990. // TODO OPT: The sort is a hot spot on the profiles. We could use SIMD to
  1991. // speed this up. See http://www.vldb.org/pvldb/1/1454171.pdf for an excellent
  1992. // explanation of a SIMD mergesort algorithm.
  1993. void b2ParticleSystem::SortProxies(b2GrowableBuffer<Proxy>& proxies) const
  1994. {
  1995. std::sort(proxies.Begin(), proxies.End());
  1996. }
  1997. class b2ParticleContactRemovePredicate
  1998. {
  1999. public:
  2000. b2ParticleContactRemovePredicate(
  2001. b2ParticleSystem* system,
  2002. b2ContactFilter* contactFilter) :
  2003. m_system(system),
  2004. m_contactFilter(contactFilter)
  2005. {}
  2006. bool operator()(const b2ParticleContact& contact)
  2007. {
  2008. return (contact.GetFlags() & b2_particleContactFilterParticle)
  2009. && !m_contactFilter->ShouldCollide(m_system, contact.GetIndexA(),
  2010. contact.GetIndexB());
  2011. }
  2012. private:
  2013. b2ParticleSystem* m_system;
  2014. b2ContactFilter* m_contactFilter;
  2015. };
  2016. // Only changes 'contacts', but the contact filter has a non-const 'this'
  2017. // pointer, so this member function cannot be const.
  2018. void b2ParticleSystem::FilterContacts(
  2019. b2GrowableBuffer<b2ParticleContact>& contacts)
  2020. {
  2021. // Optionally filter the contact.
  2022. b2ContactFilter* const contactFilter = GetParticleContactFilter();
  2023. if (contactFilter == NULL)
  2024. return;
  2025. contacts.RemoveIf(b2ParticleContactRemovePredicate(this, contactFilter));
  2026. }
  2027. void b2ParticleSystem::NotifyContactListenerPreContact(
  2028. b2ParticlePairSet* particlePairs) const
  2029. {
  2030. b2ContactListener* const contactListener = GetParticleContactListener();
  2031. if (contactListener == NULL)
  2032. return;
  2033. particlePairs->Initialize(m_contactBuffer.Begin(),
  2034. m_contactBuffer.GetCount(),
  2035. GetFlagsBuffer());
  2036. }
  2037. // Note: This function is not const because 'this' in BeginContact and
  2038. // EndContact callbacks must be non-const. However, this function itself
  2039. // does not change any internal data (though the callbacks might).
  2040. void b2ParticleSystem::NotifyContactListenerPostContact(
  2041. b2ParticlePairSet& particlePairs)
  2042. {
  2043. b2ContactListener* const contactListener = GetParticleContactListener();
  2044. if (contactListener == NULL)
  2045. return;
  2046. // Loop through all new contacts, reporting any new ones, and
  2047. // "invalidating" the ones that still exist.
  2048. const b2ParticleContact* const endContact = m_contactBuffer.End();
  2049. for (b2ParticleContact* contact = m_contactBuffer.Begin();
  2050. contact < endContact; ++contact)
  2051. {
  2052. ParticlePair pair;
  2053. pair.first = contact->GetIndexA();
  2054. pair.second = contact->GetIndexB();
  2055. const int32 itemIndex = particlePairs.Find(pair);
  2056. if (itemIndex >= 0)
  2057. {
  2058. // Already touching, ignore this contact.
  2059. particlePairs.Invalidate(itemIndex);
  2060. }
  2061. else
  2062. {
  2063. // Just started touching, inform the listener.
  2064. contactListener->BeginContact(this, contact);
  2065. }
  2066. }
  2067. // Report particles that are no longer touching.
  2068. // That is, any pairs that were not invalidated above.
  2069. const int32 pairCount = particlePairs.GetCount();
  2070. const ParticlePair* const pairs = particlePairs.GetBuffer();
  2071. const int8* const valid = particlePairs.GetValidBuffer();
  2072. for (int32 i = 0; i < pairCount; ++i)
  2073. {
  2074. if (valid[i])
  2075. {
  2076. contactListener->EndContact(this, pairs[i].first,
  2077. pairs[i].second);
  2078. }
  2079. }
  2080. }
  2081. void b2ParticleSystem::UpdateContacts(bool exceptZombie)
  2082. {
  2083. UpdateProxies(m_proxyBuffer);
  2084. SortProxies(m_proxyBuffer);
  2085. b2ParticlePairSet particlePairs(&m_world->m_stackAllocator);
  2086. NotifyContactListenerPreContact(&particlePairs);
  2087. FindContacts(m_contactBuffer);
  2088. FilterContacts(m_contactBuffer);
  2089. NotifyContactListenerPostContact(particlePairs);
  2090. if (exceptZombie)
  2091. {
  2092. m_contactBuffer.RemoveIf(b2ParticleContactIsZombie);
  2093. }
  2094. }
  2095. void b2ParticleSystem::DetectStuckParticle(int32 particle)
  2096. {
  2097. // Detect stuck particles
  2098. //
  2099. // The basic algorithm is to allow the user to specify an optional
  2100. // threshold where we detect whenever a particle is contacting
  2101. // more than one fixture for more than threshold consecutive
  2102. // steps. This is considered to be "stuck", and these are put
  2103. // in a list the user can query per step, if enabled, to deal with
  2104. // such particles.
  2105. if (m_stuckThreshold <= 0)
  2106. {
  2107. return;
  2108. }
  2109. // Get the state variables for this particle.
  2110. int32 * const consecutiveCount =
  2111. &m_consecutiveContactStepsBuffer.data[particle];
  2112. int32 * const lastStep = &m_lastBodyContactStepBuffer.data[particle];
  2113. int32 * const bodyCount = &m_bodyContactCountBuffer.data[particle];
  2114. // This is only called when there is a body contact for this particle.
  2115. ++(*bodyCount);
  2116. // We want to only trigger detection once per step, the first time we
  2117. // contact more than one fixture in a step for a given particle.
  2118. if (*bodyCount == 2)
  2119. {
  2120. ++(*consecutiveCount);
  2121. if (*consecutiveCount > m_stuckThreshold)
  2122. {
  2123. int32& newStuckParticle = m_stuckParticleBuffer.Append();
  2124. newStuckParticle = particle;
  2125. }
  2126. }
  2127. *lastStep = m_timestamp;
  2128. }
  2129. // Get the world's contact listener if any particles with the
  2130. // b2_fixtureContactListenerParticle flag are present in the system.
  2131. inline b2ContactListener* b2ParticleSystem::GetFixtureContactListener() const
  2132. {
  2133. return (m_allParticleFlags & b2_fixtureContactListenerParticle) ?
  2134. m_world->m_contactManager.m_contactListener : NULL;
  2135. }
  2136. // Get the world's contact filter if any particles with the
  2137. // b2_fixtureContactFilterParticle flag are present in the system.
  2138. inline b2ContactFilter* b2ParticleSystem::GetFixtureContactFilter() const
  2139. {
  2140. return (m_allParticleFlags & b2_fixtureContactFilterParticle) ?
  2141. m_world->m_contactManager.m_contactFilter : NULL;
  2142. }
  2143. /// Compute the axis-aligned bounding box for all particles contained
  2144. /// within this particle system.
  2145. /// @param aabb Returns the axis-aligned bounding box of the system.
  2146. void b2ParticleSystem::ComputeAABB(b2AABB* const aabb) const
  2147. {
  2148. const int32 particleCount = GetParticleCount();
  2149. b2Assert(aabb);
  2150. aabb->lowerBound.x = +b2_maxFloat;
  2151. aabb->lowerBound.y = +b2_maxFloat;
  2152. aabb->upperBound.x = -b2_maxFloat;
  2153. aabb->upperBound.y = -b2_maxFloat;
  2154. for (int32 i = 0; i < particleCount; i++)
  2155. {
  2156. b2Vec2 p = m_positionBuffer.data[i];
  2157. aabb->lowerBound = b2Min(aabb->lowerBound, p);
  2158. aabb->upperBound = b2Max(aabb->upperBound, p);
  2159. }
  2160. aabb->lowerBound.x -= m_particleDiameter;
  2161. aabb->lowerBound.y -= m_particleDiameter;
  2162. aabb->upperBound.x += m_particleDiameter;
  2163. aabb->upperBound.y += m_particleDiameter;
  2164. }
  2165. // Associate a memory allocator with this object.
  2166. FixedSetAllocator::FixedSetAllocator(
  2167. b2StackAllocator* allocator) :
  2168. m_buffer(NULL), m_valid(NULL), m_count(0), m_allocator(allocator)
  2169. {
  2170. b2Assert(allocator);
  2171. }
  2172. // Allocate internal storage for this object.
  2173. int32 FixedSetAllocator::Allocate(
  2174. const int32 itemSize, const int32 count)
  2175. {
  2176. Clear();
  2177. if (count)
  2178. {
  2179. m_buffer = m_allocator->Allocate(
  2180. (itemSize + sizeof(*m_valid)) * count);
  2181. b2Assert(m_buffer);
  2182. m_valid = (int8*)m_buffer + (itemSize * count);
  2183. memset(m_valid, 1, sizeof(*m_valid) * count);
  2184. m_count = count;
  2185. }
  2186. return m_count;
  2187. }
  2188. // Deallocate the internal buffer if it's allocated.
  2189. void FixedSetAllocator::Clear()
  2190. {
  2191. if (m_buffer)
  2192. {
  2193. m_allocator->Free(m_buffer);
  2194. m_buffer = NULL;
  2195. m_count = 0;
  2196. }
  2197. }
  2198. // Search set for item returning the index of the item if it's found, -1
  2199. // otherwise.
  2200. template<typename T>
  2201. static int32 FindItemIndexInFixedSet(const TypedFixedSetAllocator<T>& set,
  2202. const T& item)
  2203. {
  2204. if (set.GetCount())
  2205. {
  2206. const T* buffer = set.GetBuffer();
  2207. const T* last = buffer + set.GetCount();
  2208. const T* found = std::lower_bound( buffer, buffer + set.GetCount(),
  2209. item, T::Compare);
  2210. if( found != last )
  2211. {
  2212. return set.GetIndex( found );
  2213. }
  2214. }
  2215. return -1;
  2216. }
  2217. // Initialize from a set of particle / body contacts for particles
  2218. // that have the b2_fixtureContactListenerParticle flag set.
  2219. void FixtureParticleSet::Initialize(
  2220. const b2ParticleBodyContact * const bodyContacts,
  2221. const int32 numBodyContacts,
  2222. const uint32 * const particleFlagsBuffer)
  2223. {
  2224. Clear();
  2225. if (Allocate(numBodyContacts))
  2226. {
  2227. FixtureParticle* set = GetBuffer();
  2228. int32 insertedContacts = 0;
  2229. for (int32 i = 0; i < numBodyContacts; ++i)
  2230. {
  2231. FixtureParticle* const fixtureParticle = &set[i];
  2232. const b2ParticleBodyContact& bodyContact = bodyContacts[i];
  2233. if (bodyContact.index == b2_invalidParticleIndex ||
  2234. !(particleFlagsBuffer[bodyContact.index] &
  2235. b2_fixtureContactListenerParticle))
  2236. {
  2237. continue;
  2238. }
  2239. fixtureParticle->first = bodyContact.fixture;
  2240. fixtureParticle->second = bodyContact.index;
  2241. insertedContacts++;
  2242. }
  2243. SetCount(insertedContacts);
  2244. std::sort(set, set + insertedContacts, FixtureParticle::Compare);
  2245. }
  2246. }
  2247. // Find the index of a particle / fixture pair in the set or -1 if it's not
  2248. // present.
  2249. int32 FixtureParticleSet::Find(
  2250. const FixtureParticle& fixtureParticle) const
  2251. {
  2252. return FindItemIndexInFixedSet(*this, fixtureParticle);
  2253. }
  2254. // Initialize from a set of particle contacts.
  2255. void b2ParticlePairSet::Initialize(
  2256. const b2ParticleContact * const contacts, const int32 numContacts,
  2257. const uint32 * const particleFlagsBuffer)
  2258. {
  2259. Clear();
  2260. if (Allocate(numContacts))
  2261. {
  2262. ParticlePair* set = GetBuffer();
  2263. int32 insertedContacts = 0;
  2264. for (int32 i = 0; i < numContacts; ++i)
  2265. {
  2266. ParticlePair* const pair = &set[i];
  2267. const b2ParticleContact& contact = contacts[i];
  2268. if (contact.GetIndexA() == b2_invalidParticleIndex ||
  2269. contact.GetIndexB() == b2_invalidParticleIndex ||
  2270. !((particleFlagsBuffer[contact.GetIndexA()] |
  2271. particleFlagsBuffer[contact.GetIndexB()]) &
  2272. b2_particleContactListenerParticle))
  2273. {
  2274. continue;
  2275. }
  2276. pair->first = contact.GetIndexA();
  2277. pair->second = contact.GetIndexB();
  2278. insertedContacts++;
  2279. }
  2280. SetCount(insertedContacts);
  2281. std::sort(set, set + insertedContacts, ParticlePair::Compare);
  2282. }
  2283. }
  2284. // Find the index of a particle pair in the set or -1 if it's not present.
  2285. int32 b2ParticlePairSet::Find(const ParticlePair& pair) const
  2286. {
  2287. int32 index = FindItemIndexInFixedSet(*this, pair);
  2288. if (index < 0)
  2289. {
  2290. ParticlePair swapped;
  2291. swapped.first = pair.second;
  2292. swapped.second = pair.first;
  2293. index = FindItemIndexInFixedSet(*this, swapped);
  2294. }
  2295. return index;
  2296. }
  2297. /// Callback class to receive pairs of fixtures and particles which may be
  2298. /// overlapping. Used as an argument of b2World::QueryAABB.
  2299. class b2FixtureParticleQueryCallback : public b2QueryCallback
  2300. {
  2301. public:
  2302. explicit b2FixtureParticleQueryCallback(b2ParticleSystem* system)
  2303. {
  2304. m_system = system;
  2305. }
  2306. private:
  2307. // Skip reporting particles.
  2308. bool ShouldQueryParticleSystem(const b2ParticleSystem* system)
  2309. {
  2310. B2_NOT_USED(system);
  2311. return false;
  2312. }
  2313. // Receive a fixture and call ReportFixtureAndParticle() for each particle
  2314. // inside aabb of the fixture.
  2315. bool ReportFixture(b2Fixture* fixture)
  2316. {
  2317. if (fixture->IsSensor())
  2318. {
  2319. return true;
  2320. }
  2321. const b2Shape* shape = fixture->GetShape();
  2322. int32 childCount = shape->GetChildCount();
  2323. for (int32 childIndex = 0; childIndex < childCount; childIndex++)
  2324. {
  2325. b2AABB aabb = fixture->GetAABB(childIndex);
  2326. b2ParticleSystem::InsideBoundsEnumerator enumerator =
  2327. m_system->GetInsideBoundsEnumerator(aabb);
  2328. int32 index;
  2329. while ((index = enumerator.GetNext()) >= 0)
  2330. {
  2331. ReportFixtureAndParticle(fixture, childIndex, index);
  2332. }
  2333. }
  2334. return true;
  2335. }
  2336. // Receive a fixture and a particle which may be overlapping.
  2337. virtual void ReportFixtureAndParticle(
  2338. b2Fixture* fixture, int32 childIndex, int32 index) = 0;
  2339. protected:
  2340. b2ParticleSystem* m_system;
  2341. };
  2342. void b2ParticleSystem::NotifyBodyContactListenerPreContact(
  2343. FixtureParticleSet* fixtureSet) const
  2344. {
  2345. b2ContactListener* const contactListener = GetFixtureContactListener();
  2346. if (contactListener == NULL)
  2347. return;
  2348. fixtureSet->Initialize(m_bodyContactBuffer.Begin(),
  2349. m_bodyContactBuffer.GetCount(),
  2350. GetFlagsBuffer());
  2351. }
  2352. // If a contact listener is present and the contact is just starting
  2353. // report the contact. If the contact is already in progress invalid
  2354. // the contact from m_fixtureSet.
  2355. void b2ParticleSystem::NotifyBodyContactListenerPostContact(
  2356. FixtureParticleSet& fixtureSet)
  2357. {
  2358. b2ContactListener* const contactListener = GetFixtureContactListener();
  2359. if (contactListener == NULL)
  2360. return;
  2361. // Loop through all new contacts, reporting any new ones, and
  2362. // "invalidating" the ones that still exist.
  2363. for (b2ParticleBodyContact* contact = m_bodyContactBuffer.Begin();
  2364. contact != m_bodyContactBuffer.End(); ++contact)
  2365. {
  2366. b2Assert(contact);
  2367. FixtureParticle fixtureParticleToFind;
  2368. fixtureParticleToFind.first = contact->fixture;
  2369. fixtureParticleToFind.second = contact->index;
  2370. const int32 index = fixtureSet.Find(fixtureParticleToFind);
  2371. if (index >= 0)
  2372. {
  2373. // Already touching remove this from the set.
  2374. fixtureSet.Invalidate(index);
  2375. }
  2376. else
  2377. {
  2378. // Just started touching, report it!
  2379. contactListener->BeginContact(this, contact);
  2380. }
  2381. }
  2382. // If the contact listener is enabled, report all fixtures that are no
  2383. // longer in contact with particles.
  2384. const FixtureParticle* const fixtureParticles = fixtureSet.GetBuffer();
  2385. const int8* const fixtureParticlesValid = fixtureSet.GetValidBuffer();
  2386. const int32 fixtureParticleCount = fixtureSet.GetCount();
  2387. for (int32 i = 0; i < fixtureParticleCount; ++i)
  2388. {
  2389. if (fixtureParticlesValid[i])
  2390. {
  2391. const FixtureParticle* const fixtureParticle =
  2392. &fixtureParticles[i];
  2393. contactListener->EndContact(fixtureParticle->first, this,
  2394. fixtureParticle->second);
  2395. }
  2396. }
  2397. }
  2398. void b2ParticleSystem::UpdateBodyContacts()
  2399. {
  2400. // If the particle contact listener is enabled, generate a set of
  2401. // fixture / particle contacts.
  2402. FixtureParticleSet fixtureSet(&m_world->m_stackAllocator);
  2403. NotifyBodyContactListenerPreContact(&fixtureSet);
  2404. if (m_stuckThreshold > 0)
  2405. {
  2406. const int32 particleCount = GetParticleCount();
  2407. for (int32 i = 0; i < particleCount; i++)
  2408. {
  2409. // Detect stuck particles, see comment in
  2410. // b2ParticleSystem::DetectStuckParticle()
  2411. m_bodyContactCountBuffer.data[i] = 0;
  2412. if (m_timestamp > (m_lastBodyContactStepBuffer.data[i] + 1))
  2413. {
  2414. m_consecutiveContactStepsBuffer.data[i] = 0;
  2415. }
  2416. }
  2417. }
  2418. m_bodyContactBuffer.SetCount(0);
  2419. m_stuckParticleBuffer.SetCount(0);
  2420. class UpdateBodyContactsCallback : public b2FixtureParticleQueryCallback
  2421. {
  2422. // Call the contact filter if it's set, to determine whether to
  2423. // filter this contact. Returns true if contact calculations should
  2424. // be performed, false otherwise.
  2425. inline bool ShouldCollide(b2Fixture * const fixture,
  2426. int32 particleIndex)
  2427. {
  2428. if (m_contactFilter)
  2429. {
  2430. const uint32* const flags = m_system->GetFlagsBuffer();
  2431. if (flags[particleIndex] & b2_fixtureContactFilterParticle)
  2432. {
  2433. return m_contactFilter->ShouldCollide(fixture, m_system,
  2434. particleIndex);
  2435. }
  2436. }
  2437. return true;
  2438. }
  2439. void ReportFixtureAndParticle(
  2440. b2Fixture* fixture, int32 childIndex, int32 a)
  2441. {
  2442. b2Vec2 ap = m_system->m_positionBuffer.data[a];
  2443. float32 d;
  2444. b2Vec2 n;
  2445. fixture->ComputeDistance(ap, &d, &n, childIndex);
  2446. if (d < m_system->m_particleDiameter && ShouldCollide(fixture, a))
  2447. {
  2448. b2Body* b = fixture->GetBody();
  2449. b2Vec2 bp = b->GetWorldCenter();
  2450. float32 bm = b->GetMass();
  2451. float32 bI =
  2452. b->GetInertia() - bm * b->GetLocalCenter().LengthSquared();
  2453. float32 invBm = bm > 0 ? 1 / bm : 0;
  2454. float32 invBI = bI > 0 ? 1 / bI : 0;
  2455. float32 invAm =
  2456. m_system->m_flagsBuffer.data[a] &
  2457. b2_wallParticle ? 0 : m_system->GetParticleInvMass();
  2458. b2Vec2 rp = ap - bp;
  2459. float32 rpn = b2Cross(rp, n);
  2460. float32 invM = invAm + invBm + invBI * rpn * rpn;
  2461. b2ParticleBodyContact& contact =
  2462. m_system->m_bodyContactBuffer.Append();
  2463. contact.index = a;
  2464. contact.body = b;
  2465. contact.fixture = fixture;
  2466. contact.weight = 1 - d * m_system->m_inverseDiameter;
  2467. contact.normal = -n;
  2468. contact.mass = invM > 0 ? 1 / invM : 0;
  2469. m_system->DetectStuckParticle(a);
  2470. }
  2471. }
  2472. b2ContactFilter* m_contactFilter;
  2473. public:
  2474. UpdateBodyContactsCallback(
  2475. b2ParticleSystem* system, b2ContactFilter* contactFilter):
  2476. b2FixtureParticleQueryCallback(system)
  2477. {
  2478. m_contactFilter = contactFilter;
  2479. }
  2480. } callback(this, GetFixtureContactFilter());
  2481. b2AABB aabb;
  2482. ComputeAABB(&aabb);
  2483. m_world->QueryAABB(&callback, aabb);
  2484. if (m_def.strictContactCheck)
  2485. {
  2486. RemoveSpuriousBodyContacts();
  2487. }
  2488. NotifyBodyContactListenerPostContact(fixtureSet);
  2489. }
  2490. void b2ParticleSystem::RemoveSpuriousBodyContacts()
  2491. {
  2492. // At this point we have a list of contact candidates based on AABB
  2493. // overlap.The AABB query that generated this returns all collidable
  2494. // fixtures overlapping particle bounding boxes. This breaks down around
  2495. // vertices where two shapes intersect, such as a "ground" surface made
  2496. // of multiple b2PolygonShapes; it potentially applies a lot of spurious
  2497. // impulses from normals that should not actually contribute. See the
  2498. // Ramp example in Testbed.
  2499. //
  2500. // To correct for this, we apply this algorithm:
  2501. // * sort contacts by particle and subsort by weight (nearest to farthest)
  2502. // * for each contact per particle:
  2503. // - project a point at the contact distance along the inverse of the
  2504. // contact normal
  2505. // - if this intersects the fixture that generated the contact, apply
  2506. // it, otherwise discard as impossible
  2507. // - repeat for up to n nearest contacts, currently we get good results
  2508. // from n=3.
  2509. std::sort(m_bodyContactBuffer.Begin(), m_bodyContactBuffer.End(),
  2510. b2ParticleSystem::BodyContactCompare);
  2511. int32 discarded = 0;
  2512. std::remove_if(m_bodyContactBuffer.Begin(),
  2513. m_bodyContactBuffer.End(),
  2514. b2ParticleBodyContactRemovePredicate(this, &discarded));
  2515. m_bodyContactBuffer.SetCount(m_bodyContactBuffer.GetCount() - discarded);
  2516. }
  2517. bool b2ParticleSystem::BodyContactCompare(const b2ParticleBodyContact &lhs,
  2518. const b2ParticleBodyContact &rhs)
  2519. {
  2520. if (lhs.index == rhs.index)
  2521. {
  2522. // Subsort by weight, decreasing.
  2523. return lhs.weight > rhs.weight;
  2524. }
  2525. return lhs.index < rhs.index;
  2526. }
  2527. void b2ParticleSystem::SolveCollision(const b2TimeStep& step)
  2528. {
  2529. // This function detects particles which are crossing boundary of bodies
  2530. // and modifies velocities of them so that they will move just in front of
  2531. // boundary. This function function also applies the reaction force to
  2532. // bodies as precisely as the numerical stability is kept.
  2533. b2AABB aabb;
  2534. aabb.lowerBound.x = +b2_maxFloat;
  2535. aabb.lowerBound.y = +b2_maxFloat;
  2536. aabb.upperBound.x = -b2_maxFloat;
  2537. aabb.upperBound.y = -b2_maxFloat;
  2538. for (int32 i = 0; i < m_count; i++)
  2539. {
  2540. b2Vec2 v = m_velocityBuffer.data[i];
  2541. b2Vec2 p1 = m_positionBuffer.data[i];
  2542. b2Vec2 p2 = p1 + step.dt * v;
  2543. aabb.lowerBound = b2Min(aabb.lowerBound, b2Min(p1, p2));
  2544. aabb.upperBound = b2Max(aabb.upperBound, b2Max(p1, p2));
  2545. }
  2546. class SolveCollisionCallback : public b2FixtureParticleQueryCallback
  2547. {
  2548. void ReportFixtureAndParticle(
  2549. b2Fixture* fixture, int32 childIndex, int32 a)
  2550. {
  2551. b2Body* body = fixture->GetBody();
  2552. b2Vec2 ap = m_system->m_positionBuffer.data[a];
  2553. b2Vec2 av = m_system->m_velocityBuffer.data[a];
  2554. b2RayCastOutput output;
  2555. b2RayCastInput input;
  2556. if (m_system->m_iterationIndex == 0)
  2557. {
  2558. // Put 'ap' in the local space of the previous frame
  2559. b2Vec2 p1 = b2MulT(body->m_xf0, ap);
  2560. if (fixture->GetShape()->GetType() == b2Shape::e_circle)
  2561. {
  2562. // Make relative to the center of the circle
  2563. p1 -= body->GetLocalCenter();
  2564. // Re-apply rotation about the center of the
  2565. // circle
  2566. p1 = b2Mul(body->m_xf0.q, p1);
  2567. // Subtract rotation of the current frame
  2568. p1 = b2MulT(body->m_xf.q, p1);
  2569. // Return to local space
  2570. p1 += body->GetLocalCenter();
  2571. }
  2572. // Return to global space and apply rotation of current frame
  2573. input.p1 = b2Mul(body->m_xf, p1);
  2574. }
  2575. else
  2576. {
  2577. input.p1 = ap;
  2578. }
  2579. input.p2 = ap + m_step.dt * av;
  2580. input.maxFraction = 1;
  2581. if (fixture->RayCast(&output, input, childIndex))
  2582. {
  2583. b2Vec2 n = output.normal;
  2584. b2Vec2 p =
  2585. (1 - output.fraction) * input.p1 +
  2586. output.fraction * input.p2 +
  2587. b2_linearSlop * n;
  2588. b2Vec2 v = m_step.inv_dt * (p - ap);
  2589. m_system->m_velocityBuffer.data[a] = v;
  2590. b2Vec2 f = m_step.inv_dt *
  2591. m_system->GetParticleMass() * (av - v);
  2592. m_system->ParticleApplyForce(a, f);
  2593. }
  2594. }
  2595. b2TimeStep m_step;
  2596. public:
  2597. SolveCollisionCallback(
  2598. b2ParticleSystem* system, const b2TimeStep& step):
  2599. b2FixtureParticleQueryCallback(system)
  2600. {
  2601. m_step = step;
  2602. }
  2603. } callback(this, step);
  2604. m_world->QueryAABB(&callback, aabb);
  2605. }
  2606. void b2ParticleSystem::SolveBarrier(const b2TimeStep& step)
  2607. {
  2608. // If a particle is passing between paired barrier particles,
  2609. // its velocity will be decelerated to avoid passing.
  2610. for (int32 i = 0; i < m_count; i++)
  2611. {
  2612. uint32 flags = m_flagsBuffer.data[i];
  2613. static const uint32 k_barrierWallFlags =
  2614. b2_barrierParticle | b2_wallParticle;
  2615. if ((flags & k_barrierWallFlags) == k_barrierWallFlags)
  2616. {
  2617. m_velocityBuffer.data[i].SetZero();
  2618. }
  2619. }
  2620. float32 tmax = b2_barrierCollisionTime * step.dt;
  2621. for (int32 k = 0; k < m_pairBuffer.GetCount(); k++)
  2622. {
  2623. const b2ParticlePair& pair = m_pairBuffer[k];
  2624. if (pair.flags & b2_barrierParticle)
  2625. {
  2626. int32 a = pair.indexA;
  2627. int32 b = pair.indexB;
  2628. b2Vec2 pa = m_positionBuffer.data[a];
  2629. b2Vec2 pb = m_positionBuffer.data[b];
  2630. b2AABB aabb;
  2631. aabb.lowerBound = b2Min(pa, pb);
  2632. aabb.upperBound = b2Max(pa, pb);
  2633. b2ParticleGroup *aGroup = m_groupBuffer[a];
  2634. b2ParticleGroup *bGroup = m_groupBuffer[b];
  2635. b2Vec2 va = GetLinearVelocity(aGroup, a, pa);
  2636. b2Vec2 vb = GetLinearVelocity(bGroup, b, pb);
  2637. b2Vec2 pba = pb - pa;
  2638. b2Vec2 vba = vb - va;
  2639. InsideBoundsEnumerator enumerator = GetInsideBoundsEnumerator(aabb);
  2640. int32 c;
  2641. while ((c = enumerator.GetNext()) >= 0)
  2642. {
  2643. b2Vec2 pc = m_positionBuffer.data[c];
  2644. b2ParticleGroup *cGroup = m_groupBuffer[c];
  2645. if (aGroup != cGroup && bGroup != cGroup)
  2646. {
  2647. b2Vec2 vc = GetLinearVelocity(cGroup, c, pc);
  2648. // Solve the equation below:
  2649. // (1-s)*(pa+t*va)+s*(pb+t*vb) = pc+t*vc
  2650. // which expresses that the particle c will pass a line
  2651. // connecting the particles a and b at the time of t.
  2652. // if s is between 0 and 1, c will pass between a and b.
  2653. b2Vec2 pca = pc - pa;
  2654. b2Vec2 vca = vc - va;
  2655. float32 e2 = b2Cross(vba, vca);
  2656. float32 e1 = b2Cross(pba, vca) - b2Cross(pca, vba);
  2657. float32 e0 = b2Cross(pba, pca);
  2658. float32 s, t;
  2659. b2Vec2 qba, qca;
  2660. if (e2 == 0)
  2661. {
  2662. if (e1 == 0) continue;
  2663. t = - e0 / e1;
  2664. if (!(t >= 0 && t < tmax)) continue;
  2665. qba = pba + t * vba;
  2666. qca = pca + t * vca;
  2667. s = b2Dot(qba, qca) / b2Dot(qba, qba);
  2668. if (!(s >= 0 && s <= 1)) continue;
  2669. }
  2670. else
  2671. {
  2672. float32 det = e1 * e1 - 4 * e0 * e2;
  2673. if (det < 0) continue;
  2674. float32 sqrtDet = b2Sqrt(det);
  2675. float32 t1 = (- e1 - sqrtDet) / (2 * e2);
  2676. float32 t2 = (- e1 + sqrtDet) / (2 * e2);
  2677. if (t1 > t2) b2Swap(t1, t2);
  2678. t = t1;
  2679. qba = pba + t * vba;
  2680. qca = pca + t * vca;
  2681. s = b2Dot(qba, qca) / b2Dot(qba, qba);
  2682. if (!(t >= 0 && t < tmax && s >= 0 && s <= 1))
  2683. {
  2684. t = t2;
  2685. if (!(t >= 0 && t < tmax)) continue;
  2686. qba = pba + t * vba;
  2687. qca = pca + t * vca;
  2688. s = b2Dot(qba, qca) / b2Dot(qba, qba);
  2689. if (!(s >= 0 && s <= 1)) continue;
  2690. }
  2691. }
  2692. // Apply a force to particle c so that it will have the
  2693. // interpolated velocity at the collision point on line ab.
  2694. b2Vec2 dv = va + s * vba - vc;
  2695. b2Vec2 f = GetParticleMass() * dv;
  2696. if (IsRigidGroup(cGroup))
  2697. {
  2698. // If c belongs to a rigid group, the force will be
  2699. // distributed in the group.
  2700. float32 mass = cGroup->GetMass();
  2701. float32 inertia = cGroup->GetInertia();
  2702. if (mass > 0)
  2703. {
  2704. cGroup->m_linearVelocity += 1 / mass * f;
  2705. }
  2706. if (inertia > 0)
  2707. {
  2708. cGroup->m_angularVelocity +=
  2709. b2Cross(pc - cGroup->GetCenter(), f) / inertia;
  2710. }
  2711. }
  2712. else
  2713. {
  2714. m_velocityBuffer.data[c] += dv;
  2715. }
  2716. // Apply a reversed force to particle c after particle
  2717. // movement so that momentum will be preserved.
  2718. ParticleApplyForce(c, -step.inv_dt * f);
  2719. }
  2720. }
  2721. }
  2722. }
  2723. }
  2724. void b2ParticleSystem::Solve(const b2TimeStep& step)
  2725. {
  2726. if (m_count == 0)
  2727. {
  2728. return;
  2729. }
  2730. // If particle lifetimes are enabled, destroy particles that are too old.
  2731. if (m_expirationTimeBuffer.data)
  2732. {
  2733. SolveLifetimes(step);
  2734. }
  2735. if (m_allParticleFlags & b2_zombieParticle)
  2736. {
  2737. SolveZombie();
  2738. }
  2739. if (m_needsUpdateAllParticleFlags)
  2740. {
  2741. UpdateAllParticleFlags();
  2742. }
  2743. if (m_needsUpdateAllGroupFlags)
  2744. {
  2745. UpdateAllGroupFlags();
  2746. }
  2747. if (m_paused)
  2748. {
  2749. return;
  2750. }
  2751. for (m_iterationIndex = 0;
  2752. m_iterationIndex < step.particleIterations;
  2753. m_iterationIndex++)
  2754. {
  2755. ++m_timestamp;
  2756. b2TimeStep subStep = step;
  2757. subStep.dt /= step.particleIterations;
  2758. subStep.inv_dt *= step.particleIterations;
  2759. UpdateContacts(false);
  2760. UpdateBodyContacts();
  2761. ComputeWeight();
  2762. if (m_allGroupFlags & b2_particleGroupNeedsUpdateDepth)
  2763. {
  2764. ComputeDepth();
  2765. }
  2766. if (m_allParticleFlags & b2_reactiveParticle)
  2767. {
  2768. UpdatePairsAndTriadsWithReactiveParticles();
  2769. }
  2770. if (m_hasForce)
  2771. {
  2772. SolveForce(subStep);
  2773. }
  2774. if (m_allParticleFlags & b2_viscousParticle)
  2775. {
  2776. SolveViscous();
  2777. }
  2778. if (m_allParticleFlags & b2_repulsiveParticle)
  2779. {
  2780. SolveRepulsive(subStep);
  2781. }
  2782. if (m_allParticleFlags & b2_powderParticle)
  2783. {
  2784. SolvePowder(subStep);
  2785. }
  2786. if (m_allParticleFlags & b2_tensileParticle)
  2787. {
  2788. SolveTensile(subStep);
  2789. }
  2790. if (m_allGroupFlags & b2_solidParticleGroup)
  2791. {
  2792. SolveSolid(subStep);
  2793. }
  2794. if (m_allParticleFlags & b2_colorMixingParticle)
  2795. {
  2796. SolveColorMixing();
  2797. }
  2798. SolveGravity(subStep);
  2799. if (m_allParticleFlags & b2_staticPressureParticle)
  2800. {
  2801. SolveStaticPressure(subStep);
  2802. }
  2803. SolvePressure(subStep);
  2804. SolveDamping(subStep);
  2805. if (m_allParticleFlags & k_extraDampingFlags)
  2806. {
  2807. SolveExtraDamping();
  2808. }
  2809. // SolveElastic and SolveSpring refer the current velocities for
  2810. // numerical stability, they should be called as late as possible.
  2811. if (m_allParticleFlags & b2_elasticParticle)
  2812. {
  2813. SolveElastic(subStep);
  2814. }
  2815. if (m_allParticleFlags & b2_springParticle)
  2816. {
  2817. SolveSpring(subStep);
  2818. }
  2819. LimitVelocity(subStep);
  2820. if (m_allGroupFlags & b2_rigidParticleGroup)
  2821. {
  2822. SolveRigidDamping();
  2823. }
  2824. if (m_allParticleFlags & b2_barrierParticle)
  2825. {
  2826. SolveBarrier(subStep);
  2827. }
  2828. // SolveCollision, SolveRigid and SolveWall should be called after
  2829. // other force functions because they may require particles to have
  2830. // specific velocities.
  2831. SolveCollision(subStep);
  2832. if (m_allGroupFlags & b2_rigidParticleGroup)
  2833. {
  2834. SolveRigid(subStep);
  2835. }
  2836. if (m_allParticleFlags & b2_wallParticle)
  2837. {
  2838. SolveWall();
  2839. }
  2840. // The particle positions can be updated only at the end of substep.
  2841. for (int32 i = 0; i < m_count; i++)
  2842. {
  2843. m_positionBuffer.data[i] += subStep.dt * m_velocityBuffer.data[i];
  2844. }
  2845. }
  2846. }
  2847. void b2ParticleSystem::UpdateAllParticleFlags()
  2848. {
  2849. m_allParticleFlags = 0;
  2850. for (int32 i = 0; i < m_count; i++)
  2851. {
  2852. m_allParticleFlags |= m_flagsBuffer.data[i];
  2853. }
  2854. m_needsUpdateAllParticleFlags = false;
  2855. }
  2856. void b2ParticleSystem::UpdateAllGroupFlags()
  2857. {
  2858. m_allGroupFlags = 0;
  2859. for (const b2ParticleGroup* group = m_groupList; group;
  2860. group = group->GetNext())
  2861. {
  2862. m_allGroupFlags |= group->m_groupFlags;
  2863. }
  2864. m_needsUpdateAllGroupFlags = false;
  2865. }
  2866. void b2ParticleSystem::LimitVelocity(const b2TimeStep& step)
  2867. {
  2868. float32 criticalVelocitySquared = GetCriticalVelocitySquared(step);
  2869. for (int32 i = 0; i < m_count; i++)
  2870. {
  2871. b2Vec2& v = m_velocityBuffer.data[i];
  2872. float32 v2 = b2Dot(v, v);
  2873. if (v2 > criticalVelocitySquared)
  2874. {
  2875. v *= b2Sqrt(criticalVelocitySquared / v2);
  2876. }
  2877. }
  2878. }
  2879. void b2ParticleSystem::SolveGravity(const b2TimeStep& step)
  2880. {
  2881. b2Vec2 gravity = step.dt * m_def.gravityScale * m_world->GetGravity();
  2882. for (int32 i = 0; i < m_count; i++)
  2883. {
  2884. m_velocityBuffer.data[i] += gravity;
  2885. }
  2886. }
  2887. void b2ParticleSystem::SolveStaticPressure(const b2TimeStep& step)
  2888. {
  2889. m_staticPressureBuffer = RequestBuffer(m_staticPressureBuffer);
  2890. float32 criticalPressure = GetCriticalPressure(step);
  2891. float32 pressurePerWeight = m_def.staticPressureStrength * criticalPressure;
  2892. float32 maxPressure = b2_maxParticlePressure * criticalPressure;
  2893. float32 relaxation = m_def.staticPressureRelaxation;
  2894. /// Compute pressure satisfying the modified Poisson equation:
  2895. /// Sum_for_j((p_i - p_j) * w_ij) + relaxation * p_i =
  2896. /// pressurePerWeight * (w_i - b2_minParticleWeight)
  2897. /// by iterating the calculation:
  2898. /// p_i = (Sum_for_j(p_j * w_ij) + pressurePerWeight *
  2899. /// (w_i - b2_minParticleWeight)) / (w_i + relaxation)
  2900. /// where
  2901. /// p_i and p_j are static pressure of particle i and j
  2902. /// w_ij is contact weight between particle i and j
  2903. /// w_i is sum of contact weight of particle i
  2904. for (int32 t = 0; t < m_def.staticPressureIterations; t++)
  2905. {
  2906. memset(m_accumulationBuffer, 0,
  2907. sizeof(*m_accumulationBuffer) * m_count);
  2908. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  2909. {
  2910. const b2ParticleContact& contact = m_contactBuffer[k];
  2911. if (contact.GetFlags() & b2_staticPressureParticle)
  2912. {
  2913. int32 a = contact.GetIndexA();
  2914. int32 b = contact.GetIndexB();
  2915. float32 w = contact.GetWeight();
  2916. m_accumulationBuffer[a] +=
  2917. w * m_staticPressureBuffer[b]; // a <- b
  2918. m_accumulationBuffer[b] +=
  2919. w * m_staticPressureBuffer[a]; // b <- a
  2920. }
  2921. }
  2922. for (int32 i = 0; i < m_count; i++)
  2923. {
  2924. float32 w = m_weightBuffer[i];
  2925. if (m_flagsBuffer.data[i] & b2_staticPressureParticle)
  2926. {
  2927. float32 wh = m_accumulationBuffer[i];
  2928. float32 h =
  2929. (wh + pressurePerWeight * (w - b2_minParticleWeight)) /
  2930. (w + relaxation);
  2931. m_staticPressureBuffer[i] = b2Clamp(h, 0.0f, maxPressure);
  2932. }
  2933. else
  2934. {
  2935. m_staticPressureBuffer[i] = 0;
  2936. }
  2937. }
  2938. }
  2939. }
  2940. void b2ParticleSystem::SolvePressure(const b2TimeStep& step)
  2941. {
  2942. // calculates pressure as a linear function of density
  2943. float32 criticalPressure = GetCriticalPressure(step);
  2944. float32 pressurePerWeight = m_def.pressureStrength * criticalPressure;
  2945. float32 maxPressure = b2_maxParticlePressure * criticalPressure;
  2946. for (int32 i = 0; i < m_count; i++)
  2947. {
  2948. float32 w = m_weightBuffer[i];
  2949. float32 h = pressurePerWeight * b2Max(0.0f, w - b2_minParticleWeight);
  2950. m_accumulationBuffer[i] = b2Min(h, maxPressure);
  2951. }
  2952. // ignores particles which have their own repulsive force
  2953. if (m_allParticleFlags & k_noPressureFlags)
  2954. {
  2955. for (int32 i = 0; i < m_count; i++)
  2956. {
  2957. if (m_flagsBuffer.data[i] & k_noPressureFlags)
  2958. {
  2959. m_accumulationBuffer[i] = 0;
  2960. }
  2961. }
  2962. }
  2963. // static pressure
  2964. if (m_allParticleFlags & b2_staticPressureParticle)
  2965. {
  2966. b2Assert(m_staticPressureBuffer);
  2967. for (int32 i = 0; i < m_count; i++)
  2968. {
  2969. if (m_flagsBuffer.data[i] & b2_staticPressureParticle)
  2970. {
  2971. m_accumulationBuffer[i] += m_staticPressureBuffer[i];
  2972. }
  2973. }
  2974. }
  2975. // applies pressure between each particles in contact
  2976. float32 velocityPerPressure = step.dt / (m_def.density * m_particleDiameter);
  2977. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  2978. {
  2979. const b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  2980. int32 a = contact.index;
  2981. b2Body* b = contact.body;
  2982. float32 w = contact.weight;
  2983. float32 m = contact.mass;
  2984. b2Vec2 n = contact.normal;
  2985. b2Vec2 p = m_positionBuffer.data[a];
  2986. float32 h = m_accumulationBuffer[a] + pressurePerWeight * w;
  2987. b2Vec2 f = velocityPerPressure * w * m * h * n;
  2988. m_velocityBuffer.data[a] -= GetParticleInvMass() * f;
  2989. b->ApplyLinearImpulse(f, p, true);
  2990. }
  2991. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  2992. {
  2993. const b2ParticleContact& contact = m_contactBuffer[k];
  2994. int32 a = contact.GetIndexA();
  2995. int32 b = contact.GetIndexB();
  2996. float32 w = contact.GetWeight();
  2997. b2Vec2 n = contact.GetNormal();
  2998. float32 h = m_accumulationBuffer[a] + m_accumulationBuffer[b];
  2999. b2Vec2 f = velocityPerPressure * w * h * n;
  3000. m_velocityBuffer.data[a] -= f;
  3001. m_velocityBuffer.data[b] += f;
  3002. }
  3003. }
  3004. void b2ParticleSystem::SolveDamping(const b2TimeStep& step)
  3005. {
  3006. // reduces normal velocity of each contact
  3007. float32 linearDamping = m_def.dampingStrength;
  3008. float32 quadraticDamping = 1 / GetCriticalVelocity(step);
  3009. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  3010. {
  3011. const b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  3012. int32 a = contact.index;
  3013. b2Body* b = contact.body;
  3014. float32 w = contact.weight;
  3015. float32 m = contact.mass;
  3016. b2Vec2 n = contact.normal;
  3017. b2Vec2 p = m_positionBuffer.data[a];
  3018. b2Vec2 v = b->GetLinearVelocityFromWorldPoint(p) -
  3019. m_velocityBuffer.data[a];
  3020. float32 vn = b2Dot(v, n);
  3021. if (vn < 0)
  3022. {
  3023. float32 damping =
  3024. b2Max(linearDamping * w, b2Min(- quadraticDamping * vn, 0.5f));
  3025. b2Vec2 f = damping * m * vn * n;
  3026. m_velocityBuffer.data[a] += GetParticleInvMass() * f;
  3027. b->ApplyLinearImpulse(-f, p, true);
  3028. }
  3029. }
  3030. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3031. {
  3032. const b2ParticleContact& contact = m_contactBuffer[k];
  3033. int32 a = contact.GetIndexA();
  3034. int32 b = contact.GetIndexB();
  3035. float32 w = contact.GetWeight();
  3036. b2Vec2 n = contact.GetNormal();
  3037. b2Vec2 v = m_velocityBuffer.data[b] - m_velocityBuffer.data[a];
  3038. float32 vn = b2Dot(v, n);
  3039. if (vn < 0)
  3040. {
  3041. float32 damping =
  3042. b2Max(linearDamping * w, b2Min(- quadraticDamping * vn, 0.5f));
  3043. b2Vec2 f = damping * vn * n;
  3044. m_velocityBuffer.data[a] += f;
  3045. m_velocityBuffer.data[b] -= f;
  3046. }
  3047. }
  3048. }
  3049. inline bool b2ParticleSystem::IsRigidGroup(b2ParticleGroup *group) const
  3050. {
  3051. return group && (group->m_groupFlags & b2_rigidParticleGroup);
  3052. }
  3053. inline b2Vec2 b2ParticleSystem::GetLinearVelocity(
  3054. b2ParticleGroup *group, int32 particleIndex,
  3055. const b2Vec2 &point) const
  3056. {
  3057. if (IsRigidGroup(group))
  3058. {
  3059. return group->GetLinearVelocityFromWorldPoint(point);
  3060. }
  3061. else
  3062. {
  3063. return m_velocityBuffer.data[particleIndex];
  3064. }
  3065. }
  3066. inline void b2ParticleSystem::InitDampingParameter(
  3067. float32* invMass, float32* invInertia, float32* tangentDistance,
  3068. float32 mass, float32 inertia, const b2Vec2& center,
  3069. const b2Vec2& point, const b2Vec2& normal) const
  3070. {
  3071. *invMass = mass > 0 ? 1 / mass : 0;
  3072. *invInertia = inertia > 0 ? 1 / inertia : 0;
  3073. *tangentDistance = b2Cross(point - center, normal);
  3074. }
  3075. inline void b2ParticleSystem::InitDampingParameterWithRigidGroupOrParticle(
  3076. float32* invMass, float32* invInertia, float32* tangentDistance,
  3077. bool isRigidGroup, b2ParticleGroup* group, int32 particleIndex,
  3078. const b2Vec2& point, const b2Vec2& normal) const
  3079. {
  3080. if (isRigidGroup)
  3081. {
  3082. InitDampingParameter(
  3083. invMass, invInertia, tangentDistance,
  3084. group->GetMass(), group->GetInertia(), group->GetCenter(),
  3085. point, normal);
  3086. }
  3087. else
  3088. {
  3089. uint32 flags = m_flagsBuffer.data[particleIndex];
  3090. InitDampingParameter(
  3091. invMass, invInertia, tangentDistance,
  3092. flags & b2_wallParticle ? 0 : GetParticleMass(), 0, point,
  3093. point, normal);
  3094. }
  3095. }
  3096. inline float32 b2ParticleSystem::ComputeDampingImpulse(
  3097. float32 invMassA, float32 invInertiaA, float32 tangentDistanceA,
  3098. float32 invMassB, float32 invInertiaB, float32 tangentDistanceB,
  3099. float32 normalVelocity) const
  3100. {
  3101. float32 invMass =
  3102. invMassA + invInertiaA * tangentDistanceA * tangentDistanceA +
  3103. invMassB + invInertiaB * tangentDistanceB * tangentDistanceB;
  3104. return invMass > 0 ? normalVelocity / invMass : 0;
  3105. }
  3106. inline void b2ParticleSystem::ApplyDamping(
  3107. float32 invMass, float32 invInertia, float32 tangentDistance,
  3108. bool isRigidGroup, b2ParticleGroup* group, int32 particleIndex,
  3109. float32 impulse, const b2Vec2& normal)
  3110. {
  3111. if (isRigidGroup)
  3112. {
  3113. group->m_linearVelocity += impulse * invMass * normal;
  3114. group->m_angularVelocity += impulse * tangentDistance * invInertia;
  3115. }
  3116. else
  3117. {
  3118. m_velocityBuffer.data[particleIndex] += impulse * invMass * normal;
  3119. }
  3120. }
  3121. void b2ParticleSystem::SolveRigidDamping()
  3122. {
  3123. // Apply impulse to rigid particle groups colliding with other objects
  3124. // to reduce relative velocity at the colliding point.
  3125. float32 damping = m_def.dampingStrength;
  3126. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  3127. {
  3128. const b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  3129. int32 a = contact.index;
  3130. b2ParticleGroup* aGroup = m_groupBuffer[a];
  3131. if (IsRigidGroup(aGroup))
  3132. {
  3133. b2Body* b = contact.body;
  3134. b2Vec2 n = contact.normal;
  3135. float32 w = contact.weight;
  3136. b2Vec2 p = m_positionBuffer.data[a];
  3137. b2Vec2 v = b->GetLinearVelocityFromWorldPoint(p) -
  3138. aGroup->GetLinearVelocityFromWorldPoint(p);
  3139. float32 vn = b2Dot(v, n);
  3140. if (vn < 0)
  3141. // The group's average velocity at particle position 'p' is pushing
  3142. // the particle into the body.
  3143. {
  3144. float32 invMassA, invInertiaA, tangentDistanceA;
  3145. float32 invMassB, invInertiaB, tangentDistanceB;
  3146. InitDampingParameterWithRigidGroupOrParticle(
  3147. &invMassA, &invInertiaA, &tangentDistanceA,
  3148. true, aGroup, a, p, n);
  3149. InitDampingParameter(
  3150. &invMassB, &invInertiaB, &tangentDistanceB,
  3151. b->GetMass(),
  3152. // Calculate b->m_I from public functions of b2Body.
  3153. b->GetInertia() -
  3154. b->GetMass() * b->GetLocalCenter().LengthSquared(),
  3155. b->GetWorldCenter(),
  3156. p, n);
  3157. float32 f = damping * b2Min(w, 1.0f) * ComputeDampingImpulse(
  3158. invMassA, invInertiaA, tangentDistanceA,
  3159. invMassB, invInertiaB, tangentDistanceB,
  3160. vn);
  3161. ApplyDamping(
  3162. invMassA, invInertiaA, tangentDistanceA,
  3163. true, aGroup, a, f, n);
  3164. b->ApplyLinearImpulse(-f * n, p, true);
  3165. }
  3166. }
  3167. }
  3168. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3169. {
  3170. const b2ParticleContact& contact = m_contactBuffer[k];
  3171. int32 a = contact.GetIndexA();
  3172. int32 b = contact.GetIndexB();
  3173. b2Vec2 n = contact.GetNormal();
  3174. float32 w = contact.GetWeight();
  3175. b2ParticleGroup* aGroup = m_groupBuffer[a];
  3176. b2ParticleGroup* bGroup = m_groupBuffer[b];
  3177. bool aRigid = IsRigidGroup(aGroup);
  3178. bool bRigid = IsRigidGroup(bGroup);
  3179. if (aGroup != bGroup && (aRigid || bRigid))
  3180. {
  3181. b2Vec2 p =
  3182. 0.5f * (m_positionBuffer.data[a] + m_positionBuffer.data[b]);
  3183. b2Vec2 v =
  3184. GetLinearVelocity(bGroup, b, p) -
  3185. GetLinearVelocity(aGroup, a, p);
  3186. float32 vn = b2Dot(v, n);
  3187. if (vn < 0)
  3188. {
  3189. float32 invMassA, invInertiaA, tangentDistanceA;
  3190. float32 invMassB, invInertiaB, tangentDistanceB;
  3191. InitDampingParameterWithRigidGroupOrParticle(
  3192. &invMassA, &invInertiaA, &tangentDistanceA,
  3193. aRigid, aGroup, a,
  3194. p, n);
  3195. InitDampingParameterWithRigidGroupOrParticle(
  3196. &invMassB, &invInertiaB, &tangentDistanceB,
  3197. bRigid, bGroup, b,
  3198. p, n);
  3199. float32 f = damping * w * ComputeDampingImpulse(
  3200. invMassA, invInertiaA, tangentDistanceA,
  3201. invMassB, invInertiaB, tangentDistanceB,
  3202. vn);
  3203. ApplyDamping(
  3204. invMassA, invInertiaA, tangentDistanceA,
  3205. aRigid, aGroup, a, f, n);
  3206. ApplyDamping(
  3207. invMassB, invInertiaB, tangentDistanceB,
  3208. bRigid, bGroup, b, -f, n);
  3209. }
  3210. }
  3211. }
  3212. }
  3213. void b2ParticleSystem::SolveExtraDamping()
  3214. {
  3215. // Applies additional damping force between bodies and particles which can
  3216. // produce strong repulsive force. Applying damping force multiple times
  3217. // is effective in suppressing vibration.
  3218. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  3219. {
  3220. const b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  3221. int32 a = contact.index;
  3222. if (m_flagsBuffer.data[a] & k_extraDampingFlags)
  3223. {
  3224. b2Body* b = contact.body;
  3225. float32 m = contact.mass;
  3226. b2Vec2 n = contact.normal;
  3227. b2Vec2 p = m_positionBuffer.data[a];
  3228. b2Vec2 v =
  3229. b->GetLinearVelocityFromWorldPoint(p) -
  3230. m_velocityBuffer.data[a];
  3231. float32 vn = b2Dot(v, n);
  3232. if (vn < 0)
  3233. {
  3234. b2Vec2 f = 0.5f * m * vn * n;
  3235. m_velocityBuffer.data[a] += GetParticleInvMass() * f;
  3236. b->ApplyLinearImpulse(-f, p, true);
  3237. }
  3238. }
  3239. }
  3240. }
  3241. void b2ParticleSystem::SolveWall()
  3242. {
  3243. for (int32 i = 0; i < m_count; i++)
  3244. {
  3245. if (m_flagsBuffer.data[i] & b2_wallParticle)
  3246. {
  3247. m_velocityBuffer.data[i].SetZero();
  3248. }
  3249. }
  3250. }
  3251. void b2ParticleSystem::SolveRigid(const b2TimeStep& step)
  3252. {
  3253. for (b2ParticleGroup* group = m_groupList; group; group = group->GetNext())
  3254. {
  3255. if (group->m_groupFlags & b2_rigidParticleGroup)
  3256. {
  3257. group->UpdateStatistics();
  3258. b2Rot rotation(step.dt * group->m_angularVelocity);
  3259. b2Transform transform(
  3260. group->m_center + step.dt * group->m_linearVelocity -
  3261. b2Mul(rotation, group->m_center), rotation);
  3262. group->m_transform = b2Mul(transform, group->m_transform);
  3263. b2Transform velocityTransform;
  3264. velocityTransform.p.x = step.inv_dt * transform.p.x;
  3265. velocityTransform.p.y = step.inv_dt * transform.p.y;
  3266. velocityTransform.q.s = step.inv_dt * transform.q.s;
  3267. velocityTransform.q.c = step.inv_dt * (transform.q.c - 1);
  3268. for (int32 i = group->m_firstIndex; i < group->m_lastIndex; i++)
  3269. {
  3270. m_velocityBuffer.data[i] = b2Mul(velocityTransform,
  3271. m_positionBuffer.data[i]);
  3272. }
  3273. }
  3274. }
  3275. }
  3276. void b2ParticleSystem::SolveElastic(const b2TimeStep& step)
  3277. {
  3278. float32 elasticStrength = step.inv_dt * m_def.elasticStrength;
  3279. for (int32 k = 0; k < m_triadBuffer.GetCount(); k++)
  3280. {
  3281. const b2ParticleTriad& triad = m_triadBuffer[k];
  3282. if (triad.flags & b2_elasticParticle)
  3283. {
  3284. int32 a = triad.indexA;
  3285. int32 b = triad.indexB;
  3286. int32 c = triad.indexC;
  3287. const b2Vec2& oa = triad.pa;
  3288. const b2Vec2& ob = triad.pb;
  3289. const b2Vec2& oc = triad.pc;
  3290. b2Vec2 pa = m_positionBuffer.data[a];
  3291. b2Vec2 pb = m_positionBuffer.data[b];
  3292. b2Vec2 pc = m_positionBuffer.data[c];
  3293. b2Vec2& va = m_velocityBuffer.data[a];
  3294. b2Vec2& vb = m_velocityBuffer.data[b];
  3295. b2Vec2& vc = m_velocityBuffer.data[c];
  3296. pa += step.dt * va;
  3297. pb += step.dt * vb;
  3298. pc += step.dt * vc;
  3299. b2Vec2 midPoint = (float32) 1 / 3 * (pa + pb + pc);
  3300. pa -= midPoint;
  3301. pb -= midPoint;
  3302. pc -= midPoint;
  3303. b2Rot r;
  3304. r.s = b2Cross(oa, pa) + b2Cross(ob, pb) + b2Cross(oc, pc);
  3305. r.c = b2Dot(oa, pa) + b2Dot(ob, pb) + b2Dot(oc, pc);
  3306. float32 r2 = r.s * r.s + r.c * r.c;
  3307. float32 invR = b2InvSqrt(r2);
  3308. r.s *= invR;
  3309. r.c *= invR;
  3310. float32 strength = elasticStrength * triad.strength;
  3311. va += strength * (b2Mul(r, oa) - pa);
  3312. vb += strength * (b2Mul(r, ob) - pb);
  3313. vc += strength * (b2Mul(r, oc) - pc);
  3314. }
  3315. }
  3316. }
  3317. void b2ParticleSystem::SolveSpring(const b2TimeStep& step)
  3318. {
  3319. float32 springStrength = step.inv_dt * m_def.springStrength;
  3320. for (int32 k = 0; k < m_pairBuffer.GetCount(); k++)
  3321. {
  3322. const b2ParticlePair& pair = m_pairBuffer[k];
  3323. if (pair.flags & b2_springParticle)
  3324. {
  3325. int32 a = pair.indexA;
  3326. int32 b = pair.indexB;
  3327. b2Vec2 pa = m_positionBuffer.data[a];
  3328. b2Vec2 pb = m_positionBuffer.data[b];
  3329. b2Vec2& va = m_velocityBuffer.data[a];
  3330. b2Vec2& vb = m_velocityBuffer.data[b];
  3331. pa += step.dt * va;
  3332. pb += step.dt * vb;
  3333. b2Vec2 d = pb - pa;
  3334. float32 r0 = pair.distance;
  3335. float32 r1 = d.Length();
  3336. float32 strength = springStrength * pair.strength;
  3337. b2Vec2 f = strength * (r0 - r1) / r1 * d;
  3338. va -= f;
  3339. vb += f;
  3340. }
  3341. }
  3342. }
  3343. void b2ParticleSystem::SolveTensile(const b2TimeStep& step)
  3344. {
  3345. b2Assert(m_accumulation2Buffer);
  3346. for (int32 i = 0; i < m_count; i++)
  3347. {
  3348. m_accumulation2Buffer[i] = b2Vec2_zero;
  3349. }
  3350. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3351. {
  3352. const b2ParticleContact& contact = m_contactBuffer[k];
  3353. if (contact.GetFlags() & b2_tensileParticle)
  3354. {
  3355. int32 a = contact.GetIndexA();
  3356. int32 b = contact.GetIndexB();
  3357. float32 w = contact.GetWeight();
  3358. b2Vec2 n = contact.GetNormal();
  3359. b2Vec2 weightedNormal = (1 - w) * w * n;
  3360. m_accumulation2Buffer[a] -= weightedNormal;
  3361. m_accumulation2Buffer[b] += weightedNormal;
  3362. }
  3363. }
  3364. float32 criticalVelocity = GetCriticalVelocity(step);
  3365. float32 pressureStrength = m_def.surfaceTensionPressureStrength
  3366. * criticalVelocity;
  3367. float32 normalStrength = m_def.surfaceTensionNormalStrength
  3368. * criticalVelocity;
  3369. float32 maxVelocityVariation = b2_maxParticleForce * criticalVelocity;
  3370. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3371. {
  3372. const b2ParticleContact& contact = m_contactBuffer[k];
  3373. if (contact.GetFlags() & b2_tensileParticle)
  3374. {
  3375. int32 a = contact.GetIndexA();
  3376. int32 b = contact.GetIndexB();
  3377. float32 w = contact.GetWeight();
  3378. b2Vec2 n = contact.GetNormal();
  3379. float32 h = m_weightBuffer[a] + m_weightBuffer[b];
  3380. b2Vec2 s = m_accumulation2Buffer[b] - m_accumulation2Buffer[a];
  3381. float32 fn = b2Min(
  3382. pressureStrength * (h - 2) + normalStrength * b2Dot(s, n),
  3383. maxVelocityVariation) * w;
  3384. b2Vec2 f = fn * n;
  3385. m_velocityBuffer.data[a] -= f;
  3386. m_velocityBuffer.data[b] += f;
  3387. }
  3388. }
  3389. }
  3390. void b2ParticleSystem::SolveViscous()
  3391. {
  3392. float32 viscousStrength = m_def.viscousStrength;
  3393. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  3394. {
  3395. const b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  3396. int32 a = contact.index;
  3397. if (m_flagsBuffer.data[a] & b2_viscousParticle)
  3398. {
  3399. b2Body* b = contact.body;
  3400. float32 w = contact.weight;
  3401. float32 m = contact.mass;
  3402. b2Vec2 p = m_positionBuffer.data[a];
  3403. b2Vec2 v = b->GetLinearVelocityFromWorldPoint(p) -
  3404. m_velocityBuffer.data[a];
  3405. b2Vec2 f = viscousStrength * m * w * v;
  3406. m_velocityBuffer.data[a] += GetParticleInvMass() * f;
  3407. b->ApplyLinearImpulse(-f, p, true);
  3408. }
  3409. }
  3410. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3411. {
  3412. const b2ParticleContact& contact = m_contactBuffer[k];
  3413. if (contact.GetFlags() & b2_viscousParticle)
  3414. {
  3415. int32 a = contact.GetIndexA();
  3416. int32 b = contact.GetIndexB();
  3417. float32 w = contact.GetWeight();
  3418. b2Vec2 v = m_velocityBuffer.data[b] - m_velocityBuffer.data[a];
  3419. b2Vec2 f = viscousStrength * w * v;
  3420. m_velocityBuffer.data[a] += f;
  3421. m_velocityBuffer.data[b] -= f;
  3422. }
  3423. }
  3424. }
  3425. void b2ParticleSystem::SolveRepulsive(const b2TimeStep& step)
  3426. {
  3427. float32 repulsiveStrength =
  3428. m_def.repulsiveStrength * GetCriticalVelocity(step);
  3429. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3430. {
  3431. const b2ParticleContact& contact = m_contactBuffer[k];
  3432. if (contact.GetFlags() & b2_repulsiveParticle)
  3433. {
  3434. int32 a = contact.GetIndexA();
  3435. int32 b = contact.GetIndexB();
  3436. if (m_groupBuffer[a] != m_groupBuffer[b])
  3437. {
  3438. float32 w = contact.GetWeight();
  3439. b2Vec2 n = contact.GetNormal();
  3440. b2Vec2 f = repulsiveStrength * w * n;
  3441. m_velocityBuffer.data[a] -= f;
  3442. m_velocityBuffer.data[b] += f;
  3443. }
  3444. }
  3445. }
  3446. }
  3447. void b2ParticleSystem::SolvePowder(const b2TimeStep& step)
  3448. {
  3449. float32 powderStrength = m_def.powderStrength * GetCriticalVelocity(step);
  3450. float32 minWeight = 1.0f - b2_particleStride;
  3451. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3452. {
  3453. const b2ParticleContact& contact = m_contactBuffer[k];
  3454. if (contact.GetFlags() & b2_powderParticle)
  3455. {
  3456. float32 w = contact.GetWeight();
  3457. if (w > minWeight)
  3458. {
  3459. int32 a = contact.GetIndexA();
  3460. int32 b = contact.GetIndexB();
  3461. b2Vec2 n = contact.GetNormal();
  3462. b2Vec2 f = powderStrength * (w - minWeight) * n;
  3463. m_velocityBuffer.data[a] -= f;
  3464. m_velocityBuffer.data[b] += f;
  3465. }
  3466. }
  3467. }
  3468. }
  3469. void b2ParticleSystem::SolveSolid(const b2TimeStep& step)
  3470. {
  3471. // applies extra repulsive force from solid particle groups
  3472. b2Assert(m_depthBuffer);
  3473. float32 ejectionStrength = step.inv_dt * m_def.ejectionStrength;
  3474. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3475. {
  3476. const b2ParticleContact& contact = m_contactBuffer[k];
  3477. int32 a = contact.GetIndexA();
  3478. int32 b = contact.GetIndexB();
  3479. if (m_groupBuffer[a] != m_groupBuffer[b])
  3480. {
  3481. float32 w = contact.GetWeight();
  3482. b2Vec2 n = contact.GetNormal();
  3483. float32 h = m_depthBuffer[a] + m_depthBuffer[b];
  3484. b2Vec2 f = ejectionStrength * h * w * n;
  3485. m_velocityBuffer.data[a] -= f;
  3486. m_velocityBuffer.data[b] += f;
  3487. }
  3488. }
  3489. }
  3490. void b2ParticleSystem::SolveForce(const b2TimeStep& step)
  3491. {
  3492. float32 velocityPerForce = step.dt * GetParticleInvMass();
  3493. for (int32 i = 0; i < m_count; i++)
  3494. {
  3495. m_velocityBuffer.data[i] += velocityPerForce * m_forceBuffer[i];
  3496. }
  3497. m_hasForce = false;
  3498. }
  3499. void b2ParticleSystem::SolveColorMixing()
  3500. {
  3501. // mixes color between contacting particles
  3502. b2Assert(m_colorBuffer.data);
  3503. const int32 colorMixing128 = (int32) (128 * m_def.colorMixingStrength);
  3504. if (colorMixing128) {
  3505. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3506. {
  3507. const b2ParticleContact& contact = m_contactBuffer[k];
  3508. int32 a = contact.GetIndexA();
  3509. int32 b = contact.GetIndexB();
  3510. if (m_flagsBuffer.data[a] & m_flagsBuffer.data[b] &
  3511. b2_colorMixingParticle)
  3512. {
  3513. b2ParticleColor& colorA = m_colorBuffer.data[a];
  3514. b2ParticleColor& colorB = m_colorBuffer.data[b];
  3515. // Use the static method to ensure certain compilers inline
  3516. // this correctly.
  3517. b2ParticleColor::MixColors(&colorA, &colorB, colorMixing128);
  3518. }
  3519. }
  3520. }
  3521. }
  3522. void b2ParticleSystem::SolveZombie()
  3523. {
  3524. // removes particles with zombie flag
  3525. int32 newCount = 0;
  3526. int32* newIndices = (int32*) m_world->m_stackAllocator.Allocate(
  3527. sizeof(int32) * m_count);
  3528. uint32 allParticleFlags = 0;
  3529. for (int32 i = 0; i < m_count; i++)
  3530. {
  3531. int32 flags = m_flagsBuffer.data[i];
  3532. if (flags & b2_zombieParticle)
  3533. {
  3534. b2DestructionListener * const destructionListener =
  3535. m_world->m_destructionListener;
  3536. if ((flags & b2_destructionListenerParticle) &&
  3537. destructionListener)
  3538. {
  3539. destructionListener->SayGoodbye(this, i);
  3540. }
  3541. // Destroy particle handle.
  3542. if (m_handleIndexBuffer.data)
  3543. {
  3544. b2ParticleHandle * const handle = m_handleIndexBuffer.data[i];
  3545. if (handle)
  3546. {
  3547. handle->SetIndex(b2_invalidParticleIndex);
  3548. m_handleIndexBuffer.data[i] = NULL;
  3549. m_handleAllocator.Free(handle);
  3550. }
  3551. }
  3552. newIndices[i] = b2_invalidParticleIndex;
  3553. }
  3554. else
  3555. {
  3556. newIndices[i] = newCount;
  3557. if (i != newCount)
  3558. {
  3559. // Update handle to reference new particle index.
  3560. if (m_handleIndexBuffer.data)
  3561. {
  3562. b2ParticleHandle * const handle =
  3563. m_handleIndexBuffer.data[i];
  3564. if (handle) handle->SetIndex(newCount);
  3565. m_handleIndexBuffer.data[newCount] = handle;
  3566. }
  3567. m_flagsBuffer.data[newCount] = m_flagsBuffer.data[i];
  3568. if (m_lastBodyContactStepBuffer.data)
  3569. {
  3570. m_lastBodyContactStepBuffer.data[newCount] =
  3571. m_lastBodyContactStepBuffer.data[i];
  3572. }
  3573. if (m_bodyContactCountBuffer.data)
  3574. {
  3575. m_bodyContactCountBuffer.data[newCount] =
  3576. m_bodyContactCountBuffer.data[i];
  3577. }
  3578. if (m_consecutiveContactStepsBuffer.data)
  3579. {
  3580. m_consecutiveContactStepsBuffer.data[newCount] =
  3581. m_consecutiveContactStepsBuffer.data[i];
  3582. }
  3583. m_positionBuffer.data[newCount] = m_positionBuffer.data[i];
  3584. m_velocityBuffer.data[newCount] = m_velocityBuffer.data[i];
  3585. m_groupBuffer[newCount] = m_groupBuffer[i];
  3586. if (m_hasForce)
  3587. {
  3588. m_forceBuffer[newCount] = m_forceBuffer[i];
  3589. }
  3590. if (m_staticPressureBuffer)
  3591. {
  3592. m_staticPressureBuffer[newCount] =
  3593. m_staticPressureBuffer[i];
  3594. }
  3595. if (m_depthBuffer)
  3596. {
  3597. m_depthBuffer[newCount] = m_depthBuffer[i];
  3598. }
  3599. if (m_colorBuffer.data)
  3600. {
  3601. m_colorBuffer.data[newCount] = m_colorBuffer.data[i];
  3602. }
  3603. if (m_userDataBuffer.data)
  3604. {
  3605. m_userDataBuffer.data[newCount] = m_userDataBuffer.data[i];
  3606. }
  3607. if (m_expirationTimeBuffer.data)
  3608. {
  3609. m_expirationTimeBuffer.data[newCount] =
  3610. m_expirationTimeBuffer.data[i];
  3611. }
  3612. }
  3613. newCount++;
  3614. allParticleFlags |= flags;
  3615. }
  3616. }
  3617. // predicate functions
  3618. struct Test
  3619. {
  3620. static bool IsProxyInvalid(const Proxy& proxy)
  3621. {
  3622. return proxy.index < 0;
  3623. }
  3624. static bool IsContactInvalid(const b2ParticleContact& contact)
  3625. {
  3626. return contact.GetIndexA() < 0 || contact.GetIndexB() < 0;
  3627. }
  3628. static bool IsBodyContactInvalid(const b2ParticleBodyContact& contact)
  3629. {
  3630. return contact.index < 0;
  3631. }
  3632. static bool IsPairInvalid(const b2ParticlePair& pair)
  3633. {
  3634. return pair.indexA < 0 || pair.indexB < 0;
  3635. }
  3636. static bool IsTriadInvalid(const b2ParticleTriad& triad)
  3637. {
  3638. return triad.indexA < 0 || triad.indexB < 0 || triad.indexC < 0;
  3639. }
  3640. };
  3641. // update proxies
  3642. for (int32 k = 0; k < m_proxyBuffer.GetCount(); k++)
  3643. {
  3644. Proxy& proxy = m_proxyBuffer.Begin()[k];
  3645. proxy.index = newIndices[proxy.index];
  3646. }
  3647. m_proxyBuffer.RemoveIf(Test::IsProxyInvalid);
  3648. // update contacts
  3649. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3650. {
  3651. b2ParticleContact& contact = m_contactBuffer[k];
  3652. contact.SetIndices(newIndices[contact.GetIndexA()],
  3653. newIndices[contact.GetIndexB()]);
  3654. }
  3655. m_contactBuffer.RemoveIf(Test::IsContactInvalid);
  3656. // update particle-body contacts
  3657. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  3658. {
  3659. b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  3660. contact.index = newIndices[contact.index];
  3661. }
  3662. m_bodyContactBuffer.RemoveIf(Test::IsBodyContactInvalid);
  3663. // update pairs
  3664. for (int32 k = 0; k < m_pairBuffer.GetCount(); k++)
  3665. {
  3666. b2ParticlePair& pair = m_pairBuffer[k];
  3667. pair.indexA = newIndices[pair.indexA];
  3668. pair.indexB = newIndices[pair.indexB];
  3669. }
  3670. m_pairBuffer.RemoveIf(Test::IsPairInvalid);
  3671. // update triads
  3672. for (int32 k = 0; k < m_triadBuffer.GetCount(); k++)
  3673. {
  3674. b2ParticleTriad& triad = m_triadBuffer[k];
  3675. triad.indexA = newIndices[triad.indexA];
  3676. triad.indexB = newIndices[triad.indexB];
  3677. triad.indexC = newIndices[triad.indexC];
  3678. }
  3679. m_triadBuffer.RemoveIf(Test::IsTriadInvalid);
  3680. // Update lifetime indices.
  3681. if (m_indexByExpirationTimeBuffer.data)
  3682. {
  3683. int32 writeOffset = 0;
  3684. for (int32 readOffset = 0; readOffset < m_count; readOffset++)
  3685. {
  3686. const int32 newIndex = newIndices[
  3687. m_indexByExpirationTimeBuffer.data[readOffset]];
  3688. if (newIndex != b2_invalidParticleIndex)
  3689. {
  3690. m_indexByExpirationTimeBuffer.data[writeOffset++] = newIndex;
  3691. }
  3692. }
  3693. }
  3694. // update groups
  3695. for (b2ParticleGroup* group = m_groupList; group; group = group->GetNext())
  3696. {
  3697. int32 firstIndex = newCount;
  3698. int32 lastIndex = 0;
  3699. bool modified = false;
  3700. for (int32 i = group->m_firstIndex; i < group->m_lastIndex; i++)
  3701. {
  3702. int32 j = newIndices[i];
  3703. if (j >= 0) {
  3704. firstIndex = b2Min(firstIndex, j);
  3705. lastIndex = b2Max(lastIndex, j + 1);
  3706. } else {
  3707. modified = true;
  3708. }
  3709. }
  3710. if (firstIndex < lastIndex)
  3711. {
  3712. group->m_firstIndex = firstIndex;
  3713. group->m_lastIndex = lastIndex;
  3714. if (modified)
  3715. {
  3716. if (group->m_groupFlags & b2_solidParticleGroup)
  3717. {
  3718. SetGroupFlags(group,
  3719. group->m_groupFlags |
  3720. b2_particleGroupNeedsUpdateDepth);
  3721. }
  3722. }
  3723. }
  3724. else
  3725. {
  3726. group->m_firstIndex = 0;
  3727. group->m_lastIndex = 0;
  3728. if (!(group->m_groupFlags & b2_particleGroupCanBeEmpty))
  3729. {
  3730. SetGroupFlags(group,
  3731. group->m_groupFlags | b2_particleGroupWillBeDestroyed);
  3732. }
  3733. }
  3734. }
  3735. // update particle count
  3736. m_count = newCount;
  3737. m_world->m_stackAllocator.Free(newIndices);
  3738. m_allParticleFlags = allParticleFlags;
  3739. m_needsUpdateAllParticleFlags = false;
  3740. // destroy bodies with no particles
  3741. for (b2ParticleGroup* group = m_groupList; group;)
  3742. {
  3743. b2ParticleGroup* next = group->GetNext();
  3744. if (group->m_groupFlags & b2_particleGroupWillBeDestroyed)
  3745. {
  3746. DestroyParticleGroup(group);
  3747. }
  3748. group = next;
  3749. }
  3750. }
  3751. /// Destroy all particles which have outlived their lifetimes set by
  3752. /// SetParticleLifetime().
  3753. void b2ParticleSystem::SolveLifetimes(const b2TimeStep& step)
  3754. {
  3755. b2Assert(m_expirationTimeBuffer.data);
  3756. b2Assert(m_indexByExpirationTimeBuffer.data);
  3757. // Update the time elapsed.
  3758. m_timeElapsed = LifetimeToExpirationTime(step.dt);
  3759. // Get the floor (non-fractional component) of the elapsed time.
  3760. const int32 quantizedTimeElapsed = GetQuantizedTimeElapsed();
  3761. const int32* const expirationTimes = m_expirationTimeBuffer.data;
  3762. int32* const expirationTimeIndices = m_indexByExpirationTimeBuffer.data;
  3763. const int32 particleCount = GetParticleCount();
  3764. // Sort the lifetime buffer if it's required.
  3765. if (m_expirationTimeBufferRequiresSorting)
  3766. {
  3767. const ExpirationTimeComparator expirationTimeComparator(
  3768. expirationTimes);
  3769. std::sort(expirationTimeIndices,
  3770. expirationTimeIndices + particleCount,
  3771. expirationTimeComparator);
  3772. m_expirationTimeBufferRequiresSorting = false;
  3773. }
  3774. // Destroy particles which have expired.
  3775. for (int32 i = particleCount - 1; i >= 0; --i)
  3776. {
  3777. const int32 particleIndex = expirationTimeIndices[i];
  3778. const int32 expirationTime = expirationTimes[particleIndex];
  3779. // If no particles need to be destroyed, skip this.
  3780. if (quantizedTimeElapsed < expirationTime || expirationTime <= 0)
  3781. {
  3782. break;
  3783. }
  3784. // Destroy this particle.
  3785. DestroyParticle(particleIndex);
  3786. }
  3787. }
  3788. void b2ParticleSystem::RotateBuffer(int32 start, int32 mid, int32 end)
  3789. {
  3790. // move the particles assigned to the given group toward the end of array
  3791. if (start == mid || mid == end)
  3792. {
  3793. return;
  3794. }
  3795. b2Assert(mid >= start && mid <= end);
  3796. struct NewIndices
  3797. {
  3798. int32 operator[](int32 i) const
  3799. {
  3800. if (i < start)
  3801. {
  3802. return i;
  3803. }
  3804. else if (i < mid)
  3805. {
  3806. return i + end - mid;
  3807. }
  3808. else if (i < end)
  3809. {
  3810. return i + start - mid;
  3811. }
  3812. else
  3813. {
  3814. return i;
  3815. }
  3816. }
  3817. int32 start, mid, end;
  3818. } newIndices;
  3819. newIndices.start = start;
  3820. newIndices.mid = mid;
  3821. newIndices.end = end;
  3822. std::rotate(m_flagsBuffer.data + start, m_flagsBuffer.data + mid,
  3823. m_flagsBuffer.data + end);
  3824. if (m_lastBodyContactStepBuffer.data)
  3825. {
  3826. std::rotate(m_lastBodyContactStepBuffer.data + start,
  3827. m_lastBodyContactStepBuffer.data + mid,
  3828. m_lastBodyContactStepBuffer.data + end);
  3829. }
  3830. if (m_bodyContactCountBuffer.data)
  3831. {
  3832. std::rotate(m_bodyContactCountBuffer.data + start,
  3833. m_bodyContactCountBuffer.data + mid,
  3834. m_bodyContactCountBuffer.data + end);
  3835. }
  3836. if (m_consecutiveContactStepsBuffer.data)
  3837. {
  3838. std::rotate(m_consecutiveContactStepsBuffer.data + start,
  3839. m_consecutiveContactStepsBuffer.data + mid,
  3840. m_consecutiveContactStepsBuffer.data + end);
  3841. }
  3842. std::rotate(m_positionBuffer.data + start, m_positionBuffer.data + mid,
  3843. m_positionBuffer.data + end);
  3844. std::rotate(m_velocityBuffer.data + start, m_velocityBuffer.data + mid,
  3845. m_velocityBuffer.data + end);
  3846. std::rotate(m_groupBuffer + start, m_groupBuffer + mid,
  3847. m_groupBuffer + end);
  3848. if (m_hasForce)
  3849. {
  3850. std::rotate(m_forceBuffer + start, m_forceBuffer + mid,
  3851. m_forceBuffer + end);
  3852. }
  3853. if (m_staticPressureBuffer)
  3854. {
  3855. std::rotate(m_staticPressureBuffer + start,
  3856. m_staticPressureBuffer + mid,
  3857. m_staticPressureBuffer + end);
  3858. }
  3859. if (m_depthBuffer)
  3860. {
  3861. std::rotate(m_depthBuffer + start, m_depthBuffer + mid,
  3862. m_depthBuffer + end);
  3863. }
  3864. if (m_colorBuffer.data)
  3865. {
  3866. std::rotate(m_colorBuffer.data + start,
  3867. m_colorBuffer.data + mid, m_colorBuffer.data + end);
  3868. }
  3869. if (m_userDataBuffer.data)
  3870. {
  3871. std::rotate(m_userDataBuffer.data + start,
  3872. m_userDataBuffer.data + mid, m_userDataBuffer.data + end);
  3873. }
  3874. // Update handle indices.
  3875. if (m_handleIndexBuffer.data)
  3876. {
  3877. std::rotate(m_handleIndexBuffer.data + start,
  3878. m_handleIndexBuffer.data + mid,
  3879. m_handleIndexBuffer.data + end);
  3880. for (int32 i = start; i < end; ++i)
  3881. {
  3882. b2ParticleHandle * const handle = m_handleIndexBuffer.data[i];
  3883. if (handle) handle->SetIndex(newIndices[handle->GetIndex()]);
  3884. }
  3885. }
  3886. if (m_expirationTimeBuffer.data)
  3887. {
  3888. std::rotate(m_expirationTimeBuffer.data + start,
  3889. m_expirationTimeBuffer.data + mid,
  3890. m_expirationTimeBuffer.data + end);
  3891. // Update expiration time buffer indices.
  3892. const int32 particleCount = GetParticleCount();
  3893. int32* const indexByExpirationTime =
  3894. m_indexByExpirationTimeBuffer.data;
  3895. for (int32 i = 0; i < particleCount; ++i)
  3896. {
  3897. indexByExpirationTime[i] = newIndices[indexByExpirationTime[i]];
  3898. }
  3899. }
  3900. // update proxies
  3901. for (int32 k = 0; k < m_proxyBuffer.GetCount(); k++)
  3902. {
  3903. Proxy& proxy = m_proxyBuffer.Begin()[k];
  3904. proxy.index = newIndices[proxy.index];
  3905. }
  3906. // update contacts
  3907. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  3908. {
  3909. b2ParticleContact& contact = m_contactBuffer[k];
  3910. contact.SetIndices(newIndices[contact.GetIndexA()],
  3911. newIndices[contact.GetIndexB()]);
  3912. }
  3913. // update particle-body contacts
  3914. for (int32 k = 0; k < m_bodyContactBuffer.GetCount(); k++)
  3915. {
  3916. b2ParticleBodyContact& contact = m_bodyContactBuffer[k];
  3917. contact.index = newIndices[contact.index];
  3918. }
  3919. // update pairs
  3920. for (int32 k = 0; k < m_pairBuffer.GetCount(); k++)
  3921. {
  3922. b2ParticlePair& pair = m_pairBuffer[k];
  3923. pair.indexA = newIndices[pair.indexA];
  3924. pair.indexB = newIndices[pair.indexB];
  3925. }
  3926. // update triads
  3927. for (int32 k = 0; k < m_triadBuffer.GetCount(); k++)
  3928. {
  3929. b2ParticleTriad& triad = m_triadBuffer[k];
  3930. triad.indexA = newIndices[triad.indexA];
  3931. triad.indexB = newIndices[triad.indexB];
  3932. triad.indexC = newIndices[triad.indexC];
  3933. }
  3934. // update groups
  3935. for (b2ParticleGroup* group = m_groupList; group; group = group->GetNext())
  3936. {
  3937. group->m_firstIndex = newIndices[group->m_firstIndex];
  3938. group->m_lastIndex = newIndices[group->m_lastIndex - 1] + 1;
  3939. }
  3940. }
  3941. /// Set the lifetime (in seconds) of a particle relative to the current
  3942. /// time.
  3943. void b2ParticleSystem::SetParticleLifetime(const int32 index,
  3944. const float32 lifetime)
  3945. {
  3946. b2Assert(ValidateParticleIndex(index));
  3947. const bool initializeExpirationTimes =
  3948. m_indexByExpirationTimeBuffer.data == NULL;
  3949. m_expirationTimeBuffer.data = RequestBuffer(
  3950. m_expirationTimeBuffer.data);
  3951. m_indexByExpirationTimeBuffer.data = RequestBuffer(
  3952. m_indexByExpirationTimeBuffer.data);
  3953. // Initialize the inverse mapping buffer.
  3954. if (initializeExpirationTimes)
  3955. {
  3956. const int32 particleCount = GetParticleCount();
  3957. for (int32 i = 0; i < particleCount; ++i)
  3958. {
  3959. m_indexByExpirationTimeBuffer.data[i] = i;
  3960. }
  3961. }
  3962. const int32 quantizedLifetime = (int32)(lifetime /
  3963. m_def.lifetimeGranularity);
  3964. // Use a negative lifetime so that it's possible to track which
  3965. // of the infinite lifetime particles are older.
  3966. const int32 newExpirationTime = quantizedLifetime > 0 ?
  3967. GetQuantizedTimeElapsed() + quantizedLifetime : quantizedLifetime;
  3968. if (newExpirationTime != m_expirationTimeBuffer.data[index])
  3969. {
  3970. m_expirationTimeBuffer.data[index] = newExpirationTime;
  3971. m_expirationTimeBufferRequiresSorting = true;
  3972. }
  3973. }
  3974. /// Convert a lifetime value in returned by GetExpirationTimeBuffer()
  3975. /// to a value in seconds relative to the current simulation time.
  3976. float32 b2ParticleSystem::ExpirationTimeToLifetime(
  3977. const int32 expirationTime) const
  3978. {
  3979. return (float32)(expirationTime > 0 ?
  3980. expirationTime - GetQuantizedTimeElapsed() :
  3981. expirationTime) * m_def.lifetimeGranularity;
  3982. }
  3983. /// Get the lifetime (in seconds) of a particle relative to the current
  3984. /// time.
  3985. float32 b2ParticleSystem::GetParticleLifetime(const int32 index)
  3986. {
  3987. b2Assert(ValidateParticleIndex(index));
  3988. return ExpirationTimeToLifetime(GetExpirationTimeBuffer()[index]);
  3989. }
  3990. /// Get the array of particle lifetimes indexed by particle index.
  3991. /// GetParticleCount() items are in the returned array.
  3992. const int32* b2ParticleSystem::GetExpirationTimeBuffer()
  3993. {
  3994. m_expirationTimeBuffer.data = RequestBuffer(
  3995. m_expirationTimeBuffer.data);
  3996. return m_expirationTimeBuffer.data;
  3997. }
  3998. /// Get the array of particle indices ordered by lifetime.
  3999. /// GetExpirationTimeBuffer(
  4000. /// GetIndexByExpirationTimeBuffer()[index])
  4001. /// is equivalent to GetParticleLifetime(index).
  4002. /// GetParticleCount() items are in the returned array.
  4003. const int32* b2ParticleSystem::GetIndexByExpirationTimeBuffer()
  4004. {
  4005. // If particles are present, initialize / reinitialize the lifetime buffer.
  4006. if (GetParticleCount())
  4007. {
  4008. SetParticleLifetime(0, GetParticleLifetime(0));
  4009. }
  4010. else
  4011. {
  4012. m_indexByExpirationTimeBuffer.data = RequestBuffer(
  4013. m_indexByExpirationTimeBuffer.data);
  4014. }
  4015. return m_indexByExpirationTimeBuffer.data;
  4016. }
  4017. void b2ParticleSystem::SetDestructionByAge(const bool enable)
  4018. {
  4019. if (enable)
  4020. {
  4021. GetExpirationTimeBuffer();
  4022. }
  4023. m_def.destroyByAge = enable;
  4024. }
  4025. /// Get the time elapsed in b2ParticleSystemDef::lifetimeGranularity.
  4026. int32 b2ParticleSystem::GetQuantizedTimeElapsed() const
  4027. {
  4028. return (int32)(m_timeElapsed >> 32);
  4029. }
  4030. /// Convert a lifetime in seconds to an expiration time.
  4031. int64 b2ParticleSystem::LifetimeToExpirationTime(const float32 lifetime) const
  4032. {
  4033. return m_timeElapsed + (int64)((lifetime / m_def.lifetimeGranularity) *
  4034. (float32)(1LL << 32));
  4035. }
  4036. template <typename T> void b2ParticleSystem::SetUserOverridableBuffer(
  4037. UserOverridableBuffer<T>* buffer, T* newData, int32 newCapacity)
  4038. {
  4039. b2Assert((newData && newCapacity) || (!newData && !newCapacity));
  4040. if (!buffer->userSuppliedCapacity && buffer->data)
  4041. {
  4042. m_world->m_blockAllocator.Free(
  4043. buffer->data, sizeof(T) * m_internalAllocatedCapacity);
  4044. }
  4045. buffer->data = newData;
  4046. buffer->userSuppliedCapacity = newCapacity;
  4047. }
  4048. void b2ParticleSystem::SetFlagsBuffer(uint32* buffer, int32 capacity)
  4049. {
  4050. SetUserOverridableBuffer(&m_flagsBuffer, buffer, capacity);
  4051. }
  4052. void b2ParticleSystem::SetPositionBuffer(b2Vec2* buffer,
  4053. int32 capacity)
  4054. {
  4055. SetUserOverridableBuffer(&m_positionBuffer, buffer, capacity);
  4056. }
  4057. void b2ParticleSystem::SetVelocityBuffer(b2Vec2* buffer,
  4058. int32 capacity)
  4059. {
  4060. SetUserOverridableBuffer(&m_velocityBuffer, buffer, capacity);
  4061. }
  4062. void b2ParticleSystem::SetColorBuffer(b2ParticleColor* buffer,
  4063. int32 capacity)
  4064. {
  4065. SetUserOverridableBuffer(&m_colorBuffer, buffer, capacity);
  4066. }
  4067. void b2ParticleSystem::SetUserDataBuffer(void** buffer, int32 capacity)
  4068. {
  4069. SetUserOverridableBuffer(&m_userDataBuffer, buffer, capacity);
  4070. }
  4071. void b2ParticleSystem::SetParticleFlags(int32 index, uint32 newFlags)
  4072. {
  4073. uint32* oldFlags = &m_flagsBuffer.data[index];
  4074. if (*oldFlags & ~newFlags)
  4075. {
  4076. // If any flags might be removed
  4077. m_needsUpdateAllParticleFlags = true;
  4078. }
  4079. if (~m_allParticleFlags & newFlags)
  4080. {
  4081. // If any flags were added
  4082. if (newFlags & b2_tensileParticle)
  4083. {
  4084. m_accumulation2Buffer = RequestBuffer(
  4085. m_accumulation2Buffer);
  4086. }
  4087. if (newFlags & b2_colorMixingParticle)
  4088. {
  4089. m_colorBuffer.data = RequestBuffer(m_colorBuffer.data);
  4090. }
  4091. m_allParticleFlags |= newFlags;
  4092. }
  4093. *oldFlags = newFlags;
  4094. }
  4095. void b2ParticleSystem::SetGroupFlags(
  4096. b2ParticleGroup* group, uint32 newFlags)
  4097. {
  4098. uint32* oldFlags = &group->m_groupFlags;
  4099. if ((*oldFlags ^ newFlags) & b2_solidParticleGroup)
  4100. {
  4101. // If the b2_solidParticleGroup flag changed schedule depth update.
  4102. newFlags |= b2_particleGroupNeedsUpdateDepth;
  4103. }
  4104. if (*oldFlags & ~newFlags)
  4105. {
  4106. // If any flags might be removed
  4107. m_needsUpdateAllGroupFlags = true;
  4108. }
  4109. if (~m_allGroupFlags & newFlags)
  4110. {
  4111. // If any flags were added
  4112. if (newFlags & b2_solidParticleGroup)
  4113. {
  4114. m_depthBuffer = RequestBuffer(m_depthBuffer);
  4115. }
  4116. m_allGroupFlags |= newFlags;
  4117. }
  4118. *oldFlags = newFlags;
  4119. }
  4120. static inline bool IsSignificantForce(const b2Vec2& force)
  4121. {
  4122. return force.x != 0 || force.y != 0;
  4123. }
  4124. inline bool b2ParticleSystem::ForceCanBeApplied(uint32 flags) const
  4125. {
  4126. return !(flags & b2_wallParticle);
  4127. }
  4128. inline void b2ParticleSystem::PrepareForceBuffer()
  4129. {
  4130. if (!m_hasForce)
  4131. {
  4132. memset(m_forceBuffer, 0, sizeof(*m_forceBuffer) * m_count);
  4133. m_hasForce = true;
  4134. }
  4135. }
  4136. void b2ParticleSystem::ApplyForce(int32 firstIndex, int32 lastIndex,
  4137. const b2Vec2& force)
  4138. {
  4139. // Ensure we're not trying to apply force to particles that can't move,
  4140. // such as wall particles.
  4141. #if B2_ASSERT_ENABLED
  4142. uint32 flags = 0;
  4143. for (int32 i = firstIndex; i < lastIndex; i++)
  4144. {
  4145. flags |= m_flagsBuffer.data[i];
  4146. }
  4147. b2Assert(ForceCanBeApplied(flags));
  4148. #endif
  4149. // Early out if force does nothing (optimization).
  4150. const b2Vec2 distributedForce = force / (float32)(lastIndex - firstIndex);
  4151. if (IsSignificantForce(distributedForce))
  4152. {
  4153. PrepareForceBuffer();
  4154. // Distribute the force over all the particles.
  4155. for (int32 i = firstIndex; i < lastIndex; i++)
  4156. {
  4157. m_forceBuffer[i] += distributedForce;
  4158. }
  4159. }
  4160. }
  4161. void b2ParticleSystem::ParticleApplyForce(int32 index, const b2Vec2& force)
  4162. {
  4163. if (IsSignificantForce(force) &&
  4164. ForceCanBeApplied(m_flagsBuffer.data[index]))
  4165. {
  4166. PrepareForceBuffer();
  4167. m_forceBuffer[index] += force;
  4168. }
  4169. }
  4170. void b2ParticleSystem::ApplyLinearImpulse(int32 firstIndex, int32 lastIndex,
  4171. const b2Vec2& impulse)
  4172. {
  4173. const float32 numParticles = (float32)(lastIndex - firstIndex);
  4174. const float32 totalMass = numParticles * GetParticleMass();
  4175. const b2Vec2 velocityDelta = impulse / totalMass;
  4176. for (int32 i = firstIndex; i < lastIndex; i++)
  4177. {
  4178. m_velocityBuffer.data[i] += velocityDelta;
  4179. }
  4180. }
  4181. void b2ParticleSystem::QueryAABB(b2QueryCallback* callback,
  4182. const b2AABB& aabb) const
  4183. {
  4184. if (m_proxyBuffer.GetCount() == 0)
  4185. {
  4186. return;
  4187. }
  4188. const Proxy* beginProxy = m_proxyBuffer.Begin();
  4189. const Proxy* endProxy = m_proxyBuffer.End();
  4190. const Proxy* firstProxy = std::lower_bound(
  4191. beginProxy, endProxy,
  4192. computeTag(
  4193. m_inverseDiameter * aabb.lowerBound.x,
  4194. m_inverseDiameter * aabb.lowerBound.y));
  4195. const Proxy* lastProxy = std::upper_bound(
  4196. firstProxy, endProxy,
  4197. computeTag(
  4198. m_inverseDiameter * aabb.upperBound.x,
  4199. m_inverseDiameter * aabb.upperBound.y));
  4200. for (const Proxy* proxy = firstProxy; proxy < lastProxy; ++proxy)
  4201. {
  4202. int32 i = proxy->index;
  4203. const b2Vec2& p = m_positionBuffer.data[i];
  4204. if (aabb.lowerBound.x < p.x && p.x < aabb.upperBound.x &&
  4205. aabb.lowerBound.y < p.y && p.y < aabb.upperBound.y)
  4206. {
  4207. if (!callback->ReportParticle(this, i))
  4208. {
  4209. break;
  4210. }
  4211. }
  4212. }
  4213. }
  4214. void b2ParticleSystem::QueryShapeAABB(b2QueryCallback* callback,
  4215. const b2Shape& shape,
  4216. const b2Transform& xf) const
  4217. {
  4218. b2AABB aabb;
  4219. shape.ComputeAABB(&aabb, xf, 0);
  4220. QueryAABB(callback, aabb);
  4221. }
  4222. void b2ParticleSystem::RayCast(b2RayCastCallback* callback,
  4223. const b2Vec2& point1,
  4224. const b2Vec2& point2) const
  4225. {
  4226. if (m_proxyBuffer.GetCount() == 0)
  4227. {
  4228. return;
  4229. }
  4230. b2AABB aabb;
  4231. aabb.lowerBound = b2Min(point1, point2);
  4232. aabb.upperBound = b2Max(point1, point2);
  4233. float32 fraction = 1;
  4234. // solving the following equation:
  4235. // ((1-t)*point1+t*point2-position)^2=diameter^2
  4236. // where t is a potential fraction
  4237. b2Vec2 v = point2 - point1;
  4238. float32 v2 = b2Dot(v, v);
  4239. InsideBoundsEnumerator enumerator = GetInsideBoundsEnumerator(aabb);
  4240. int32 i;
  4241. while ((i = enumerator.GetNext()) >= 0)
  4242. {
  4243. b2Vec2 p = point1 - m_positionBuffer.data[i];
  4244. float32 pv = b2Dot(p, v);
  4245. float32 p2 = b2Dot(p, p);
  4246. float32 determinant = pv * pv - v2 * (p2 - m_squaredDiameter);
  4247. if (determinant >= 0)
  4248. {
  4249. float32 sqrtDeterminant = b2Sqrt(determinant);
  4250. // find a solution between 0 and fraction
  4251. float32 t = (-pv - sqrtDeterminant) / v2;
  4252. if (t > fraction)
  4253. {
  4254. continue;
  4255. }
  4256. if (t < 0)
  4257. {
  4258. t = (-pv + sqrtDeterminant) / v2;
  4259. if (t < 0 || t > fraction)
  4260. {
  4261. continue;
  4262. }
  4263. }
  4264. b2Vec2 n = p + t * v;
  4265. n.Normalize();
  4266. float32 f = callback->ReportParticle(this, i, point1 + t * v, n, t);
  4267. fraction = b2Min(fraction, f);
  4268. if (fraction <= 0)
  4269. {
  4270. break;
  4271. }
  4272. }
  4273. }
  4274. }
  4275. float32 b2ParticleSystem::ComputeCollisionEnergy() const
  4276. {
  4277. float32 sum_v2 = 0;
  4278. for (int32 k = 0; k < m_contactBuffer.GetCount(); k++)
  4279. {
  4280. const b2ParticleContact& contact = m_contactBuffer[k];
  4281. int32 a = contact.GetIndexA();
  4282. int32 b = contact.GetIndexB();
  4283. b2Vec2 n = contact.GetNormal();
  4284. b2Vec2 v = m_velocityBuffer.data[b] - m_velocityBuffer.data[a];
  4285. float32 vn = b2Dot(v, n);
  4286. if (vn < 0)
  4287. {
  4288. sum_v2 += vn * vn;
  4289. }
  4290. }
  4291. return 0.5f * GetParticleMass() * sum_v2;
  4292. }
  4293. void b2ParticleSystem::SetStuckThreshold(int32 steps)
  4294. {
  4295. m_stuckThreshold = steps;
  4296. if (steps > 0)
  4297. {
  4298. m_lastBodyContactStepBuffer.data = RequestBuffer(
  4299. m_lastBodyContactStepBuffer.data);
  4300. m_bodyContactCountBuffer.data = RequestBuffer(
  4301. m_bodyContactCountBuffer.data);
  4302. m_consecutiveContactStepsBuffer.data = RequestBuffer(
  4303. m_consecutiveContactStepsBuffer.data);
  4304. }
  4305. }
  4306. #if LIQUIDFUN_EXTERNAL_LANGUAGE_API
  4307. b2ParticleSystem::b2ExceptionType b2ParticleSystem::IsBufCopyValid(
  4308. int startIndex, int numParticles, int copySize, int bufSize) const
  4309. {
  4310. const int maxNumParticles = GetParticleCount();
  4311. // are we actually copying?
  4312. if (copySize == 0)
  4313. {
  4314. return b2_noExceptions;
  4315. }
  4316. // is the index out of bounds?
  4317. if (startIndex < 0 ||
  4318. startIndex >= maxNumParticles ||
  4319. numParticles < 0 ||
  4320. numParticles + startIndex > maxNumParticles)
  4321. {
  4322. return b2_particleIndexOutOfBounds;
  4323. }
  4324. // are we copying within the boundaries?
  4325. if (copySize > bufSize)
  4326. {
  4327. return b2_bufferTooSmall;
  4328. }
  4329. return b2_noExceptions;
  4330. }
  4331. #endif // LIQUIDFUN_EXTERNAL_LANGUAGE_API