cannon-es.js 338 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023
  1. /**
  2. * Records what objects are colliding with each other
  3. */
  4. class ObjectCollisionMatrix {
  5. /**
  6. * The matrix storage.
  7. */
  8. /**
  9. * @todo Remove useless constructor
  10. */
  11. constructor() {
  12. this.matrix = {};
  13. }
  14. /**
  15. * get
  16. */
  17. get(bi, bj) {
  18. let {
  19. id: i
  20. } = bi;
  21. let {
  22. id: j
  23. } = bj;
  24. if (j > i) {
  25. const temp = j;
  26. j = i;
  27. i = temp;
  28. }
  29. return `${i}-${j}` in this.matrix;
  30. }
  31. /**
  32. * set
  33. */
  34. set(bi, bj, value) {
  35. let {
  36. id: i
  37. } = bi;
  38. let {
  39. id: j
  40. } = bj;
  41. if (j > i) {
  42. const temp = j;
  43. j = i;
  44. i = temp;
  45. }
  46. if (value) {
  47. this.matrix[`${i}-${j}`] = true;
  48. } else {
  49. delete this.matrix[`${i}-${j}`];
  50. }
  51. }
  52. /**
  53. * Empty the matrix
  54. */
  55. reset() {
  56. this.matrix = {};
  57. }
  58. /**
  59. * Set max number of objects
  60. */
  61. setNumObjects(n) {}
  62. }
  63. /**
  64. * A 3x3 matrix.
  65. * Authored by {@link http://github.com/schteppe/ schteppe}
  66. */
  67. class Mat3 {
  68. /**
  69. * A vector of length 9, containing all matrix elements.
  70. */
  71. /**
  72. * @param elements A vector of length 9, containing all matrix elements.
  73. */
  74. constructor(elements) {
  75. if (elements === void 0) {
  76. elements = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  77. }
  78. this.elements = elements;
  79. }
  80. /**
  81. * Sets the matrix to identity
  82. * @todo Should perhaps be renamed to `setIdentity()` to be more clear.
  83. * @todo Create another function that immediately creates an identity matrix eg. `eye()`
  84. */
  85. identity() {
  86. const e = this.elements;
  87. e[0] = 1;
  88. e[1] = 0;
  89. e[2] = 0;
  90. e[3] = 0;
  91. e[4] = 1;
  92. e[5] = 0;
  93. e[6] = 0;
  94. e[7] = 0;
  95. e[8] = 1;
  96. }
  97. /**
  98. * Set all elements to zero
  99. */
  100. setZero() {
  101. const e = this.elements;
  102. e[0] = 0;
  103. e[1] = 0;
  104. e[2] = 0;
  105. e[3] = 0;
  106. e[4] = 0;
  107. e[5] = 0;
  108. e[6] = 0;
  109. e[7] = 0;
  110. e[8] = 0;
  111. }
  112. /**
  113. * Sets the matrix diagonal elements from a Vec3
  114. */
  115. setTrace(vector) {
  116. const e = this.elements;
  117. e[0] = vector.x;
  118. e[4] = vector.y;
  119. e[8] = vector.z;
  120. }
  121. /**
  122. * Gets the matrix diagonal elements
  123. */
  124. getTrace(target) {
  125. if (target === void 0) {
  126. target = new Vec3();
  127. }
  128. const e = this.elements;
  129. target.x = e[0];
  130. target.y = e[4];
  131. target.z = e[8];
  132. return target;
  133. }
  134. /**
  135. * Matrix-Vector multiplication
  136. * @param v The vector to multiply with
  137. * @param target Optional, target to save the result in.
  138. */
  139. vmult(v, target) {
  140. if (target === void 0) {
  141. target = new Vec3();
  142. }
  143. const e = this.elements;
  144. const x = v.x;
  145. const y = v.y;
  146. const z = v.z;
  147. target.x = e[0] * x + e[1] * y + e[2] * z;
  148. target.y = e[3] * x + e[4] * y + e[5] * z;
  149. target.z = e[6] * x + e[7] * y + e[8] * z;
  150. return target;
  151. }
  152. /**
  153. * Matrix-scalar multiplication
  154. */
  155. smult(s) {
  156. for (let i = 0; i < this.elements.length; i++) {
  157. this.elements[i] *= s;
  158. }
  159. }
  160. /**
  161. * Matrix multiplication
  162. * @param matrix Matrix to multiply with from left side.
  163. */
  164. mmult(matrix, target) {
  165. if (target === void 0) {
  166. target = new Mat3();
  167. }
  168. const A = this.elements;
  169. const B = matrix.elements;
  170. const T = target.elements;
  171. const a11 = A[0],
  172. a12 = A[1],
  173. a13 = A[2],
  174. a21 = A[3],
  175. a22 = A[4],
  176. a23 = A[5],
  177. a31 = A[6],
  178. a32 = A[7],
  179. a33 = A[8];
  180. const b11 = B[0],
  181. b12 = B[1],
  182. b13 = B[2],
  183. b21 = B[3],
  184. b22 = B[4],
  185. b23 = B[5],
  186. b31 = B[6],
  187. b32 = B[7],
  188. b33 = B[8];
  189. T[0] = a11 * b11 + a12 * b21 + a13 * b31;
  190. T[1] = a11 * b12 + a12 * b22 + a13 * b32;
  191. T[2] = a11 * b13 + a12 * b23 + a13 * b33;
  192. T[3] = a21 * b11 + a22 * b21 + a23 * b31;
  193. T[4] = a21 * b12 + a22 * b22 + a23 * b32;
  194. T[5] = a21 * b13 + a22 * b23 + a23 * b33;
  195. T[6] = a31 * b11 + a32 * b21 + a33 * b31;
  196. T[7] = a31 * b12 + a32 * b22 + a33 * b32;
  197. T[8] = a31 * b13 + a32 * b23 + a33 * b33;
  198. return target;
  199. }
  200. /**
  201. * Scale each column of the matrix
  202. */
  203. scale(vector, target) {
  204. if (target === void 0) {
  205. target = new Mat3();
  206. }
  207. const e = this.elements;
  208. const t = target.elements;
  209. for (let i = 0; i !== 3; i++) {
  210. t[3 * i + 0] = vector.x * e[3 * i + 0];
  211. t[3 * i + 1] = vector.y * e[3 * i + 1];
  212. t[3 * i + 2] = vector.z * e[3 * i + 2];
  213. }
  214. return target;
  215. }
  216. /**
  217. * Solve Ax=b
  218. * @param b The right hand side
  219. * @param target Optional. Target vector to save in.
  220. * @return The solution x
  221. * @todo should reuse arrays
  222. */
  223. solve(b, target) {
  224. if (target === void 0) {
  225. target = new Vec3();
  226. }
  227. // Construct equations
  228. const nr = 3; // num rows
  229. const nc = 4; // num cols
  230. const eqns = [];
  231. let i;
  232. let j;
  233. for (i = 0; i < nr * nc; i++) {
  234. eqns.push(0);
  235. }
  236. for (i = 0; i < 3; i++) {
  237. for (j = 0; j < 3; j++) {
  238. eqns[i + nc * j] = this.elements[i + 3 * j];
  239. }
  240. }
  241. eqns[3 + 4 * 0] = b.x;
  242. eqns[3 + 4 * 1] = b.y;
  243. eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination
  244. let n = 3;
  245. const k = n;
  246. let np;
  247. const kp = 4; // num rows
  248. let p;
  249. do {
  250. i = k - n;
  251. if (eqns[i + nc * i] === 0) {
  252. // the pivot is null, swap lines
  253. for (j = i + 1; j < k; j++) {
  254. if (eqns[i + nc * j] !== 0) {
  255. np = kp;
  256. do {
  257. // do ligne( i ) = ligne( i ) + ligne( k )
  258. p = kp - np;
  259. eqns[p + nc * i] += eqns[p + nc * j];
  260. } while (--np);
  261. break;
  262. }
  263. }
  264. }
  265. if (eqns[i + nc * i] !== 0) {
  266. for (j = i + 1; j < k; j++) {
  267. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  268. np = kp;
  269. do {
  270. // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  271. p = kp - np;
  272. eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  273. } while (--np);
  274. }
  275. }
  276. } while (--n); // Get the solution
  277. target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2];
  278. target.y = (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1];
  279. target.x = (eqns[0 * nc + 3] - eqns[0 * nc + 2] * target.z - eqns[0 * nc + 1] * target.y) / eqns[0 * nc + 0];
  280. if (isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x === Infinity || target.y === Infinity || target.z === Infinity) {
  281. throw `Could not solve equation! Got x=[${target.toString()}], b=[${b.toString()}], A=[${this.toString()}]`;
  282. }
  283. return target;
  284. }
  285. /**
  286. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  287. * @param value If provided, the matrix element will be set to this value.
  288. */
  289. e(row, column, value) {
  290. if (value === undefined) {
  291. return this.elements[column + 3 * row];
  292. } else {
  293. // Set value
  294. this.elements[column + 3 * row] = value;
  295. }
  296. }
  297. /**
  298. * Copy another matrix into this matrix object.
  299. */
  300. copy(matrix) {
  301. for (let i = 0; i < matrix.elements.length; i++) {
  302. this.elements[i] = matrix.elements[i];
  303. }
  304. return this;
  305. }
  306. /**
  307. * Returns a string representation of the matrix.
  308. */
  309. toString() {
  310. let r = '';
  311. const sep = ',';
  312. for (let i = 0; i < 9; i++) {
  313. r += this.elements[i] + sep;
  314. }
  315. return r;
  316. }
  317. /**
  318. * reverse the matrix
  319. * @param target Target matrix to save in.
  320. * @return The solution x
  321. */
  322. reverse(target) {
  323. if (target === void 0) {
  324. target = new Mat3();
  325. }
  326. // Construct equations
  327. const nr = 3; // num rows
  328. const nc = 6; // num cols
  329. const eqns = reverse_eqns;
  330. let i;
  331. let j;
  332. for (i = 0; i < 3; i++) {
  333. for (j = 0; j < 3; j++) {
  334. eqns[i + nc * j] = this.elements[i + 3 * j];
  335. }
  336. }
  337. eqns[3 + 6 * 0] = 1;
  338. eqns[3 + 6 * 1] = 0;
  339. eqns[3 + 6 * 2] = 0;
  340. eqns[4 + 6 * 0] = 0;
  341. eqns[4 + 6 * 1] = 1;
  342. eqns[4 + 6 * 2] = 0;
  343. eqns[5 + 6 * 0] = 0;
  344. eqns[5 + 6 * 1] = 0;
  345. eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination
  346. let n = 3;
  347. const k = n;
  348. let np;
  349. const kp = nc; // num rows
  350. let p;
  351. do {
  352. i = k - n;
  353. if (eqns[i + nc * i] === 0) {
  354. // the pivot is null, swap lines
  355. for (j = i + 1; j < k; j++) {
  356. if (eqns[i + nc * j] !== 0) {
  357. np = kp;
  358. do {
  359. // do line( i ) = line( i ) + line( k )
  360. p = kp - np;
  361. eqns[p + nc * i] += eqns[p + nc * j];
  362. } while (--np);
  363. break;
  364. }
  365. }
  366. }
  367. if (eqns[i + nc * i] !== 0) {
  368. for (j = i + 1; j < k; j++) {
  369. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  370. np = kp;
  371. do {
  372. // do line( k ) = line( k ) - multiplier * line( i )
  373. p = kp - np;
  374. eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  375. } while (--np);
  376. }
  377. }
  378. } while (--n); // eliminate the upper left triangle of the matrix
  379. i = 2;
  380. do {
  381. j = i - 1;
  382. do {
  383. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  384. np = nc;
  385. do {
  386. p = nc - np;
  387. eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  388. } while (--np);
  389. } while (j--);
  390. } while (--i); // operations on the diagonal
  391. i = 2;
  392. do {
  393. const multiplier = 1 / eqns[i + nc * i];
  394. np = nc;
  395. do {
  396. p = nc - np;
  397. eqns[p + nc * i] = eqns[p + nc * i] * multiplier;
  398. } while (--np);
  399. } while (i--);
  400. i = 2;
  401. do {
  402. j = 2;
  403. do {
  404. p = eqns[nr + j + nc * i];
  405. if (isNaN(p) || p === Infinity) {
  406. throw `Could not reverse! A=[${this.toString()}]`;
  407. }
  408. target.e(i, j, p);
  409. } while (j--);
  410. } while (i--);
  411. return target;
  412. }
  413. /**
  414. * Set the matrix from a quaterion
  415. */
  416. setRotationFromQuaternion(q) {
  417. const x = q.x;
  418. const y = q.y;
  419. const z = q.z;
  420. const w = q.w;
  421. const x2 = x + x;
  422. const y2 = y + y;
  423. const z2 = z + z;
  424. const xx = x * x2;
  425. const xy = x * y2;
  426. const xz = x * z2;
  427. const yy = y * y2;
  428. const yz = y * z2;
  429. const zz = z * z2;
  430. const wx = w * x2;
  431. const wy = w * y2;
  432. const wz = w * z2;
  433. const e = this.elements;
  434. e[3 * 0 + 0] = 1 - (yy + zz);
  435. e[3 * 0 + 1] = xy - wz;
  436. e[3 * 0 + 2] = xz + wy;
  437. e[3 * 1 + 0] = xy + wz;
  438. e[3 * 1 + 1] = 1 - (xx + zz);
  439. e[3 * 1 + 2] = yz - wx;
  440. e[3 * 2 + 0] = xz - wy;
  441. e[3 * 2 + 1] = yz + wx;
  442. e[3 * 2 + 2] = 1 - (xx + yy);
  443. return this;
  444. }
  445. /**
  446. * Transpose the matrix
  447. * @param target Optional. Where to store the result.
  448. * @return The target Mat3, or a new Mat3 if target was omitted.
  449. */
  450. transpose(target) {
  451. if (target === void 0) {
  452. target = new Mat3();
  453. }
  454. const M = this.elements;
  455. const T = target.elements;
  456. let tmp; //Set diagonals
  457. T[0] = M[0];
  458. T[4] = M[4];
  459. T[8] = M[8];
  460. tmp = M[1];
  461. T[1] = M[3];
  462. T[3] = tmp;
  463. tmp = M[2];
  464. T[2] = M[6];
  465. T[6] = tmp;
  466. tmp = M[5];
  467. T[5] = M[7];
  468. T[7] = tmp;
  469. return target;
  470. }
  471. }
  472. const reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  473. /**
  474. * 3-dimensional vector
  475. * @example
  476. * const v = new Vec3(1, 2, 3)
  477. * console.log('x=' + v.x) // x=1
  478. */
  479. class Vec3 {
  480. constructor(x, y, z) {
  481. if (x === void 0) {
  482. x = 0.0;
  483. }
  484. if (y === void 0) {
  485. y = 0.0;
  486. }
  487. if (z === void 0) {
  488. z = 0.0;
  489. }
  490. this.x = x;
  491. this.y = y;
  492. this.z = z;
  493. }
  494. /**
  495. * Vector cross product
  496. * @param target Optional target to save in.
  497. */
  498. cross(vector, target) {
  499. if (target === void 0) {
  500. target = new Vec3();
  501. }
  502. const vx = vector.x;
  503. const vy = vector.y;
  504. const vz = vector.z;
  505. const x = this.x;
  506. const y = this.y;
  507. const z = this.z;
  508. target.x = y * vz - z * vy;
  509. target.y = z * vx - x * vz;
  510. target.z = x * vy - y * vx;
  511. return target;
  512. }
  513. /**
  514. * Set the vectors' 3 elements
  515. */
  516. set(x, y, z) {
  517. this.x = x;
  518. this.y = y;
  519. this.z = z;
  520. return this;
  521. }
  522. /**
  523. * Set all components of the vector to zero.
  524. */
  525. setZero() {
  526. this.x = this.y = this.z = 0;
  527. }
  528. /**
  529. * Vector addition
  530. */
  531. vadd(vector, target) {
  532. if (target) {
  533. target.x = vector.x + this.x;
  534. target.y = vector.y + this.y;
  535. target.z = vector.z + this.z;
  536. } else {
  537. return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z);
  538. }
  539. }
  540. /**
  541. * Vector subtraction
  542. * @param target Optional target to save in.
  543. */
  544. vsub(vector, target) {
  545. if (target) {
  546. target.x = this.x - vector.x;
  547. target.y = this.y - vector.y;
  548. target.z = this.z - vector.z;
  549. } else {
  550. return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z);
  551. }
  552. }
  553. /**
  554. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  555. *
  556. * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture}
  557. */
  558. crossmat() {
  559. return new Mat3([0, -this.z, this.y, this.z, 0, -this.x, -this.y, this.x, 0]);
  560. }
  561. /**
  562. * Normalize the vector. Note that this changes the values in the vector.
  563. * @return Returns the norm of the vector
  564. */
  565. normalize() {
  566. const x = this.x;
  567. const y = this.y;
  568. const z = this.z;
  569. const n = Math.sqrt(x * x + y * y + z * z);
  570. if (n > 0.0) {
  571. const invN = 1 / n;
  572. this.x *= invN;
  573. this.y *= invN;
  574. this.z *= invN;
  575. } else {
  576. // Make something up
  577. this.x = 0;
  578. this.y = 0;
  579. this.z = 0;
  580. }
  581. return n;
  582. }
  583. /**
  584. * Get the version of this vector that is of length 1.
  585. * @param target Optional target to save in
  586. * @return Returns the unit vector
  587. */
  588. unit(target) {
  589. if (target === void 0) {
  590. target = new Vec3();
  591. }
  592. const x = this.x;
  593. const y = this.y;
  594. const z = this.z;
  595. let ninv = Math.sqrt(x * x + y * y + z * z);
  596. if (ninv > 0.0) {
  597. ninv = 1.0 / ninv;
  598. target.x = x * ninv;
  599. target.y = y * ninv;
  600. target.z = z * ninv;
  601. } else {
  602. target.x = 1;
  603. target.y = 0;
  604. target.z = 0;
  605. }
  606. return target;
  607. }
  608. /**
  609. * Get the length of the vector
  610. */
  611. length() {
  612. const x = this.x;
  613. const y = this.y;
  614. const z = this.z;
  615. return Math.sqrt(x * x + y * y + z * z);
  616. }
  617. /**
  618. * Get the squared length of the vector.
  619. */
  620. lengthSquared() {
  621. return this.dot(this);
  622. }
  623. /**
  624. * Get distance from this point to another point
  625. */
  626. distanceTo(p) {
  627. const x = this.x;
  628. const y = this.y;
  629. const z = this.z;
  630. const px = p.x;
  631. const py = p.y;
  632. const pz = p.z;
  633. return Math.sqrt((px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z));
  634. }
  635. /**
  636. * Get squared distance from this point to another point
  637. */
  638. distanceSquared(p) {
  639. const x = this.x;
  640. const y = this.y;
  641. const z = this.z;
  642. const px = p.x;
  643. const py = p.y;
  644. const pz = p.z;
  645. return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z);
  646. }
  647. /**
  648. * Multiply all the components of the vector with a scalar.
  649. * @param target The vector to save the result in.
  650. */
  651. scale(scalar, target) {
  652. if (target === void 0) {
  653. target = new Vec3();
  654. }
  655. const x = this.x;
  656. const y = this.y;
  657. const z = this.z;
  658. target.x = scalar * x;
  659. target.y = scalar * y;
  660. target.z = scalar * z;
  661. return target;
  662. }
  663. /**
  664. * Multiply the vector with an other vector, component-wise.
  665. * @param target The vector to save the result in.
  666. */
  667. vmul(vector, target) {
  668. if (target === void 0) {
  669. target = new Vec3();
  670. }
  671. target.x = vector.x * this.x;
  672. target.y = vector.y * this.y;
  673. target.z = vector.z * this.z;
  674. return target;
  675. }
  676. /**
  677. * Scale a vector and add it to this vector. Save the result in "target". (target = this + vector * scalar)
  678. * @param target The vector to save the result in.
  679. */
  680. addScaledVector(scalar, vector, target) {
  681. if (target === void 0) {
  682. target = new Vec3();
  683. }
  684. target.x = this.x + scalar * vector.x;
  685. target.y = this.y + scalar * vector.y;
  686. target.z = this.z + scalar * vector.z;
  687. return target;
  688. }
  689. /**
  690. * Calculate dot product
  691. * @param vector
  692. */
  693. dot(vector) {
  694. return this.x * vector.x + this.y * vector.y + this.z * vector.z;
  695. }
  696. isZero() {
  697. return this.x === 0 && this.y === 0 && this.z === 0;
  698. }
  699. /**
  700. * Make the vector point in the opposite direction.
  701. * @param target Optional target to save in
  702. */
  703. negate(target) {
  704. if (target === void 0) {
  705. target = new Vec3();
  706. }
  707. target.x = -this.x;
  708. target.y = -this.y;
  709. target.z = -this.z;
  710. return target;
  711. }
  712. /**
  713. * Compute two artificial tangents to the vector
  714. * @param t1 Vector object to save the first tangent in
  715. * @param t2 Vector object to save the second tangent in
  716. */
  717. tangents(t1, t2) {
  718. const norm = this.length();
  719. if (norm > 0.0) {
  720. const n = Vec3_tangents_n;
  721. const inorm = 1 / norm;
  722. n.set(this.x * inorm, this.y * inorm, this.z * inorm);
  723. const randVec = Vec3_tangents_randVec;
  724. if (Math.abs(n.x) < 0.9) {
  725. randVec.set(1, 0, 0);
  726. n.cross(randVec, t1);
  727. } else {
  728. randVec.set(0, 1, 0);
  729. n.cross(randVec, t1);
  730. }
  731. n.cross(t1, t2);
  732. } else {
  733. // The normal length is zero, make something up
  734. t1.set(1, 0, 0);
  735. t2.set(0, 1, 0);
  736. }
  737. }
  738. /**
  739. * Converts to a more readable format
  740. */
  741. toString() {
  742. return `${this.x},${this.y},${this.z}`;
  743. }
  744. /**
  745. * Converts to an array
  746. */
  747. toArray() {
  748. return [this.x, this.y, this.z];
  749. }
  750. /**
  751. * Copies value of source to this vector.
  752. */
  753. copy(vector) {
  754. this.x = vector.x;
  755. this.y = vector.y;
  756. this.z = vector.z;
  757. return this;
  758. }
  759. /**
  760. * Do a linear interpolation between two vectors
  761. * @param t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.
  762. */
  763. lerp(vector, t, target) {
  764. const x = this.x;
  765. const y = this.y;
  766. const z = this.z;
  767. target.x = x + (vector.x - x) * t;
  768. target.y = y + (vector.y - y) * t;
  769. target.z = z + (vector.z - z) * t;
  770. }
  771. /**
  772. * Check if a vector equals is almost equal to another one.
  773. */
  774. almostEquals(vector, precision) {
  775. if (precision === void 0) {
  776. precision = 1e-6;
  777. }
  778. if (Math.abs(this.x - vector.x) > precision || Math.abs(this.y - vector.y) > precision || Math.abs(this.z - vector.z) > precision) {
  779. return false;
  780. }
  781. return true;
  782. }
  783. /**
  784. * Check if a vector is almost zero
  785. */
  786. almostZero(precision) {
  787. if (precision === void 0) {
  788. precision = 1e-6;
  789. }
  790. if (Math.abs(this.x) > precision || Math.abs(this.y) > precision || Math.abs(this.z) > precision) {
  791. return false;
  792. }
  793. return true;
  794. }
  795. /**
  796. * Check if the vector is anti-parallel to another vector.
  797. * @param precision Set to zero for exact comparisons
  798. */
  799. isAntiparallelTo(vector, precision) {
  800. this.negate(antip_neg);
  801. return antip_neg.almostEquals(vector, precision);
  802. }
  803. /**
  804. * Clone the vector
  805. */
  806. clone() {
  807. return new Vec3(this.x, this.y, this.z);
  808. }
  809. }
  810. Vec3.ZERO = new Vec3(0, 0, 0);
  811. Vec3.UNIT_X = new Vec3(1, 0, 0);
  812. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  813. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  814. const Vec3_tangents_n = new Vec3();
  815. const Vec3_tangents_randVec = new Vec3();
  816. const antip_neg = new Vec3();
  817. /**
  818. * Axis aligned bounding box class.
  819. */
  820. class AABB {
  821. /**
  822. * The lower bound of the bounding box
  823. */
  824. /**
  825. * The upper bound of the bounding box
  826. */
  827. constructor(options) {
  828. if (options === void 0) {
  829. options = {};
  830. }
  831. this.lowerBound = new Vec3();
  832. this.upperBound = new Vec3();
  833. if (options.lowerBound) {
  834. this.lowerBound.copy(options.lowerBound);
  835. }
  836. if (options.upperBound) {
  837. this.upperBound.copy(options.upperBound);
  838. }
  839. }
  840. /**
  841. * Set the AABB bounds from a set of points.
  842. * @param points An array of Vec3's.
  843. * @return The self object
  844. */
  845. setFromPoints(points, position, quaternion, skinSize) {
  846. const l = this.lowerBound;
  847. const u = this.upperBound;
  848. const q = quaternion; // Set to the first point
  849. l.copy(points[0]);
  850. if (q) {
  851. q.vmult(l, l);
  852. }
  853. u.copy(l);
  854. for (let i = 1; i < points.length; i++) {
  855. let p = points[i];
  856. if (q) {
  857. q.vmult(p, tmp$1);
  858. p = tmp$1;
  859. }
  860. if (p.x > u.x) {
  861. u.x = p.x;
  862. }
  863. if (p.x < l.x) {
  864. l.x = p.x;
  865. }
  866. if (p.y > u.y) {
  867. u.y = p.y;
  868. }
  869. if (p.y < l.y) {
  870. l.y = p.y;
  871. }
  872. if (p.z > u.z) {
  873. u.z = p.z;
  874. }
  875. if (p.z < l.z) {
  876. l.z = p.z;
  877. }
  878. } // Add offset
  879. if (position) {
  880. position.vadd(l, l);
  881. position.vadd(u, u);
  882. }
  883. if (skinSize) {
  884. l.x -= skinSize;
  885. l.y -= skinSize;
  886. l.z -= skinSize;
  887. u.x += skinSize;
  888. u.y += skinSize;
  889. u.z += skinSize;
  890. }
  891. return this;
  892. }
  893. /**
  894. * Copy bounds from an AABB to this AABB
  895. * @param aabb Source to copy from
  896. * @return The this object, for chainability
  897. */
  898. copy(aabb) {
  899. this.lowerBound.copy(aabb.lowerBound);
  900. this.upperBound.copy(aabb.upperBound);
  901. return this;
  902. }
  903. /**
  904. * Clone an AABB
  905. */
  906. clone() {
  907. return new AABB().copy(this);
  908. }
  909. /**
  910. * Extend this AABB so that it covers the given AABB too.
  911. */
  912. extend(aabb) {
  913. this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);
  914. this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);
  915. this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);
  916. this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);
  917. this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);
  918. this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);
  919. }
  920. /**
  921. * Returns true if the given AABB overlaps this AABB.
  922. */
  923. overlaps(aabb) {
  924. const l1 = this.lowerBound;
  925. const u1 = this.upperBound;
  926. const l2 = aabb.lowerBound;
  927. const u2 = aabb.upperBound; // l2 u2
  928. // |---------|
  929. // |--------|
  930. // l1 u1
  931. const overlapsX = l2.x <= u1.x && u1.x <= u2.x || l1.x <= u2.x && u2.x <= u1.x;
  932. const overlapsY = l2.y <= u1.y && u1.y <= u2.y || l1.y <= u2.y && u2.y <= u1.y;
  933. const overlapsZ = l2.z <= u1.z && u1.z <= u2.z || l1.z <= u2.z && u2.z <= u1.z;
  934. return overlapsX && overlapsY && overlapsZ;
  935. } // Mostly for debugging
  936. volume() {
  937. const l = this.lowerBound;
  938. const u = this.upperBound;
  939. return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);
  940. }
  941. /**
  942. * Returns true if the given AABB is fully contained in this AABB.
  943. */
  944. contains(aabb) {
  945. const l1 = this.lowerBound;
  946. const u1 = this.upperBound;
  947. const l2 = aabb.lowerBound;
  948. const u2 = aabb.upperBound; // l2 u2
  949. // |---------|
  950. // |---------------|
  951. // l1 u1
  952. return l1.x <= l2.x && u1.x >= u2.x && l1.y <= l2.y && u1.y >= u2.y && l1.z <= l2.z && u1.z >= u2.z;
  953. }
  954. getCorners(a, b, c, d, e, f, g, h) {
  955. const l = this.lowerBound;
  956. const u = this.upperBound;
  957. a.copy(l);
  958. b.set(u.x, l.y, l.z);
  959. c.set(u.x, u.y, l.z);
  960. d.set(l.x, u.y, u.z);
  961. e.set(u.x, l.y, u.z);
  962. f.set(l.x, u.y, l.z);
  963. g.set(l.x, l.y, u.z);
  964. h.copy(u);
  965. }
  966. /**
  967. * Get the representation of an AABB in another frame.
  968. * @return The "target" AABB object.
  969. */
  970. toLocalFrame(frame, target) {
  971. const corners = transformIntoFrame_corners;
  972. const a = corners[0];
  973. const b = corners[1];
  974. const c = corners[2];
  975. const d = corners[3];
  976. const e = corners[4];
  977. const f = corners[5];
  978. const g = corners[6];
  979. const h = corners[7]; // Get corners in current frame
  980. this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame
  981. for (let i = 0; i !== 8; i++) {
  982. const corner = corners[i];
  983. frame.pointToLocal(corner, corner);
  984. }
  985. return target.setFromPoints(corners);
  986. }
  987. /**
  988. * Get the representation of an AABB in the global frame.
  989. * @return The "target" AABB object.
  990. */
  991. toWorldFrame(frame, target) {
  992. const corners = transformIntoFrame_corners;
  993. const a = corners[0];
  994. const b = corners[1];
  995. const c = corners[2];
  996. const d = corners[3];
  997. const e = corners[4];
  998. const f = corners[5];
  999. const g = corners[6];
  1000. const h = corners[7]; // Get corners in current frame
  1001. this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame
  1002. for (let i = 0; i !== 8; i++) {
  1003. const corner = corners[i];
  1004. frame.pointToWorld(corner, corner);
  1005. }
  1006. return target.setFromPoints(corners);
  1007. }
  1008. /**
  1009. * Check if the AABB is hit by a ray.
  1010. */
  1011. overlapsRay(ray) {
  1012. const {
  1013. direction,
  1014. from
  1015. } = ray; // const t = 0
  1016. // ray.direction is unit direction vector of ray
  1017. const dirFracX = 1 / direction.x;
  1018. const dirFracY = 1 / direction.y;
  1019. const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
  1020. const t1 = (this.lowerBound.x - from.x) * dirFracX;
  1021. const t2 = (this.upperBound.x - from.x) * dirFracX;
  1022. const t3 = (this.lowerBound.y - from.y) * dirFracY;
  1023. const t4 = (this.upperBound.y - from.y) * dirFracY;
  1024. const t5 = (this.lowerBound.z - from.z) * dirFracZ;
  1025. const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
  1026. // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
  1027. const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
  1028. const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
  1029. if (tmax < 0) {
  1030. //t = tmax;
  1031. return false;
  1032. } // if tmin > tmax, ray doesn't intersect AABB
  1033. if (tmin > tmax) {
  1034. //t = tmax;
  1035. return false;
  1036. }
  1037. return true;
  1038. }
  1039. }
  1040. const tmp$1 = new Vec3();
  1041. const transformIntoFrame_corners = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  1042. /**
  1043. * Collision "matrix".
  1044. * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  1045. */
  1046. class ArrayCollisionMatrix {
  1047. /**
  1048. * The matrix storage.
  1049. */
  1050. constructor() {
  1051. this.matrix = [];
  1052. }
  1053. /**
  1054. * Get an element
  1055. */
  1056. get(bi, bj) {
  1057. let {
  1058. index: i
  1059. } = bi;
  1060. let {
  1061. index: j
  1062. } = bj;
  1063. if (j > i) {
  1064. const temp = j;
  1065. j = i;
  1066. i = temp;
  1067. }
  1068. return this.matrix[(i * (i + 1) >> 1) + j - 1];
  1069. }
  1070. /**
  1071. * Set an element
  1072. */
  1073. set(bi, bj, value) {
  1074. let {
  1075. index: i
  1076. } = bi;
  1077. let {
  1078. index: j
  1079. } = bj;
  1080. if (j > i) {
  1081. const temp = j;
  1082. j = i;
  1083. i = temp;
  1084. }
  1085. this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;
  1086. }
  1087. /**
  1088. * Sets all elements to zero
  1089. */
  1090. reset() {
  1091. for (let i = 0, l = this.matrix.length; i !== l; i++) {
  1092. this.matrix[i] = 0;
  1093. }
  1094. }
  1095. /**
  1096. * Sets the max number of objects
  1097. */
  1098. setNumObjects(n) {
  1099. this.matrix.length = n * (n - 1) >> 1;
  1100. }
  1101. }
  1102. /**
  1103. * Base class for objects that dispatches events.
  1104. */
  1105. class EventTarget {
  1106. /**
  1107. * Add an event listener
  1108. * @return The self object, for chainability.
  1109. */
  1110. addEventListener(type, listener) {
  1111. if (this._listeners === undefined) {
  1112. this._listeners = {};
  1113. }
  1114. const listeners = this._listeners;
  1115. if (listeners[type] === undefined) {
  1116. listeners[type] = [];
  1117. }
  1118. if (!listeners[type].includes(listener)) {
  1119. listeners[type].push(listener);
  1120. }
  1121. return this;
  1122. }
  1123. /**
  1124. * Check if an event listener is added
  1125. */
  1126. hasEventListener(type, listener) {
  1127. if (this._listeners === undefined) {
  1128. return false;
  1129. }
  1130. const listeners = this._listeners;
  1131. if (listeners[type] !== undefined && listeners[type].includes(listener)) {
  1132. return true;
  1133. }
  1134. return false;
  1135. }
  1136. /**
  1137. * Check if any event listener of the given type is added
  1138. */
  1139. hasAnyEventListener(type) {
  1140. if (this._listeners === undefined) {
  1141. return false;
  1142. }
  1143. const listeners = this._listeners;
  1144. return listeners[type] !== undefined;
  1145. }
  1146. /**
  1147. * Remove an event listener
  1148. * @return The self object, for chainability.
  1149. */
  1150. removeEventListener(type, listener) {
  1151. if (this._listeners === undefined) {
  1152. return this;
  1153. }
  1154. const listeners = this._listeners;
  1155. if (listeners[type] === undefined) {
  1156. return this;
  1157. }
  1158. const index = listeners[type].indexOf(listener);
  1159. if (index !== -1) {
  1160. listeners[type].splice(index, 1);
  1161. }
  1162. return this;
  1163. }
  1164. /**
  1165. * Emit an event.
  1166. * @return The self object, for chainability.
  1167. */
  1168. dispatchEvent(event) {
  1169. if (this._listeners === undefined) {
  1170. return this;
  1171. }
  1172. const listeners = this._listeners;
  1173. const listenerArray = listeners[event.type];
  1174. if (listenerArray !== undefined) {
  1175. event.target = this;
  1176. for (let i = 0, l = listenerArray.length; i < l; i++) {
  1177. listenerArray[i].call(this, event);
  1178. }
  1179. }
  1180. return this;
  1181. }
  1182. }
  1183. /**
  1184. * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.
  1185. * @param x Multiplier of the imaginary basis vector i.
  1186. * @param y Multiplier of the imaginary basis vector j.
  1187. * @param z Multiplier of the imaginary basis vector k.
  1188. * @param w Multiplier of the real part.
  1189. * @see http://en.wikipedia.org/wiki/Quaternion
  1190. */
  1191. class Quaternion {
  1192. constructor(x, y, z, w) {
  1193. if (x === void 0) {
  1194. x = 0;
  1195. }
  1196. if (y === void 0) {
  1197. y = 0;
  1198. }
  1199. if (z === void 0) {
  1200. z = 0;
  1201. }
  1202. if (w === void 0) {
  1203. w = 1;
  1204. }
  1205. this.x = x;
  1206. this.y = y;
  1207. this.z = z;
  1208. this.w = w;
  1209. }
  1210. /**
  1211. * Set the value of the quaternion.
  1212. */
  1213. set(x, y, z, w) {
  1214. this.x = x;
  1215. this.y = y;
  1216. this.z = z;
  1217. this.w = w;
  1218. return this;
  1219. }
  1220. /**
  1221. * Convert to a readable format
  1222. * @return "x,y,z,w"
  1223. */
  1224. toString() {
  1225. return `${this.x},${this.y},${this.z},${this.w}`;
  1226. }
  1227. /**
  1228. * Convert to an Array
  1229. * @return [x, y, z, w]
  1230. */
  1231. toArray() {
  1232. return [this.x, this.y, this.z, this.w];
  1233. }
  1234. /**
  1235. * Set the quaternion components given an axis and an angle in radians.
  1236. */
  1237. setFromAxisAngle(vector, angle) {
  1238. const s = Math.sin(angle * 0.5);
  1239. this.x = vector.x * s;
  1240. this.y = vector.y * s;
  1241. this.z = vector.z * s;
  1242. this.w = Math.cos(angle * 0.5);
  1243. return this;
  1244. }
  1245. /**
  1246. * Converts the quaternion to [ axis, angle ] representation.
  1247. * @param targetAxis A vector object to reuse for storing the axis.
  1248. * @return An array, first element is the axis and the second is the angle in radians.
  1249. */
  1250. toAxisAngle(targetAxis) {
  1251. if (targetAxis === void 0) {
  1252. targetAxis = new Vec3();
  1253. }
  1254. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  1255. const angle = 2 * Math.acos(this.w);
  1256. const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  1257. if (s < 0.001) {
  1258. // test to avoid divide by zero, s is always positive due to sqrt
  1259. // if s close to zero then direction of axis not important
  1260. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  1261. targetAxis.y = this.y;
  1262. targetAxis.z = this.z;
  1263. } else {
  1264. targetAxis.x = this.x / s; // normalise axis
  1265. targetAxis.y = this.y / s;
  1266. targetAxis.z = this.z / s;
  1267. }
  1268. return [targetAxis, angle];
  1269. }
  1270. /**
  1271. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  1272. */
  1273. setFromVectors(u, v) {
  1274. if (u.isAntiparallelTo(v)) {
  1275. const t1 = sfv_t1;
  1276. const t2 = sfv_t2;
  1277. u.tangents(t1, t2);
  1278. this.setFromAxisAngle(t1, Math.PI);
  1279. } else {
  1280. const a = u.cross(v);
  1281. this.x = a.x;
  1282. this.y = a.y;
  1283. this.z = a.z;
  1284. this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v);
  1285. this.normalize();
  1286. }
  1287. return this;
  1288. }
  1289. /**
  1290. * Multiply the quaternion with an other quaternion.
  1291. */
  1292. mult(quat, target) {
  1293. if (target === void 0) {
  1294. target = new Quaternion();
  1295. }
  1296. const ax = this.x;
  1297. const ay = this.y;
  1298. const az = this.z;
  1299. const aw = this.w;
  1300. const bx = quat.x;
  1301. const by = quat.y;
  1302. const bz = quat.z;
  1303. const bw = quat.w;
  1304. target.x = ax * bw + aw * bx + ay * bz - az * by;
  1305. target.y = ay * bw + aw * by + az * bx - ax * bz;
  1306. target.z = az * bw + aw * bz + ax * by - ay * bx;
  1307. target.w = aw * bw - ax * bx - ay * by - az * bz;
  1308. return target;
  1309. }
  1310. /**
  1311. * Get the inverse quaternion rotation.
  1312. */
  1313. inverse(target) {
  1314. if (target === void 0) {
  1315. target = new Quaternion();
  1316. }
  1317. const x = this.x;
  1318. const y = this.y;
  1319. const z = this.z;
  1320. const w = this.w;
  1321. this.conjugate(target);
  1322. const inorm2 = 1 / (x * x + y * y + z * z + w * w);
  1323. target.x *= inorm2;
  1324. target.y *= inorm2;
  1325. target.z *= inorm2;
  1326. target.w *= inorm2;
  1327. return target;
  1328. }
  1329. /**
  1330. * Get the quaternion conjugate
  1331. */
  1332. conjugate(target) {
  1333. if (target === void 0) {
  1334. target = new Quaternion();
  1335. }
  1336. target.x = -this.x;
  1337. target.y = -this.y;
  1338. target.z = -this.z;
  1339. target.w = this.w;
  1340. return target;
  1341. }
  1342. /**
  1343. * Normalize the quaternion. Note that this changes the values of the quaternion.
  1344. */
  1345. normalize() {
  1346. let l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1347. if (l === 0) {
  1348. this.x = 0;
  1349. this.y = 0;
  1350. this.z = 0;
  1351. this.w = 0;
  1352. } else {
  1353. l = 1 / l;
  1354. this.x *= l;
  1355. this.y *= l;
  1356. this.z *= l;
  1357. this.w *= l;
  1358. }
  1359. return this;
  1360. }
  1361. /**
  1362. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  1363. * @author unphased, https://github.com/unphased
  1364. */
  1365. normalizeFast() {
  1366. const f = (3.0 - (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)) / 2.0;
  1367. if (f === 0) {
  1368. this.x = 0;
  1369. this.y = 0;
  1370. this.z = 0;
  1371. this.w = 0;
  1372. } else {
  1373. this.x *= f;
  1374. this.y *= f;
  1375. this.z *= f;
  1376. this.w *= f;
  1377. }
  1378. return this;
  1379. }
  1380. /**
  1381. * Multiply the quaternion by a vector
  1382. */
  1383. vmult(v, target) {
  1384. if (target === void 0) {
  1385. target = new Vec3();
  1386. }
  1387. const x = v.x;
  1388. const y = v.y;
  1389. const z = v.z;
  1390. const qx = this.x;
  1391. const qy = this.y;
  1392. const qz = this.z;
  1393. const qw = this.w; // q*v
  1394. const ix = qw * x + qy * z - qz * y;
  1395. const iy = qw * y + qz * x - qx * z;
  1396. const iz = qw * z + qx * y - qy * x;
  1397. const iw = -qx * x - qy * y - qz * z;
  1398. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1399. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1400. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1401. return target;
  1402. }
  1403. /**
  1404. * Copies value of source to this quaternion.
  1405. * @return this
  1406. */
  1407. copy(quat) {
  1408. this.x = quat.x;
  1409. this.y = quat.y;
  1410. this.z = quat.z;
  1411. this.w = quat.w;
  1412. return this;
  1413. }
  1414. /**
  1415. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm
  1416. * @param order Three-character string, defaults to "YZX"
  1417. */
  1418. toEuler(target, order) {
  1419. if (order === void 0) {
  1420. order = 'YZX';
  1421. }
  1422. let heading;
  1423. let attitude;
  1424. let bank;
  1425. const x = this.x;
  1426. const y = this.y;
  1427. const z = this.z;
  1428. const w = this.w;
  1429. switch (order) {
  1430. case 'YZX':
  1431. const test = x * y + z * w;
  1432. if (test > 0.499) {
  1433. // singularity at north pole
  1434. heading = 2 * Math.atan2(x, w);
  1435. attitude = Math.PI / 2;
  1436. bank = 0;
  1437. }
  1438. if (test < -0.499) {
  1439. // singularity at south pole
  1440. heading = -2 * Math.atan2(x, w);
  1441. attitude = -Math.PI / 2;
  1442. bank = 0;
  1443. }
  1444. if (heading === undefined) {
  1445. const sqx = x * x;
  1446. const sqy = y * y;
  1447. const sqz = z * z;
  1448. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1449. attitude = Math.asin(2 * test); // attitude
  1450. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1451. }
  1452. break;
  1453. default:
  1454. throw new Error(`Euler order ${order} not supported yet.`);
  1455. }
  1456. target.y = heading;
  1457. target.z = attitude;
  1458. target.x = bank;
  1459. }
  1460. /**
  1461. * Set the quaternion components given Euler angle representation.
  1462. *
  1463. * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination.
  1464. *
  1465. * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference
  1466. */
  1467. setFromEuler(x, y, z, order) {
  1468. if (order === void 0) {
  1469. order = 'XYZ';
  1470. }
  1471. const c1 = Math.cos(x / 2);
  1472. const c2 = Math.cos(y / 2);
  1473. const c3 = Math.cos(z / 2);
  1474. const s1 = Math.sin(x / 2);
  1475. const s2 = Math.sin(y / 2);
  1476. const s3 = Math.sin(z / 2);
  1477. if (order === 'XYZ') {
  1478. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1479. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1480. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1481. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1482. } else if (order === 'YXZ') {
  1483. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1484. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1485. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1486. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1487. } else if (order === 'ZXY') {
  1488. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1489. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1490. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1491. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1492. } else if (order === 'ZYX') {
  1493. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1494. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1495. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1496. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1497. } else if (order === 'YZX') {
  1498. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1499. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1500. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1501. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1502. } else if (order === 'XZY') {
  1503. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1504. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1505. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1506. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1507. }
  1508. return this;
  1509. }
  1510. clone() {
  1511. return new Quaternion(this.x, this.y, this.z, this.w);
  1512. }
  1513. /**
  1514. * Performs a spherical linear interpolation between two quat
  1515. *
  1516. * @param toQuat second operand
  1517. * @param t interpolation amount between the self quaternion and toQuat
  1518. * @param target A quaternion to store the result in. If not provided, a new one will be created.
  1519. * @returns {Quaternion} The "target" object
  1520. */
  1521. slerp(toQuat, t, target) {
  1522. if (target === void 0) {
  1523. target = new Quaternion();
  1524. }
  1525. const ax = this.x;
  1526. const ay = this.y;
  1527. const az = this.z;
  1528. const aw = this.w;
  1529. let bx = toQuat.x;
  1530. let by = toQuat.y;
  1531. let bz = toQuat.z;
  1532. let bw = toQuat.w;
  1533. let omega;
  1534. let cosom;
  1535. let sinom;
  1536. let scale0;
  1537. let scale1; // calc cosine
  1538. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  1539. if (cosom < 0.0) {
  1540. cosom = -cosom;
  1541. bx = -bx;
  1542. by = -by;
  1543. bz = -bz;
  1544. bw = -bw;
  1545. } // calculate coefficients
  1546. if (1.0 - cosom > 0.000001) {
  1547. // standard case (slerp)
  1548. omega = Math.acos(cosom);
  1549. sinom = Math.sin(omega);
  1550. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  1551. scale1 = Math.sin(t * omega) / sinom;
  1552. } else {
  1553. // "from" and "to" quaternions are very close
  1554. // ... so we can do a linear interpolation
  1555. scale0 = 1.0 - t;
  1556. scale1 = t;
  1557. } // calculate final values
  1558. target.x = scale0 * ax + scale1 * bx;
  1559. target.y = scale0 * ay + scale1 * by;
  1560. target.z = scale0 * az + scale1 * bz;
  1561. target.w = scale0 * aw + scale1 * bw;
  1562. return target;
  1563. }
  1564. /**
  1565. * Rotate an absolute orientation quaternion given an angular velocity and a time step.
  1566. */
  1567. integrate(angularVelocity, dt, angularFactor, target) {
  1568. if (target === void 0) {
  1569. target = new Quaternion();
  1570. }
  1571. const ax = angularVelocity.x * angularFactor.x,
  1572. ay = angularVelocity.y * angularFactor.y,
  1573. az = angularVelocity.z * angularFactor.z,
  1574. bx = this.x,
  1575. by = this.y,
  1576. bz = this.z,
  1577. bw = this.w;
  1578. const half_dt = dt * 0.5;
  1579. target.x += half_dt * (ax * bw + ay * bz - az * by);
  1580. target.y += half_dt * (ay * bw + az * bx - ax * bz);
  1581. target.z += half_dt * (az * bw + ax * by - ay * bx);
  1582. target.w += half_dt * (-ax * bx - ay * by - az * bz);
  1583. return target;
  1584. }
  1585. }
  1586. const sfv_t1 = new Vec3();
  1587. const sfv_t2 = new Vec3();
  1588. /**
  1589. * The available shape types.
  1590. */
  1591. const SHAPE_TYPES = {
  1592. /** SPHERE */
  1593. SPHERE: 1,
  1594. /** PLANE */
  1595. PLANE: 2,
  1596. /** BOX */
  1597. BOX: 4,
  1598. /** COMPOUND */
  1599. COMPOUND: 8,
  1600. /** CONVEXPOLYHEDRON */
  1601. CONVEXPOLYHEDRON: 16,
  1602. /** HEIGHTFIELD */
  1603. HEIGHTFIELD: 32,
  1604. /** PARTICLE */
  1605. PARTICLE: 64,
  1606. /** CYLINDER */
  1607. CYLINDER: 128,
  1608. /** TRIMESH */
  1609. TRIMESH: 256
  1610. };
  1611. /**
  1612. * ShapeType
  1613. */
  1614. /**
  1615. * Base class for shapes
  1616. */
  1617. class Shape {
  1618. /**
  1619. * Identifier of the Shape.
  1620. */
  1621. /**
  1622. * The type of this shape. Must be set to an int > 0 by subclasses.
  1623. */
  1624. /**
  1625. * The local bounding sphere radius of this shape.
  1626. */
  1627. /**
  1628. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  1629. * @default true
  1630. */
  1631. /**
  1632. * @default 1
  1633. */
  1634. /**
  1635. * @default -1
  1636. */
  1637. /**
  1638. * Optional material of the shape that regulates contact properties.
  1639. */
  1640. /**
  1641. * The body to which the shape is added to.
  1642. */
  1643. /**
  1644. * All the Shape types.
  1645. */
  1646. constructor(options) {
  1647. if (options === void 0) {
  1648. options = {};
  1649. }
  1650. this.id = Shape.idCounter++;
  1651. this.type = options.type || 0;
  1652. this.boundingSphereRadius = 0;
  1653. this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;
  1654. this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;
  1655. this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;
  1656. this.material = options.material ? options.material : null;
  1657. this.body = null;
  1658. }
  1659. /**
  1660. * Computes the bounding sphere radius.
  1661. * The result is stored in the property `.boundingSphereRadius`
  1662. */
  1663. updateBoundingSphereRadius() {
  1664. throw `computeBoundingSphereRadius() not implemented for shape type ${this.type}`;
  1665. }
  1666. /**
  1667. * Get the volume of this shape
  1668. */
  1669. volume() {
  1670. throw `volume() not implemented for shape type ${this.type}`;
  1671. }
  1672. /**
  1673. * Calculates the inertia in the local frame for this shape.
  1674. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  1675. */
  1676. calculateLocalInertia(mass, target) {
  1677. throw `calculateLocalInertia() not implemented for shape type ${this.type}`;
  1678. }
  1679. /**
  1680. * @todo use abstract for these kind of methods
  1681. */
  1682. calculateWorldAABB(pos, quat, min, max) {
  1683. throw `calculateWorldAABB() not implemented for shape type ${this.type}`;
  1684. }
  1685. }
  1686. Shape.idCounter = 0;
  1687. Shape.types = SHAPE_TYPES;
  1688. /**
  1689. * Transformation utilities.
  1690. */
  1691. class Transform {
  1692. /**
  1693. * position
  1694. */
  1695. /**
  1696. * quaternion
  1697. */
  1698. constructor(options) {
  1699. if (options === void 0) {
  1700. options = {};
  1701. }
  1702. this.position = new Vec3();
  1703. this.quaternion = new Quaternion();
  1704. if (options.position) {
  1705. this.position.copy(options.position);
  1706. }
  1707. if (options.quaternion) {
  1708. this.quaternion.copy(options.quaternion);
  1709. }
  1710. }
  1711. /**
  1712. * Get a global point in local transform coordinates.
  1713. */
  1714. pointToLocal(worldPoint, result) {
  1715. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  1716. }
  1717. /**
  1718. * Get a local point in global transform coordinates.
  1719. */
  1720. pointToWorld(localPoint, result) {
  1721. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  1722. }
  1723. /**
  1724. * vectorToWorldFrame
  1725. */
  1726. vectorToWorldFrame(localVector, result) {
  1727. if (result === void 0) {
  1728. result = new Vec3();
  1729. }
  1730. this.quaternion.vmult(localVector, result);
  1731. return result;
  1732. }
  1733. /**
  1734. * pointToLocalFrame
  1735. */
  1736. static pointToLocalFrame(position, quaternion, worldPoint, result) {
  1737. if (result === void 0) {
  1738. result = new Vec3();
  1739. }
  1740. worldPoint.vsub(position, result);
  1741. quaternion.conjugate(tmpQuat$1);
  1742. tmpQuat$1.vmult(result, result);
  1743. return result;
  1744. }
  1745. /**
  1746. * pointToWorldFrame
  1747. */
  1748. static pointToWorldFrame(position, quaternion, localPoint, result) {
  1749. if (result === void 0) {
  1750. result = new Vec3();
  1751. }
  1752. quaternion.vmult(localPoint, result);
  1753. result.vadd(position, result);
  1754. return result;
  1755. }
  1756. /**
  1757. * vectorToWorldFrame
  1758. */
  1759. static vectorToWorldFrame(quaternion, localVector, result) {
  1760. if (result === void 0) {
  1761. result = new Vec3();
  1762. }
  1763. quaternion.vmult(localVector, result);
  1764. return result;
  1765. }
  1766. /**
  1767. * vectorToLocalFrame
  1768. */
  1769. static vectorToLocalFrame(position, quaternion, worldVector, result) {
  1770. if (result === void 0) {
  1771. result = new Vec3();
  1772. }
  1773. quaternion.w *= -1;
  1774. quaternion.vmult(worldVector, result);
  1775. quaternion.w *= -1;
  1776. return result;
  1777. }
  1778. }
  1779. const tmpQuat$1 = new Quaternion();
  1780. /**
  1781. * A set of polygons describing a convex shape.
  1782. *
  1783. * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  1784. * in the same 3D plane), instead these should be merged into one polygon.
  1785. *
  1786. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  1787. * @author schteppe / https://github.com/schteppe
  1788. * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  1789. *
  1790. * @todo Move the clipping functions to ContactGenerator?
  1791. * @todo Automatically merge coplanar polygons in constructor.
  1792. * @example
  1793. * const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces })
  1794. * const convexBody = new CANNON.Body({ mass: 1, shape: convexShape })
  1795. * world.addBody(convexBody)
  1796. */
  1797. class ConvexPolyhedron extends Shape {
  1798. /** vertices */
  1799. /**
  1800. * Array of integer arrays, indicating which vertices each face consists of
  1801. */
  1802. /** faceNormals */
  1803. /** worldVertices */
  1804. /** worldVerticesNeedsUpdate */
  1805. /** worldFaceNormals */
  1806. /** worldFaceNormalsNeedsUpdate */
  1807. /**
  1808. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  1809. */
  1810. /** uniqueEdges */
  1811. /**
  1812. * @param vertices An array of Vec3's
  1813. * @param faces Array of integer arrays, describing which vertices that is included in each face.
  1814. */
  1815. constructor(props) {
  1816. if (props === void 0) {
  1817. props = {};
  1818. }
  1819. const {
  1820. vertices = [],
  1821. faces = [],
  1822. normals = [],
  1823. axes,
  1824. boundingSphereRadius
  1825. } = props;
  1826. super({
  1827. type: Shape.types.CONVEXPOLYHEDRON
  1828. });
  1829. this.vertices = vertices;
  1830. this.faces = faces;
  1831. this.faceNormals = normals;
  1832. if (this.faceNormals.length === 0) {
  1833. this.computeNormals();
  1834. }
  1835. if (!boundingSphereRadius) {
  1836. this.updateBoundingSphereRadius();
  1837. } else {
  1838. this.boundingSphereRadius = boundingSphereRadius;
  1839. }
  1840. this.worldVertices = []; // World transformed version of .vertices
  1841. this.worldVerticesNeedsUpdate = true;
  1842. this.worldFaceNormals = []; // World transformed version of .faceNormals
  1843. this.worldFaceNormalsNeedsUpdate = true;
  1844. this.uniqueAxes = axes ? axes.slice() : null;
  1845. this.uniqueEdges = [];
  1846. this.computeEdges();
  1847. }
  1848. /**
  1849. * Computes uniqueEdges
  1850. */
  1851. computeEdges() {
  1852. const faces = this.faces;
  1853. const vertices = this.vertices;
  1854. const edges = this.uniqueEdges;
  1855. edges.length = 0;
  1856. const edge = new Vec3();
  1857. for (let i = 0; i !== faces.length; i++) {
  1858. const face = faces[i];
  1859. const numVertices = face.length;
  1860. for (let j = 0; j !== numVertices; j++) {
  1861. const k = (j + 1) % numVertices;
  1862. vertices[face[j]].vsub(vertices[face[k]], edge);
  1863. edge.normalize();
  1864. let found = false;
  1865. for (let p = 0; p !== edges.length; p++) {
  1866. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) {
  1867. found = true;
  1868. break;
  1869. }
  1870. }
  1871. if (!found) {
  1872. edges.push(edge.clone());
  1873. }
  1874. }
  1875. }
  1876. }
  1877. /**
  1878. * Compute the normals of the faces.
  1879. * Will reuse existing Vec3 objects in the `faceNormals` array if they exist.
  1880. */
  1881. computeNormals() {
  1882. this.faceNormals.length = this.faces.length; // Generate normals
  1883. for (let i = 0; i < this.faces.length; i++) {
  1884. // Check so all vertices exists for this face
  1885. for (let j = 0; j < this.faces[i].length; j++) {
  1886. if (!this.vertices[this.faces[i][j]]) {
  1887. throw new Error(`Vertex ${this.faces[i][j]} not found!`);
  1888. }
  1889. }
  1890. const n = this.faceNormals[i] || new Vec3();
  1891. this.getFaceNormal(i, n);
  1892. n.negate(n);
  1893. this.faceNormals[i] = n;
  1894. const vertex = this.vertices[this.faces[i][0]];
  1895. if (n.dot(vertex) < 0) {
  1896. console.error(`.faceNormals[${i}] = Vec3(${n.toString()}) looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.`);
  1897. for (let j = 0; j < this.faces[i].length; j++) {
  1898. console.warn(`.vertices[${this.faces[i][j]}] = Vec3(${this.vertices[this.faces[i][j]].toString()})`);
  1899. }
  1900. }
  1901. }
  1902. }
  1903. /**
  1904. * Compute the normal of a face from its vertices
  1905. */
  1906. getFaceNormal(i, target) {
  1907. const f = this.faces[i];
  1908. const va = this.vertices[f[0]];
  1909. const vb = this.vertices[f[1]];
  1910. const vc = this.vertices[f[2]];
  1911. ConvexPolyhedron.computeNormal(va, vb, vc, target);
  1912. }
  1913. /**
  1914. * Get face normal given 3 vertices
  1915. */
  1916. static computeNormal(va, vb, vc, target) {
  1917. const cb = new Vec3();
  1918. const ab = new Vec3();
  1919. vb.vsub(va, ab);
  1920. vc.vsub(vb, cb);
  1921. cb.cross(ab, target);
  1922. if (!target.isZero()) {
  1923. target.normalize();
  1924. }
  1925. }
  1926. /**
  1927. * @param minDist Clamp distance
  1928. * @param result The an array of contact point objects, see clipFaceAgainstHull
  1929. */
  1930. clipAgainstHull(posA, quatA, hullB, posB, quatB, separatingNormal, minDist, maxDist, result) {
  1931. const WorldNormal = new Vec3();
  1932. let closestFaceB = -1;
  1933. let dmax = -Number.MAX_VALUE;
  1934. for (let face = 0; face < hullB.faces.length; face++) {
  1935. WorldNormal.copy(hullB.faceNormals[face]);
  1936. quatB.vmult(WorldNormal, WorldNormal);
  1937. const d = WorldNormal.dot(separatingNormal);
  1938. if (d > dmax) {
  1939. dmax = d;
  1940. closestFaceB = face;
  1941. }
  1942. }
  1943. const worldVertsB1 = [];
  1944. for (let i = 0; i < hullB.faces[closestFaceB].length; i++) {
  1945. const b = hullB.vertices[hullB.faces[closestFaceB][i]];
  1946. const worldb = new Vec3();
  1947. worldb.copy(b);
  1948. quatB.vmult(worldb, worldb);
  1949. posB.vadd(worldb, worldb);
  1950. worldVertsB1.push(worldb);
  1951. }
  1952. if (closestFaceB >= 0) {
  1953. this.clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result);
  1954. }
  1955. }
  1956. /**
  1957. * Find the separating axis between this hull and another
  1958. * @param target The target vector to save the axis in
  1959. * @return Returns false if a separation is found, else true
  1960. */
  1961. findSeparatingAxis(hullB, posA, quatA, posB, quatB, target, faceListA, faceListB) {
  1962. const faceANormalWS3 = new Vec3();
  1963. const Worldnormal1 = new Vec3();
  1964. const deltaC = new Vec3();
  1965. const worldEdge0 = new Vec3();
  1966. const worldEdge1 = new Vec3();
  1967. const Cross = new Vec3();
  1968. let dmin = Number.MAX_VALUE;
  1969. const hullA = this;
  1970. if (!hullA.uniqueAxes) {
  1971. const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA
  1972. for (let i = 0; i < numFacesA; i++) {
  1973. const fi = faceListA ? faceListA[i] : i; // Get world face normal
  1974. faceANormalWS3.copy(hullA.faceNormals[fi]);
  1975. quatA.vmult(faceANormalWS3, faceANormalWS3);
  1976. const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  1977. if (d === false) {
  1978. return false;
  1979. }
  1980. if (d < dmin) {
  1981. dmin = d;
  1982. target.copy(faceANormalWS3);
  1983. }
  1984. }
  1985. } else {
  1986. // Test unique axes
  1987. for (let i = 0; i !== hullA.uniqueAxes.length; i++) {
  1988. // Get world axis
  1989. quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3);
  1990. const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  1991. if (d === false) {
  1992. return false;
  1993. }
  1994. if (d < dmin) {
  1995. dmin = d;
  1996. target.copy(faceANormalWS3);
  1997. }
  1998. }
  1999. }
  2000. if (!hullB.uniqueAxes) {
  2001. // Test face normals from hullB
  2002. const numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  2003. for (let i = 0; i < numFacesB; i++) {
  2004. const fi = faceListB ? faceListB[i] : i;
  2005. Worldnormal1.copy(hullB.faceNormals[fi]);
  2006. quatB.vmult(Worldnormal1, Worldnormal1);
  2007. const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);
  2008. if (d === false) {
  2009. return false;
  2010. }
  2011. if (d < dmin) {
  2012. dmin = d;
  2013. target.copy(Worldnormal1);
  2014. }
  2015. }
  2016. } else {
  2017. // Test unique axes in B
  2018. for (let i = 0; i !== hullB.uniqueAxes.length; i++) {
  2019. quatB.vmult(hullB.uniqueAxes[i], Worldnormal1);
  2020. const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);
  2021. if (d === false) {
  2022. return false;
  2023. }
  2024. if (d < dmin) {
  2025. dmin = d;
  2026. target.copy(Worldnormal1);
  2027. }
  2028. }
  2029. } // Test edges
  2030. for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) {
  2031. // Get world edge
  2032. quatA.vmult(hullA.uniqueEdges[e0], worldEdge0);
  2033. for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) {
  2034. // Get world edge 2
  2035. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  2036. worldEdge0.cross(worldEdge1, Cross);
  2037. if (!Cross.almostZero()) {
  2038. Cross.normalize();
  2039. const dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  2040. if (dist === false) {
  2041. return false;
  2042. }
  2043. if (dist < dmin) {
  2044. dmin = dist;
  2045. target.copy(Cross);
  2046. }
  2047. }
  2048. }
  2049. }
  2050. posB.vsub(posA, deltaC);
  2051. if (deltaC.dot(target) > 0.0) {
  2052. target.negate(target);
  2053. }
  2054. return true;
  2055. }
  2056. /**
  2057. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  2058. * @return The overlap depth, or FALSE if no penetration.
  2059. */
  2060. testSepAxis(axis, hullB, posA, quatA, posB, quatB) {
  2061. const hullA = this;
  2062. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  2063. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  2064. const maxA = maxminA[0];
  2065. const minA = maxminA[1];
  2066. const maxB = maxminB[0];
  2067. const minB = maxminB[1];
  2068. if (maxA < minB || maxB < minA) {
  2069. return false; // Separated
  2070. }
  2071. const d0 = maxA - minB;
  2072. const d1 = maxB - minA;
  2073. const depth = d0 < d1 ? d0 : d1;
  2074. return depth;
  2075. }
  2076. /**
  2077. * calculateLocalInertia
  2078. */
  2079. calculateLocalInertia(mass, target) {
  2080. // Approximate with box inertia
  2081. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  2082. const aabbmax = new Vec3();
  2083. const aabbmin = new Vec3();
  2084. this.computeLocalAABB(aabbmin, aabbmax);
  2085. const x = aabbmax.x - aabbmin.x;
  2086. const y = aabbmax.y - aabbmin.y;
  2087. const z = aabbmax.z - aabbmin.z;
  2088. target.x = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z);
  2089. target.y = 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z);
  2090. target.z = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x);
  2091. }
  2092. /**
  2093. * @param face_i Index of the face
  2094. */
  2095. getPlaneConstantOfFace(face_i) {
  2096. const f = this.faces[face_i];
  2097. const n = this.faceNormals[face_i];
  2098. const v = this.vertices[f[0]];
  2099. const c = -n.dot(v);
  2100. return c;
  2101. }
  2102. /**
  2103. * Clip a face against a hull.
  2104. * @param worldVertsB1 An array of Vec3 with vertices in the world frame.
  2105. * @param minDist Distance clamping
  2106. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  2107. */
  2108. clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result) {
  2109. const faceANormalWS = new Vec3();
  2110. const edge0 = new Vec3();
  2111. const WorldEdge0 = new Vec3();
  2112. const worldPlaneAnormal1 = new Vec3();
  2113. const planeNormalWS1 = new Vec3();
  2114. const worldA1 = new Vec3();
  2115. const localPlaneNormal = new Vec3();
  2116. const planeNormalWS = new Vec3();
  2117. const hullA = this;
  2118. const worldVertsB2 = [];
  2119. const pVtxIn = worldVertsB1;
  2120. const pVtxOut = worldVertsB2;
  2121. let closestFaceA = -1;
  2122. let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis
  2123. for (let face = 0; face < hullA.faces.length; face++) {
  2124. faceANormalWS.copy(hullA.faceNormals[face]);
  2125. quatA.vmult(faceANormalWS, faceANormalWS);
  2126. const d = faceANormalWS.dot(separatingNormal);
  2127. if (d < dmin) {
  2128. dmin = d;
  2129. closestFaceA = face;
  2130. }
  2131. }
  2132. if (closestFaceA < 0) {
  2133. return;
  2134. } // Get the face and construct connected faces
  2135. const polyA = hullA.faces[closestFaceA];
  2136. polyA.connectedFaces = [];
  2137. for (let i = 0; i < hullA.faces.length; i++) {
  2138. for (let j = 0; j < hullA.faces[i].length; j++) {
  2139. if (
  2140. /* Sharing a vertex*/
  2141. polyA.indexOf(hullA.faces[i][j]) !== -1 &&
  2142. /* Not the one we are looking for connections from */
  2143. i !== closestFaceA &&
  2144. /* Not already added */
  2145. polyA.connectedFaces.indexOf(i) === -1) {
  2146. polyA.connectedFaces.push(i);
  2147. }
  2148. }
  2149. } // Clip the polygon to the back of the planes of all faces of hull A,
  2150. // that are adjacent to the witness face
  2151. const numVerticesA = polyA.length;
  2152. for (let i = 0; i < numVerticesA; i++) {
  2153. const a = hullA.vertices[polyA[i]];
  2154. const b = hullA.vertices[polyA[(i + 1) % numVerticesA]];
  2155. a.vsub(b, edge0);
  2156. WorldEdge0.copy(edge0);
  2157. quatA.vmult(WorldEdge0, WorldEdge0);
  2158. posA.vadd(WorldEdge0, WorldEdge0);
  2159. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);
  2160. quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1);
  2161. posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1);
  2162. WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1);
  2163. planeNormalWS1.negate(planeNormalWS1);
  2164. worldA1.copy(a);
  2165. quatA.vmult(worldA1, worldA1);
  2166. posA.vadd(worldA1, worldA1);
  2167. const otherFace = polyA.connectedFaces[i];
  2168. localPlaneNormal.copy(this.faceNormals[otherFace]);
  2169. const localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  2170. planeNormalWS.copy(localPlaneNormal);
  2171. quatA.vmult(planeNormalWS, planeNormalWS);
  2172. const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane
  2173. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip
  2174. while (pVtxIn.length) {
  2175. pVtxIn.shift();
  2176. }
  2177. while (pVtxOut.length) {
  2178. pVtxIn.push(pVtxOut.shift());
  2179. }
  2180. } // only keep contact points that are behind the witness face
  2181. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  2182. const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  2183. planeNormalWS.copy(localPlaneNormal);
  2184. quatA.vmult(planeNormalWS, planeNormalWS);
  2185. const planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  2186. for (let i = 0; i < pVtxIn.length; i++) {
  2187. let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ???
  2188. if (depth <= minDist) {
  2189. console.log(`clamped: depth=${depth} to minDist=${minDist}`);
  2190. depth = minDist;
  2191. }
  2192. if (depth <= maxDist) {
  2193. const point = pVtxIn[i];
  2194. if (depth <= 1e-6) {
  2195. const p = {
  2196. point,
  2197. normal: planeNormalWS,
  2198. depth
  2199. };
  2200. result.push(p);
  2201. }
  2202. }
  2203. }
  2204. }
  2205. /**
  2206. * Clip a face in a hull against the back of a plane.
  2207. * @param planeConstant The constant in the mathematical plane equation
  2208. */
  2209. clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) {
  2210. let n_dot_first;
  2211. let n_dot_last;
  2212. const numVerts = inVertices.length;
  2213. if (numVerts < 2) {
  2214. return outVertices;
  2215. }
  2216. let firstVertex = inVertices[inVertices.length - 1];
  2217. let lastVertex = inVertices[0];
  2218. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  2219. for (let vi = 0; vi < numVerts; vi++) {
  2220. lastVertex = inVertices[vi];
  2221. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  2222. if (n_dot_first < 0) {
  2223. if (n_dot_last < 0) {
  2224. // Start < 0, end < 0, so output lastVertex
  2225. const newv = new Vec3();
  2226. newv.copy(lastVertex);
  2227. outVertices.push(newv);
  2228. } else {
  2229. // Start < 0, end >= 0, so output intersection
  2230. const newv = new Vec3();
  2231. firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
  2232. outVertices.push(newv);
  2233. }
  2234. } else {
  2235. if (n_dot_last < 0) {
  2236. // Start >= 0, end < 0 so output intersection and end
  2237. const newv = new Vec3();
  2238. firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
  2239. outVertices.push(newv);
  2240. outVertices.push(lastVertex);
  2241. }
  2242. }
  2243. firstVertex = lastVertex;
  2244. n_dot_first = n_dot_last;
  2245. }
  2246. return outVertices;
  2247. }
  2248. /**
  2249. * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false.
  2250. */
  2251. computeWorldVertices(position, quat) {
  2252. while (this.worldVertices.length < this.vertices.length) {
  2253. this.worldVertices.push(new Vec3());
  2254. }
  2255. const verts = this.vertices;
  2256. const worldVerts = this.worldVertices;
  2257. for (let i = 0; i !== this.vertices.length; i++) {
  2258. quat.vmult(verts[i], worldVerts[i]);
  2259. position.vadd(worldVerts[i], worldVerts[i]);
  2260. }
  2261. this.worldVerticesNeedsUpdate = false;
  2262. }
  2263. computeLocalAABB(aabbmin, aabbmax) {
  2264. const vertices = this.vertices;
  2265. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2266. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2267. for (let i = 0; i < this.vertices.length; i++) {
  2268. const v = vertices[i];
  2269. if (v.x < aabbmin.x) {
  2270. aabbmin.x = v.x;
  2271. } else if (v.x > aabbmax.x) {
  2272. aabbmax.x = v.x;
  2273. }
  2274. if (v.y < aabbmin.y) {
  2275. aabbmin.y = v.y;
  2276. } else if (v.y > aabbmax.y) {
  2277. aabbmax.y = v.y;
  2278. }
  2279. if (v.z < aabbmin.z) {
  2280. aabbmin.z = v.z;
  2281. } else if (v.z > aabbmax.z) {
  2282. aabbmax.z = v.z;
  2283. }
  2284. }
  2285. }
  2286. /**
  2287. * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false.
  2288. */
  2289. computeWorldFaceNormals(quat) {
  2290. const N = this.faceNormals.length;
  2291. while (this.worldFaceNormals.length < N) {
  2292. this.worldFaceNormals.push(new Vec3());
  2293. }
  2294. const normals = this.faceNormals;
  2295. const worldNormals = this.worldFaceNormals;
  2296. for (let i = 0; i !== N; i++) {
  2297. quat.vmult(normals[i], worldNormals[i]);
  2298. }
  2299. this.worldFaceNormalsNeedsUpdate = false;
  2300. }
  2301. /**
  2302. * updateBoundingSphereRadius
  2303. */
  2304. updateBoundingSphereRadius() {
  2305. // Assume points are distributed with local (0,0,0) as center
  2306. let max2 = 0;
  2307. const verts = this.vertices;
  2308. for (let i = 0; i !== verts.length; i++) {
  2309. const norm2 = verts[i].lengthSquared();
  2310. if (norm2 > max2) {
  2311. max2 = norm2;
  2312. }
  2313. }
  2314. this.boundingSphereRadius = Math.sqrt(max2);
  2315. }
  2316. /**
  2317. * calculateWorldAABB
  2318. */
  2319. calculateWorldAABB(pos, quat, min, max) {
  2320. const verts = this.vertices;
  2321. let minx;
  2322. let miny;
  2323. let minz;
  2324. let maxx;
  2325. let maxy;
  2326. let maxz;
  2327. let tempWorldVertex = new Vec3();
  2328. for (let i = 0; i < verts.length; i++) {
  2329. tempWorldVertex.copy(verts[i]);
  2330. quat.vmult(tempWorldVertex, tempWorldVertex);
  2331. pos.vadd(tempWorldVertex, tempWorldVertex);
  2332. const v = tempWorldVertex;
  2333. if (minx === undefined || v.x < minx) {
  2334. minx = v.x;
  2335. }
  2336. if (maxx === undefined || v.x > maxx) {
  2337. maxx = v.x;
  2338. }
  2339. if (miny === undefined || v.y < miny) {
  2340. miny = v.y;
  2341. }
  2342. if (maxy === undefined || v.y > maxy) {
  2343. maxy = v.y;
  2344. }
  2345. if (minz === undefined || v.z < minz) {
  2346. minz = v.z;
  2347. }
  2348. if (maxz === undefined || v.z > maxz) {
  2349. maxz = v.z;
  2350. }
  2351. }
  2352. min.set(minx, miny, minz);
  2353. max.set(maxx, maxy, maxz);
  2354. }
  2355. /**
  2356. * Get approximate convex volume
  2357. */
  2358. volume() {
  2359. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  2360. }
  2361. /**
  2362. * Get an average of all the vertices positions
  2363. */
  2364. getAveragePointLocal(target) {
  2365. if (target === void 0) {
  2366. target = new Vec3();
  2367. }
  2368. const verts = this.vertices;
  2369. for (let i = 0; i < verts.length; i++) {
  2370. target.vadd(verts[i], target);
  2371. }
  2372. target.scale(1 / verts.length, target);
  2373. return target;
  2374. }
  2375. /**
  2376. * Transform all local points. Will change the .vertices
  2377. */
  2378. transformAllPoints(offset, quat) {
  2379. const n = this.vertices.length;
  2380. const verts = this.vertices; // Apply rotation
  2381. if (quat) {
  2382. // Rotate vertices
  2383. for (let i = 0; i < n; i++) {
  2384. const v = verts[i];
  2385. quat.vmult(v, v);
  2386. } // Rotate face normals
  2387. for (let i = 0; i < this.faceNormals.length; i++) {
  2388. const v = this.faceNormals[i];
  2389. quat.vmult(v, v);
  2390. }
  2391. /*
  2392. // Rotate edges
  2393. for(let i=0; i<this.uniqueEdges.length; i++){
  2394. const v = this.uniqueEdges[i];
  2395. quat.vmult(v,v);
  2396. }*/
  2397. } // Apply offset
  2398. if (offset) {
  2399. for (let i = 0; i < n; i++) {
  2400. const v = verts[i];
  2401. v.vadd(offset, v);
  2402. }
  2403. }
  2404. }
  2405. /**
  2406. * Checks whether p is inside the polyhedra. Must be in local coords.
  2407. * The point lies outside of the convex hull of the other points if and only if the direction
  2408. * of all the vectors from it to those other points are on less than one half of a sphere around it.
  2409. * @param p A point given in local coordinates
  2410. */
  2411. pointIsInside(p) {
  2412. const verts = this.vertices;
  2413. const faces = this.faces;
  2414. const normals = this.faceNormals;
  2415. const positiveResult = null;
  2416. const pointInside = new Vec3();
  2417. this.getAveragePointLocal(pointInside);
  2418. for (let i = 0; i < this.faces.length; i++) {
  2419. let n = normals[i];
  2420. const v = verts[faces[i][0]]; // We only need one point in the face
  2421. // This dot product determines which side of the edge the point is
  2422. const vToP = new Vec3();
  2423. p.vsub(v, vToP);
  2424. const r1 = n.dot(vToP);
  2425. const vToPointInside = new Vec3();
  2426. pointInside.vsub(v, vToPointInside);
  2427. const r2 = n.dot(vToPointInside);
  2428. if (r1 < 0 && r2 > 0 || r1 > 0 && r2 < 0) {
  2429. return false; // Encountered some other sign. Exit.
  2430. }
  2431. } // If we got here, all dot products were of the same sign.
  2432. return positiveResult ? 1 : -1;
  2433. }
  2434. /**
  2435. * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis.
  2436. * Results are saved in the array maxmin.
  2437. * @param result result[0] and result[1] will be set to maximum and minimum, respectively.
  2438. */
  2439. static project(shape, axis, pos, quat, result) {
  2440. const n = shape.vertices.length;
  2441. project_worldVertex;
  2442. const localAxis = project_localAxis;
  2443. let max = 0;
  2444. let min = 0;
  2445. const localOrigin = project_localOrigin;
  2446. const vs = shape.vertices;
  2447. localOrigin.setZero(); // Transform the axis to local
  2448. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  2449. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  2450. const add = localOrigin.dot(localAxis);
  2451. min = max = vs[0].dot(localAxis);
  2452. for (let i = 1; i < n; i++) {
  2453. const val = vs[i].dot(localAxis);
  2454. if (val > max) {
  2455. max = val;
  2456. }
  2457. if (val < min) {
  2458. min = val;
  2459. }
  2460. }
  2461. min -= add;
  2462. max -= add;
  2463. if (min > max) {
  2464. // Inconsistent - swap
  2465. const temp = min;
  2466. min = max;
  2467. max = temp;
  2468. } // Output
  2469. result[0] = max;
  2470. result[1] = min;
  2471. }
  2472. }
  2473. const maxminA = [];
  2474. const maxminB = [];
  2475. const project_worldVertex = new Vec3();
  2476. const project_localAxis = new Vec3();
  2477. const project_localOrigin = new Vec3();
  2478. /**
  2479. * A 3d box shape.
  2480. * @example
  2481. * const size = 1
  2482. * const halfExtents = new CANNON.Vec3(size, size, size)
  2483. * const boxShape = new CANNON.Box(halfExtents)
  2484. * const boxBody = new CANNON.Body({ mass: 1, shape: boxShape })
  2485. * world.addBody(boxBody)
  2486. */
  2487. class Box extends Shape {
  2488. /**
  2489. * The half extents of the box.
  2490. */
  2491. /**
  2492. * Used by the contact generator to make contacts with other convex polyhedra for example.
  2493. */
  2494. constructor(halfExtents) {
  2495. super({
  2496. type: Shape.types.BOX
  2497. });
  2498. this.halfExtents = halfExtents;
  2499. this.convexPolyhedronRepresentation = null;
  2500. this.updateConvexPolyhedronRepresentation();
  2501. this.updateBoundingSphereRadius();
  2502. }
  2503. /**
  2504. * Updates the local convex polyhedron representation used for some collisions.
  2505. */
  2506. updateConvexPolyhedronRepresentation() {
  2507. const sx = this.halfExtents.x;
  2508. const sy = this.halfExtents.y;
  2509. const sz = this.halfExtents.z;
  2510. const V = Vec3;
  2511. const vertices = [new V(-sx, -sy, -sz), new V(sx, -sy, -sz), new V(sx, sy, -sz), new V(-sx, sy, -sz), new V(-sx, -sy, sz), new V(sx, -sy, sz), new V(sx, sy, sz), new V(-sx, sy, sz)];
  2512. const faces = [[3, 2, 1, 0], // -z
  2513. [4, 5, 6, 7], // +z
  2514. [5, 4, 0, 1], // -y
  2515. [2, 3, 7, 6], // +y
  2516. [0, 4, 7, 3], // -x
  2517. [1, 2, 6, 5] // +x
  2518. ];
  2519. const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)];
  2520. const h = new ConvexPolyhedron({
  2521. vertices,
  2522. faces,
  2523. axes
  2524. });
  2525. this.convexPolyhedronRepresentation = h;
  2526. h.material = this.material;
  2527. }
  2528. /**
  2529. * Calculate the inertia of the box.
  2530. */
  2531. calculateLocalInertia(mass, target) {
  2532. if (target === void 0) {
  2533. target = new Vec3();
  2534. }
  2535. Box.calculateInertia(this.halfExtents, mass, target);
  2536. return target;
  2537. }
  2538. static calculateInertia(halfExtents, mass, target) {
  2539. const e = halfExtents;
  2540. target.x = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z);
  2541. target.y = 1.0 / 12.0 * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z);
  2542. target.z = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x);
  2543. }
  2544. /**
  2545. * Get the box 6 side normals
  2546. * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  2547. * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  2548. */
  2549. getSideNormals(sixTargetVectors, quat) {
  2550. const sides = sixTargetVectors;
  2551. const ex = this.halfExtents;
  2552. sides[0].set(ex.x, 0, 0);
  2553. sides[1].set(0, ex.y, 0);
  2554. sides[2].set(0, 0, ex.z);
  2555. sides[3].set(-ex.x, 0, 0);
  2556. sides[4].set(0, -ex.y, 0);
  2557. sides[5].set(0, 0, -ex.z);
  2558. if (quat !== undefined) {
  2559. for (let i = 0; i !== sides.length; i++) {
  2560. quat.vmult(sides[i], sides[i]);
  2561. }
  2562. }
  2563. return sides;
  2564. }
  2565. /**
  2566. * Returns the volume of the box.
  2567. */
  2568. volume() {
  2569. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  2570. }
  2571. /**
  2572. * updateBoundingSphereRadius
  2573. */
  2574. updateBoundingSphereRadius() {
  2575. this.boundingSphereRadius = this.halfExtents.length();
  2576. }
  2577. /**
  2578. * forEachWorldCorner
  2579. */
  2580. forEachWorldCorner(pos, quat, callback) {
  2581. const e = this.halfExtents;
  2582. const corners = [[e.x, e.y, e.z], [-e.x, e.y, e.z], [-e.x, -e.y, e.z], [-e.x, -e.y, -e.z], [e.x, -e.y, -e.z], [e.x, e.y, -e.z], [-e.x, e.y, -e.z], [e.x, -e.y, e.z]];
  2583. for (let i = 0; i < corners.length; i++) {
  2584. worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]);
  2585. quat.vmult(worldCornerTempPos, worldCornerTempPos);
  2586. pos.vadd(worldCornerTempPos, worldCornerTempPos);
  2587. callback(worldCornerTempPos.x, worldCornerTempPos.y, worldCornerTempPos.z);
  2588. }
  2589. }
  2590. /**
  2591. * calculateWorldAABB
  2592. */
  2593. calculateWorldAABB(pos, quat, min, max) {
  2594. const e = this.halfExtents;
  2595. worldCornersTemp[0].set(e.x, e.y, e.z);
  2596. worldCornersTemp[1].set(-e.x, e.y, e.z);
  2597. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  2598. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  2599. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  2600. worldCornersTemp[5].set(e.x, e.y, -e.z);
  2601. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  2602. worldCornersTemp[7].set(e.x, -e.y, e.z);
  2603. const wc = worldCornersTemp[0];
  2604. quat.vmult(wc, wc);
  2605. pos.vadd(wc, wc);
  2606. max.copy(wc);
  2607. min.copy(wc);
  2608. for (let i = 1; i < 8; i++) {
  2609. const wc = worldCornersTemp[i];
  2610. quat.vmult(wc, wc);
  2611. pos.vadd(wc, wc);
  2612. const x = wc.x;
  2613. const y = wc.y;
  2614. const z = wc.z;
  2615. if (x > max.x) {
  2616. max.x = x;
  2617. }
  2618. if (y > max.y) {
  2619. max.y = y;
  2620. }
  2621. if (z > max.z) {
  2622. max.z = z;
  2623. }
  2624. if (x < min.x) {
  2625. min.x = x;
  2626. }
  2627. if (y < min.y) {
  2628. min.y = y;
  2629. }
  2630. if (z < min.z) {
  2631. min.z = z;
  2632. }
  2633. } // Get each axis max
  2634. // min.set(Infinity,Infinity,Infinity);
  2635. // max.set(-Infinity,-Infinity,-Infinity);
  2636. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  2637. // if(x > max.x){
  2638. // max.x = x;
  2639. // }
  2640. // if(y > max.y){
  2641. // max.y = y;
  2642. // }
  2643. // if(z > max.z){
  2644. // max.z = z;
  2645. // }
  2646. // if(x < min.x){
  2647. // min.x = x;
  2648. // }
  2649. // if(y < min.y){
  2650. // min.y = y;
  2651. // }
  2652. // if(z < min.z){
  2653. // min.z = z;
  2654. // }
  2655. // });
  2656. }
  2657. }
  2658. const worldCornerTempPos = new Vec3();
  2659. const worldCornersTemp = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  2660. /**
  2661. * BODY_TYPES
  2662. */
  2663. const BODY_TYPES = {
  2664. /** DYNAMIC */
  2665. DYNAMIC: 1,
  2666. /** STATIC */
  2667. STATIC: 2,
  2668. /** KINEMATIC */
  2669. KINEMATIC: 4
  2670. };
  2671. /**
  2672. * BodyType
  2673. */
  2674. /**
  2675. * BODY_SLEEP_STATES
  2676. */
  2677. const BODY_SLEEP_STATES = {
  2678. /** AWAKE */
  2679. AWAKE: 0,
  2680. /** SLEEPY */
  2681. SLEEPY: 1,
  2682. /** SLEEPING */
  2683. SLEEPING: 2
  2684. };
  2685. /**
  2686. * BodySleepState
  2687. */
  2688. /**
  2689. * Base class for all body types.
  2690. * @example
  2691. * const shape = new CANNON.Sphere(1)
  2692. * const body = new CANNON.Body({
  2693. * mass: 1,
  2694. * shape,
  2695. * })
  2696. * world.addBody(body)
  2697. */
  2698. class Body extends EventTarget {
  2699. /**
  2700. * Dispatched after two bodies collide. This event is dispatched on each
  2701. * of the two bodies involved in the collision.
  2702. * @event collide
  2703. * @param body The body that was involved in the collision.
  2704. * @param contact The details of the collision.
  2705. */
  2706. /**
  2707. * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
  2708. */
  2709. /**
  2710. * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
  2711. */
  2712. /**
  2713. * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
  2714. */
  2715. /**
  2716. * AWAKE
  2717. */
  2718. /**
  2719. * SLEEPY
  2720. */
  2721. /**
  2722. * SLEEPING
  2723. */
  2724. /**
  2725. * Dispatched after a sleeping body has woken up.
  2726. * @event wakeup
  2727. */
  2728. /**
  2729. * Dispatched after a body has gone in to the sleepy state.
  2730. * @event sleepy
  2731. */
  2732. /**
  2733. * Dispatched after a body has fallen asleep.
  2734. * @event sleep
  2735. */
  2736. constructor(options) {
  2737. if (options === void 0) {
  2738. options = {};
  2739. }
  2740. super();
  2741. this.id = Body.idCounter++;
  2742. this.index = -1;
  2743. this.world = null;
  2744. this.vlambda = new Vec3();
  2745. this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1;
  2746. this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1;
  2747. this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true;
  2748. this.position = new Vec3();
  2749. this.previousPosition = new Vec3();
  2750. this.interpolatedPosition = new Vec3();
  2751. this.initPosition = new Vec3();
  2752. if (options.position) {
  2753. this.position.copy(options.position);
  2754. this.previousPosition.copy(options.position);
  2755. this.interpolatedPosition.copy(options.position);
  2756. this.initPosition.copy(options.position);
  2757. }
  2758. this.velocity = new Vec3();
  2759. if (options.velocity) {
  2760. this.velocity.copy(options.velocity);
  2761. }
  2762. this.initVelocity = new Vec3();
  2763. this.force = new Vec3();
  2764. const mass = typeof options.mass === 'number' ? options.mass : 0;
  2765. this.mass = mass;
  2766. this.invMass = mass > 0 ? 1.0 / mass : 0;
  2767. this.material = options.material || null;
  2768. this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01;
  2769. this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC;
  2770. if (typeof options.type === typeof Body.STATIC) {
  2771. this.type = options.type;
  2772. }
  2773. this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true;
  2774. this.sleepState = Body.AWAKE;
  2775. this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  2776. this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1;
  2777. this.timeLastSleepy = 0;
  2778. this.wakeUpAfterNarrowphase = false;
  2779. this.torque = new Vec3();
  2780. this.quaternion = new Quaternion();
  2781. this.initQuaternion = new Quaternion();
  2782. this.previousQuaternion = new Quaternion();
  2783. this.interpolatedQuaternion = new Quaternion();
  2784. if (options.quaternion) {
  2785. this.quaternion.copy(options.quaternion);
  2786. this.initQuaternion.copy(options.quaternion);
  2787. this.previousQuaternion.copy(options.quaternion);
  2788. this.interpolatedQuaternion.copy(options.quaternion);
  2789. }
  2790. this.angularVelocity = new Vec3();
  2791. if (options.angularVelocity) {
  2792. this.angularVelocity.copy(options.angularVelocity);
  2793. }
  2794. this.initAngularVelocity = new Vec3();
  2795. this.shapes = [];
  2796. this.shapeOffsets = [];
  2797. this.shapeOrientations = [];
  2798. this.inertia = new Vec3();
  2799. this.invInertia = new Vec3();
  2800. this.invInertiaWorld = new Mat3();
  2801. this.invMassSolve = 0;
  2802. this.invInertiaSolve = new Vec3();
  2803. this.invInertiaWorldSolve = new Mat3();
  2804. this.fixedRotation = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false;
  2805. this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01;
  2806. this.linearFactor = new Vec3(1, 1, 1);
  2807. if (options.linearFactor) {
  2808. this.linearFactor.copy(options.linearFactor);
  2809. }
  2810. this.angularFactor = new Vec3(1, 1, 1);
  2811. if (options.angularFactor) {
  2812. this.angularFactor.copy(options.angularFactor);
  2813. }
  2814. this.aabb = new AABB();
  2815. this.aabbNeedsUpdate = true;
  2816. this.boundingRadius = 0;
  2817. this.wlambda = new Vec3();
  2818. this.isTrigger = Boolean(options.isTrigger);
  2819. if (options.shape) {
  2820. this.addShape(options.shape);
  2821. }
  2822. this.updateMassProperties();
  2823. }
  2824. /**
  2825. * Wake the body up.
  2826. */
  2827. wakeUp() {
  2828. const prevState = this.sleepState;
  2829. this.sleepState = Body.AWAKE;
  2830. this.wakeUpAfterNarrowphase = false;
  2831. if (prevState === Body.SLEEPING) {
  2832. this.dispatchEvent(Body.wakeupEvent);
  2833. }
  2834. }
  2835. /**
  2836. * Force body sleep
  2837. */
  2838. sleep() {
  2839. this.sleepState = Body.SLEEPING;
  2840. this.velocity.set(0, 0, 0);
  2841. this.angularVelocity.set(0, 0, 0);
  2842. this.wakeUpAfterNarrowphase = false;
  2843. }
  2844. /**
  2845. * Called every timestep to update internal sleep timer and change sleep state if needed.
  2846. * @param time The world time in seconds
  2847. */
  2848. sleepTick(time) {
  2849. if (this.allowSleep) {
  2850. const sleepState = this.sleepState;
  2851. const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared();
  2852. const speedLimitSquared = this.sleepSpeedLimit ** 2;
  2853. if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {
  2854. this.sleepState = Body.SLEEPY; // Sleepy
  2855. this.timeLastSleepy = time;
  2856. this.dispatchEvent(Body.sleepyEvent);
  2857. } else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {
  2858. this.wakeUp(); // Wake up
  2859. } else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {
  2860. this.sleep(); // Sleeping
  2861. this.dispatchEvent(Body.sleepEvent);
  2862. }
  2863. }
  2864. }
  2865. /**
  2866. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  2867. */
  2868. updateSolveMassProperties() {
  2869. if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {
  2870. this.invMassSolve = 0;
  2871. this.invInertiaSolve.setZero();
  2872. this.invInertiaWorldSolve.setZero();
  2873. } else {
  2874. this.invMassSolve = this.invMass;
  2875. this.invInertiaSolve.copy(this.invInertia);
  2876. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  2877. }
  2878. }
  2879. /**
  2880. * Convert a world point to local body frame.
  2881. */
  2882. pointToLocalFrame(worldPoint, result) {
  2883. if (result === void 0) {
  2884. result = new Vec3();
  2885. }
  2886. worldPoint.vsub(this.position, result);
  2887. this.quaternion.conjugate().vmult(result, result);
  2888. return result;
  2889. }
  2890. /**
  2891. * Convert a world vector to local body frame.
  2892. */
  2893. vectorToLocalFrame(worldVector, result) {
  2894. if (result === void 0) {
  2895. result = new Vec3();
  2896. }
  2897. this.quaternion.conjugate().vmult(worldVector, result);
  2898. return result;
  2899. }
  2900. /**
  2901. * Convert a local body point to world frame.
  2902. */
  2903. pointToWorldFrame(localPoint, result) {
  2904. if (result === void 0) {
  2905. result = new Vec3();
  2906. }
  2907. this.quaternion.vmult(localPoint, result);
  2908. result.vadd(this.position, result);
  2909. return result;
  2910. }
  2911. /**
  2912. * Convert a local body point to world frame.
  2913. */
  2914. vectorToWorldFrame(localVector, result) {
  2915. if (result === void 0) {
  2916. result = new Vec3();
  2917. }
  2918. this.quaternion.vmult(localVector, result);
  2919. return result;
  2920. }
  2921. /**
  2922. * Add a shape to the body with a local offset and orientation.
  2923. * @return The body object, for chainability.
  2924. */
  2925. addShape(shape, _offset, _orientation) {
  2926. const offset = new Vec3();
  2927. const orientation = new Quaternion();
  2928. if (_offset) {
  2929. offset.copy(_offset);
  2930. }
  2931. if (_orientation) {
  2932. orientation.copy(_orientation);
  2933. }
  2934. this.shapes.push(shape);
  2935. this.shapeOffsets.push(offset);
  2936. this.shapeOrientations.push(orientation);
  2937. this.updateMassProperties();
  2938. this.updateBoundingRadius();
  2939. this.aabbNeedsUpdate = true;
  2940. shape.body = this;
  2941. return this;
  2942. }
  2943. /**
  2944. * Remove a shape from the body.
  2945. * @return The body object, for chainability.
  2946. */
  2947. removeShape(shape) {
  2948. const index = this.shapes.indexOf(shape);
  2949. if (index === -1) {
  2950. console.warn('Shape does not belong to the body');
  2951. return this;
  2952. }
  2953. this.shapes.splice(index, 1);
  2954. this.shapeOffsets.splice(index, 1);
  2955. this.shapeOrientations.splice(index, 1);
  2956. this.updateMassProperties();
  2957. this.updateBoundingRadius();
  2958. this.aabbNeedsUpdate = true;
  2959. shape.body = null;
  2960. return this;
  2961. }
  2962. /**
  2963. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  2964. */
  2965. updateBoundingRadius() {
  2966. const shapes = this.shapes;
  2967. const shapeOffsets = this.shapeOffsets;
  2968. const N = shapes.length;
  2969. let radius = 0;
  2970. for (let i = 0; i !== N; i++) {
  2971. const shape = shapes[i];
  2972. shape.updateBoundingSphereRadius();
  2973. const offset = shapeOffsets[i].length();
  2974. const r = shape.boundingSphereRadius;
  2975. if (offset + r > radius) {
  2976. radius = offset + r;
  2977. }
  2978. }
  2979. this.boundingRadius = radius;
  2980. }
  2981. /**
  2982. * Updates the .aabb
  2983. */
  2984. updateAABB() {
  2985. const shapes = this.shapes;
  2986. const shapeOffsets = this.shapeOffsets;
  2987. const shapeOrientations = this.shapeOrientations;
  2988. const N = shapes.length;
  2989. const offset = tmpVec;
  2990. const orientation = tmpQuat;
  2991. const bodyQuat = this.quaternion;
  2992. const aabb = this.aabb;
  2993. const shapeAABB = updateAABB_shapeAABB;
  2994. for (let i = 0; i !== N; i++) {
  2995. const shape = shapes[i]; // Get shape world position
  2996. bodyQuat.vmult(shapeOffsets[i], offset);
  2997. offset.vadd(this.position, offset); // Get shape world quaternion
  2998. bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB
  2999. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  3000. if (i === 0) {
  3001. aabb.copy(shapeAABB);
  3002. } else {
  3003. aabb.extend(shapeAABB);
  3004. }
  3005. }
  3006. this.aabbNeedsUpdate = false;
  3007. }
  3008. /**
  3009. * Update `.inertiaWorld` and `.invInertiaWorld`
  3010. */
  3011. updateInertiaWorld(force) {
  3012. const I = this.invInertia;
  3013. if (I.x === I.y && I.y === I.z && !force) ; else {
  3014. const m1 = uiw_m1;
  3015. const m2 = uiw_m2;
  3016. uiw_m3;
  3017. m1.setRotationFromQuaternion(this.quaternion);
  3018. m1.transpose(m2);
  3019. m1.scale(I, m1);
  3020. m1.mmult(m2, this.invInertiaWorld);
  3021. }
  3022. }
  3023. /**
  3024. * Apply force to a point of the body. This could for example be a point on the Body surface.
  3025. * Applying force this way will add to Body.force and Body.torque.
  3026. * @param force The amount of force to add.
  3027. * @param relativePoint A point relative to the center of mass to apply the force on.
  3028. */
  3029. applyForce(force, relativePoint) {
  3030. if (relativePoint === void 0) {
  3031. relativePoint = new Vec3();
  3032. }
  3033. // Needed?
  3034. if (this.type !== Body.DYNAMIC) {
  3035. return;
  3036. }
  3037. if (this.sleepState === Body.SLEEPING) {
  3038. this.wakeUp();
  3039. } // Compute produced rotational force
  3040. const rotForce = Body_applyForce_rotForce;
  3041. relativePoint.cross(force, rotForce); // Add linear force
  3042. this.force.vadd(force, this.force); // Add rotational force
  3043. this.torque.vadd(rotForce, this.torque);
  3044. }
  3045. /**
  3046. * Apply force to a local point in the body.
  3047. * @param force The force vector to apply, defined locally in the body frame.
  3048. * @param localPoint A local point in the body to apply the force on.
  3049. */
  3050. applyLocalForce(localForce, localPoint) {
  3051. if (localPoint === void 0) {
  3052. localPoint = new Vec3();
  3053. }
  3054. if (this.type !== Body.DYNAMIC) {
  3055. return;
  3056. }
  3057. const worldForce = Body_applyLocalForce_worldForce;
  3058. const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space
  3059. this.vectorToWorldFrame(localForce, worldForce);
  3060. this.vectorToWorldFrame(localPoint, relativePointWorld);
  3061. this.applyForce(worldForce, relativePointWorld);
  3062. }
  3063. /**
  3064. * Apply torque to the body.
  3065. * @param torque The amount of torque to add.
  3066. */
  3067. applyTorque(torque) {
  3068. if (this.type !== Body.DYNAMIC) {
  3069. return;
  3070. }
  3071. if (this.sleepState === Body.SLEEPING) {
  3072. this.wakeUp();
  3073. } // Add rotational force
  3074. this.torque.vadd(torque, this.torque);
  3075. }
  3076. /**
  3077. * Apply impulse to a point of the body. This could for example be a point on the Body surface.
  3078. * An impulse is a force added to a body during a short period of time (impulse = force * time).
  3079. * Impulses will be added to Body.velocity and Body.angularVelocity.
  3080. * @param impulse The amount of impulse to add.
  3081. * @param relativePoint A point relative to the center of mass to apply the force on.
  3082. */
  3083. applyImpulse(impulse, relativePoint) {
  3084. if (relativePoint === void 0) {
  3085. relativePoint = new Vec3();
  3086. }
  3087. if (this.type !== Body.DYNAMIC) {
  3088. return;
  3089. }
  3090. if (this.sleepState === Body.SLEEPING) {
  3091. this.wakeUp();
  3092. } // Compute point position relative to the body center
  3093. const r = relativePoint; // Compute produced central impulse velocity
  3094. const velo = Body_applyImpulse_velo;
  3095. velo.copy(impulse);
  3096. velo.scale(this.invMass, velo); // Add linear impulse
  3097. this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity
  3098. const rotVelo = Body_applyImpulse_rotVelo;
  3099. r.cross(impulse, rotVelo);
  3100. /*
  3101. rotVelo.x *= this.invInertia.x;
  3102. rotVelo.y *= this.invInertia.y;
  3103. rotVelo.z *= this.invInertia.z;
  3104. */
  3105. this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse
  3106. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  3107. }
  3108. /**
  3109. * Apply locally-defined impulse to a local point in the body.
  3110. * @param force The force vector to apply, defined locally in the body frame.
  3111. * @param localPoint A local point in the body to apply the force on.
  3112. */
  3113. applyLocalImpulse(localImpulse, localPoint) {
  3114. if (localPoint === void 0) {
  3115. localPoint = new Vec3();
  3116. }
  3117. if (this.type !== Body.DYNAMIC) {
  3118. return;
  3119. }
  3120. const worldImpulse = Body_applyLocalImpulse_worldImpulse;
  3121. const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space
  3122. this.vectorToWorldFrame(localImpulse, worldImpulse);
  3123. this.vectorToWorldFrame(localPoint, relativePointWorld);
  3124. this.applyImpulse(worldImpulse, relativePointWorld);
  3125. }
  3126. /**
  3127. * Should be called whenever you change the body shape or mass.
  3128. */
  3129. updateMassProperties() {
  3130. const halfExtents = Body_updateMassProperties_halfExtents;
  3131. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  3132. const I = this.inertia;
  3133. const fixed = this.fixedRotation; // Approximate with AABB box
  3134. this.updateAABB();
  3135. halfExtents.set((this.aabb.upperBound.x - this.aabb.lowerBound.x) / 2, (this.aabb.upperBound.y - this.aabb.lowerBound.y) / 2, (this.aabb.upperBound.z - this.aabb.lowerBound.z) / 2);
  3136. Box.calculateInertia(halfExtents, this.mass, I);
  3137. this.invInertia.set(I.x > 0 && !fixed ? 1.0 / I.x : 0, I.y > 0 && !fixed ? 1.0 / I.y : 0, I.z > 0 && !fixed ? 1.0 / I.z : 0);
  3138. this.updateInertiaWorld(true);
  3139. }
  3140. /**
  3141. * Get world velocity of a point in the body.
  3142. * @param worldPoint
  3143. * @param result
  3144. * @return The result vector.
  3145. */
  3146. getVelocityAtWorldPoint(worldPoint, result) {
  3147. const r = new Vec3();
  3148. worldPoint.vsub(this.position, r);
  3149. this.angularVelocity.cross(r, result);
  3150. this.velocity.vadd(result, result);
  3151. return result;
  3152. }
  3153. /**
  3154. * Move the body forward in time.
  3155. * @param dt Time step
  3156. * @param quatNormalize Set to true to normalize the body quaternion
  3157. * @param quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
  3158. */
  3159. integrate(dt, quatNormalize, quatNormalizeFast) {
  3160. // Save previous position
  3161. this.previousPosition.copy(this.position);
  3162. this.previousQuaternion.copy(this.quaternion);
  3163. if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {
  3164. // Only for dynamic
  3165. return;
  3166. }
  3167. const velo = this.velocity;
  3168. const angularVelo = this.angularVelocity;
  3169. const pos = this.position;
  3170. const force = this.force;
  3171. const torque = this.torque;
  3172. const quat = this.quaternion;
  3173. const invMass = this.invMass;
  3174. const invInertia = this.invInertiaWorld;
  3175. const linearFactor = this.linearFactor;
  3176. const iMdt = invMass * dt;
  3177. velo.x += force.x * iMdt * linearFactor.x;
  3178. velo.y += force.y * iMdt * linearFactor.y;
  3179. velo.z += force.z * iMdt * linearFactor.z;
  3180. const e = invInertia.elements;
  3181. const angularFactor = this.angularFactor;
  3182. const tx = torque.x * angularFactor.x;
  3183. const ty = torque.y * angularFactor.y;
  3184. const tz = torque.z * angularFactor.z;
  3185. angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);
  3186. angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);
  3187. angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz); // Use new velocity - leap frog
  3188. pos.x += velo.x * dt;
  3189. pos.y += velo.y * dt;
  3190. pos.z += velo.z * dt;
  3191. quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);
  3192. if (quatNormalize) {
  3193. if (quatNormalizeFast) {
  3194. quat.normalizeFast();
  3195. } else {
  3196. quat.normalize();
  3197. }
  3198. }
  3199. this.aabbNeedsUpdate = true; // Update world inertia
  3200. this.updateInertiaWorld();
  3201. }
  3202. }
  3203. Body.idCounter = 0;
  3204. Body.COLLIDE_EVENT_NAME = 'collide';
  3205. Body.DYNAMIC = BODY_TYPES.DYNAMIC;
  3206. Body.STATIC = BODY_TYPES.STATIC;
  3207. Body.KINEMATIC = BODY_TYPES.KINEMATIC;
  3208. Body.AWAKE = BODY_SLEEP_STATES.AWAKE;
  3209. Body.SLEEPY = BODY_SLEEP_STATES.SLEEPY;
  3210. Body.SLEEPING = BODY_SLEEP_STATES.SLEEPING;
  3211. Body.wakeupEvent = {
  3212. type: 'wakeup'
  3213. };
  3214. Body.sleepyEvent = {
  3215. type: 'sleepy'
  3216. };
  3217. Body.sleepEvent = {
  3218. type: 'sleep'
  3219. };
  3220. const tmpVec = new Vec3();
  3221. const tmpQuat = new Quaternion();
  3222. const updateAABB_shapeAABB = new AABB();
  3223. const uiw_m1 = new Mat3();
  3224. const uiw_m2 = new Mat3();
  3225. const uiw_m3 = new Mat3();
  3226. const Body_applyForce_rotForce = new Vec3();
  3227. const Body_applyLocalForce_worldForce = new Vec3();
  3228. const Body_applyLocalForce_relativePointWorld = new Vec3();
  3229. const Body_applyImpulse_velo = new Vec3();
  3230. const Body_applyImpulse_rotVelo = new Vec3();
  3231. const Body_applyLocalImpulse_worldImpulse = new Vec3();
  3232. const Body_applyLocalImpulse_relativePoint = new Vec3();
  3233. const Body_updateMassProperties_halfExtents = new Vec3();
  3234. /**
  3235. * Base class for broadphase implementations
  3236. * @author schteppe
  3237. */
  3238. class Broadphase {
  3239. /**
  3240. * The world to search for collisions in.
  3241. */
  3242. /**
  3243. * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres.
  3244. */
  3245. /**
  3246. * Set to true if the objects in the world moved.
  3247. */
  3248. constructor() {
  3249. this.world = null;
  3250. this.useBoundingBoxes = false;
  3251. this.dirty = true;
  3252. }
  3253. /**
  3254. * Get the collision pairs from the world
  3255. * @param world The world to search in
  3256. * @param p1 Empty array to be filled with body objects
  3257. * @param p2 Empty array to be filled with body objects
  3258. */
  3259. collisionPairs(world, p1, p2) {
  3260. throw new Error('collisionPairs not implemented for this BroadPhase class!');
  3261. }
  3262. /**
  3263. * Check if a body pair needs to be intersection tested at all.
  3264. */
  3265. needBroadphaseCollision(bodyA, bodyB) {
  3266. // Check collision filter masks
  3267. if ((bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0) {
  3268. return false;
  3269. } // Check types
  3270. if (((bodyA.type & Body.STATIC) !== 0 || bodyA.sleepState === Body.SLEEPING) && ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING)) {
  3271. // Both bodies are static or sleeping. Skip.
  3272. return false;
  3273. }
  3274. return true;
  3275. }
  3276. /**
  3277. * Check if the bounding volumes of two bodies intersect.
  3278. */
  3279. intersectionTest(bodyA, bodyB, pairs1, pairs2) {
  3280. if (this.useBoundingBoxes) {
  3281. this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2);
  3282. } else {
  3283. this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2);
  3284. }
  3285. }
  3286. /**
  3287. * Check if the bounding spheres of two bodies are intersecting.
  3288. * @param pairs1 bodyA is appended to this array if intersection
  3289. * @param pairs2 bodyB is appended to this array if intersection
  3290. */
  3291. doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) {
  3292. const r = Broadphase_collisionPairs_r;
  3293. bodyB.position.vsub(bodyA.position, r);
  3294. const boundingRadiusSum2 = (bodyA.boundingRadius + bodyB.boundingRadius) ** 2;
  3295. const norm2 = r.lengthSquared();
  3296. if (norm2 < boundingRadiusSum2) {
  3297. pairs1.push(bodyA);
  3298. pairs2.push(bodyB);
  3299. }
  3300. }
  3301. /**
  3302. * Check if the bounding boxes of two bodies are intersecting.
  3303. */
  3304. doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) {
  3305. if (bodyA.aabbNeedsUpdate) {
  3306. bodyA.updateAABB();
  3307. }
  3308. if (bodyB.aabbNeedsUpdate) {
  3309. bodyB.updateAABB();
  3310. } // Check AABB / AABB
  3311. if (bodyA.aabb.overlaps(bodyB.aabb)) {
  3312. pairs1.push(bodyA);
  3313. pairs2.push(bodyB);
  3314. }
  3315. }
  3316. /**
  3317. * Removes duplicate pairs from the pair arrays.
  3318. */
  3319. makePairsUnique(pairs1, pairs2) {
  3320. const t = Broadphase_makePairsUnique_temp;
  3321. const p1 = Broadphase_makePairsUnique_p1;
  3322. const p2 = Broadphase_makePairsUnique_p2;
  3323. const N = pairs1.length;
  3324. for (let i = 0; i !== N; i++) {
  3325. p1[i] = pairs1[i];
  3326. p2[i] = pairs2[i];
  3327. }
  3328. pairs1.length = 0;
  3329. pairs2.length = 0;
  3330. for (let i = 0; i !== N; i++) {
  3331. const id1 = p1[i].id;
  3332. const id2 = p2[i].id;
  3333. const key = id1 < id2 ? `${id1},${id2}` : `${id2},${id1}`;
  3334. t[key] = i;
  3335. t.keys.push(key);
  3336. }
  3337. for (let i = 0; i !== t.keys.length; i++) {
  3338. const key = t.keys.pop();
  3339. const pairIndex = t[key];
  3340. pairs1.push(p1[pairIndex]);
  3341. pairs2.push(p2[pairIndex]);
  3342. delete t[key];
  3343. }
  3344. }
  3345. /**
  3346. * To be implemented by subcasses
  3347. */
  3348. setWorld(world) {}
  3349. /**
  3350. * Check if the bounding spheres of two bodies overlap.
  3351. */
  3352. static boundingSphereCheck(bodyA, bodyB) {
  3353. const dist = new Vec3(); // bsc_dist;
  3354. bodyA.position.vsub(bodyB.position, dist);
  3355. const sa = bodyA.shapes[0];
  3356. const sb = bodyB.shapes[0];
  3357. return Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > dist.lengthSquared();
  3358. }
  3359. /**
  3360. * Returns all the bodies within the AABB.
  3361. */
  3362. aabbQuery(world, aabb, result) {
  3363. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  3364. return [];
  3365. }
  3366. } // Temp objects
  3367. const Broadphase_collisionPairs_r = new Vec3();
  3368. new Vec3();
  3369. new Quaternion();
  3370. new Vec3();
  3371. const Broadphase_makePairsUnique_temp = {
  3372. keys: []
  3373. };
  3374. const Broadphase_makePairsUnique_p1 = [];
  3375. const Broadphase_makePairsUnique_p2 = [];
  3376. new Vec3();
  3377. /**
  3378. * Axis aligned uniform grid broadphase.
  3379. * @todo Needs support for more than just planes and spheres.
  3380. */
  3381. class GridBroadphase extends Broadphase {
  3382. /**
  3383. * Number of boxes along x
  3384. */
  3385. /**
  3386. * Number of boxes along y
  3387. */
  3388. /**
  3389. * Number of boxes along z
  3390. */
  3391. /**
  3392. * aabbMin
  3393. */
  3394. /**
  3395. * aabbMax
  3396. */
  3397. /**
  3398. * bins
  3399. */
  3400. /**
  3401. * binLengths
  3402. */
  3403. /**
  3404. * @param nx Number of boxes along x.
  3405. * @param ny Number of boxes along y.
  3406. * @param nz Number of boxes along z.
  3407. */
  3408. constructor(aabbMin, aabbMax, nx, ny, nz) {
  3409. if (aabbMin === void 0) {
  3410. aabbMin = new Vec3(100, 100, 100);
  3411. }
  3412. if (aabbMax === void 0) {
  3413. aabbMax = new Vec3(-100, -100, -100);
  3414. }
  3415. if (nx === void 0) {
  3416. nx = 10;
  3417. }
  3418. if (ny === void 0) {
  3419. ny = 10;
  3420. }
  3421. if (nz === void 0) {
  3422. nz = 10;
  3423. }
  3424. super();
  3425. this.nx = nx;
  3426. this.ny = ny;
  3427. this.nz = nz;
  3428. this.aabbMin = aabbMin;
  3429. this.aabbMax = aabbMax;
  3430. const nbins = this.nx * this.ny * this.nz;
  3431. if (nbins <= 0) {
  3432. throw "GridBroadphase: Each dimension's n must be >0";
  3433. }
  3434. this.bins = [];
  3435. this.binLengths = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  3436. this.bins.length = nbins;
  3437. this.binLengths.length = nbins;
  3438. for (let i = 0; i < nbins; i++) {
  3439. this.bins[i] = [];
  3440. this.binLengths[i] = 0;
  3441. }
  3442. }
  3443. /**
  3444. * Get all the collision pairs in the physics world
  3445. */
  3446. collisionPairs(world, pairs1, pairs2) {
  3447. const N = world.bodies.length;
  3448. const bodies = world.bodies;
  3449. const max = this.aabbMax;
  3450. const min = this.aabbMin;
  3451. const nx = this.nx;
  3452. const ny = this.ny;
  3453. const nz = this.nz;
  3454. const xstep = ny * nz;
  3455. const ystep = nz;
  3456. const zstep = 1;
  3457. const xmax = max.x;
  3458. const ymax = max.y;
  3459. const zmax = max.z;
  3460. const xmin = min.x;
  3461. const ymin = min.y;
  3462. const zmin = min.z;
  3463. const xmult = nx / (xmax - xmin);
  3464. const ymult = ny / (ymax - ymin);
  3465. const zmult = nz / (zmax - zmin);
  3466. const binsizeX = (xmax - xmin) / nx;
  3467. const binsizeY = (ymax - ymin) / ny;
  3468. const binsizeZ = (zmax - zmin) / nz;
  3469. const binRadius = Math.sqrt(binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ) * 0.5;
  3470. const types = Shape.types;
  3471. const SPHERE = types.SPHERE;
  3472. const PLANE = types.PLANE;
  3473. types.BOX;
  3474. types.COMPOUND;
  3475. types.CONVEXPOLYHEDRON;
  3476. const bins = this.bins;
  3477. const binLengths = this.binLengths;
  3478. const Nbins = this.bins.length; // Reset bins
  3479. for (let i = 0; i !== Nbins; i++) {
  3480. binLengths[i] = 0;
  3481. }
  3482. const ceil = Math.ceil;
  3483. function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) {
  3484. let xoff0 = (x0 - xmin) * xmult | 0;
  3485. let yoff0 = (y0 - ymin) * ymult | 0;
  3486. let zoff0 = (z0 - zmin) * zmult | 0;
  3487. let xoff1 = ceil((x1 - xmin) * xmult);
  3488. let yoff1 = ceil((y1 - ymin) * ymult);
  3489. let zoff1 = ceil((z1 - zmin) * zmult);
  3490. if (xoff0 < 0) {
  3491. xoff0 = 0;
  3492. } else if (xoff0 >= nx) {
  3493. xoff0 = nx - 1;
  3494. }
  3495. if (yoff0 < 0) {
  3496. yoff0 = 0;
  3497. } else if (yoff0 >= ny) {
  3498. yoff0 = ny - 1;
  3499. }
  3500. if (zoff0 < 0) {
  3501. zoff0 = 0;
  3502. } else if (zoff0 >= nz) {
  3503. zoff0 = nz - 1;
  3504. }
  3505. if (xoff1 < 0) {
  3506. xoff1 = 0;
  3507. } else if (xoff1 >= nx) {
  3508. xoff1 = nx - 1;
  3509. }
  3510. if (yoff1 < 0) {
  3511. yoff1 = 0;
  3512. } else if (yoff1 >= ny) {
  3513. yoff1 = ny - 1;
  3514. }
  3515. if (zoff1 < 0) {
  3516. zoff1 = 0;
  3517. } else if (zoff1 >= nz) {
  3518. zoff1 = nz - 1;
  3519. }
  3520. xoff0 *= xstep;
  3521. yoff0 *= ystep;
  3522. zoff0 *= zstep;
  3523. xoff1 *= xstep;
  3524. yoff1 *= ystep;
  3525. zoff1 *= zstep;
  3526. for (let xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  3527. for (let yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  3528. for (let zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  3529. const idx = xoff + yoff + zoff;
  3530. bins[idx][binLengths[idx]++] = bi;
  3531. }
  3532. }
  3533. }
  3534. } // Put all bodies into the bins
  3535. for (let i = 0; i !== N; i++) {
  3536. const bi = bodies[i];
  3537. const si = bi.shapes[0];
  3538. switch (si.type) {
  3539. case SPHERE:
  3540. {
  3541. const shape = si; // Put in bin
  3542. // check if overlap with other bins
  3543. const x = bi.position.x;
  3544. const y = bi.position.y;
  3545. const z = bi.position.z;
  3546. const r = shape.radius;
  3547. addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi);
  3548. break;
  3549. }
  3550. case PLANE:
  3551. {
  3552. const shape = si;
  3553. if (shape.worldNormalNeedsUpdate) {
  3554. shape.computeWorldNormal(bi.quaternion);
  3555. }
  3556. const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin
  3557. //Incremented as we iterate through the bins
  3558. const xreset = xmin + binsizeX * 0.5 - bi.position.x;
  3559. const yreset = ymin + binsizeY * 0.5 - bi.position.y;
  3560. const zreset = zmin + binsizeZ * 0.5 - bi.position.z;
  3561. const d = GridBroadphase_collisionPairs_d;
  3562. d.set(xreset, yreset, zreset);
  3563. for (let xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  3564. for (let yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  3565. for (let zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  3566. if (d.dot(planeNormal) < binRadius) {
  3567. const idx = xoff + yoff + zoff;
  3568. bins[idx][binLengths[idx]++] = bi;
  3569. }
  3570. }
  3571. }
  3572. }
  3573. break;
  3574. }
  3575. default:
  3576. {
  3577. if (bi.aabbNeedsUpdate) {
  3578. bi.updateAABB();
  3579. }
  3580. addBoxToBins(bi.aabb.lowerBound.x, bi.aabb.lowerBound.y, bi.aabb.lowerBound.z, bi.aabb.upperBound.x, bi.aabb.upperBound.y, bi.aabb.upperBound.z, bi);
  3581. break;
  3582. }
  3583. }
  3584. } // Check each bin
  3585. for (let i = 0; i !== Nbins; i++) {
  3586. const binLength = binLengths[i]; //Skip bins with no potential collisions
  3587. if (binLength > 1) {
  3588. const bin = bins[i]; // Do N^2 broadphase inside
  3589. for (let xi = 0; xi !== binLength; xi++) {
  3590. const bi = bin[xi];
  3591. for (let yi = 0; yi !== xi; yi++) {
  3592. const bj = bin[yi];
  3593. if (this.needBroadphaseCollision(bi, bj)) {
  3594. this.intersectionTest(bi, bj, pairs1, pairs2);
  3595. }
  3596. }
  3597. }
  3598. }
  3599. } // for (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  3600. // console.log("layer "+zi);
  3601. // for (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  3602. // const row = '';
  3603. // for (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  3604. // const idx = xoff + yoff + zoff;
  3605. // row += ' ' + binLengths[idx];
  3606. // }
  3607. // console.log(row);
  3608. // }
  3609. // }
  3610. this.makePairsUnique(pairs1, pairs2);
  3611. }
  3612. }
  3613. const GridBroadphase_collisionPairs_d = new Vec3();
  3614. new Vec3();
  3615. /**
  3616. * Naive broadphase implementation, used in lack of better ones.
  3617. *
  3618. * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_
  3619. */
  3620. class NaiveBroadphase extends Broadphase {
  3621. /**
  3622. * @todo Remove useless constructor
  3623. */
  3624. constructor() {
  3625. super();
  3626. }
  3627. /**
  3628. * Get all the collision pairs in the physics world
  3629. */
  3630. collisionPairs(world, pairs1, pairs2) {
  3631. const bodies = world.bodies;
  3632. const n = bodies.length;
  3633. let bi;
  3634. let bj; // Naive N^2 ftw!
  3635. for (let i = 0; i !== n; i++) {
  3636. for (let j = 0; j !== i; j++) {
  3637. bi = bodies[i];
  3638. bj = bodies[j];
  3639. if (!this.needBroadphaseCollision(bi, bj)) {
  3640. continue;
  3641. }
  3642. this.intersectionTest(bi, bj, pairs1, pairs2);
  3643. }
  3644. }
  3645. }
  3646. /**
  3647. * Returns all the bodies within an AABB.
  3648. * @param result An array to store resulting bodies in.
  3649. */
  3650. aabbQuery(world, aabb, result) {
  3651. if (result === void 0) {
  3652. result = [];
  3653. }
  3654. for (let i = 0; i < world.bodies.length; i++) {
  3655. const b = world.bodies[i];
  3656. if (b.aabbNeedsUpdate) {
  3657. b.updateAABB();
  3658. } // Ugly hack until Body gets aabb
  3659. if (b.aabb.overlaps(aabb)) {
  3660. result.push(b);
  3661. }
  3662. }
  3663. return result;
  3664. }
  3665. }
  3666. /**
  3667. * Storage for Ray casting data
  3668. */
  3669. class RaycastResult {
  3670. /**
  3671. * rayFromWorld
  3672. */
  3673. /**
  3674. * rayToWorld
  3675. */
  3676. /**
  3677. * hitNormalWorld
  3678. */
  3679. /**
  3680. * hitPointWorld
  3681. */
  3682. /**
  3683. * hasHit
  3684. */
  3685. /**
  3686. * shape
  3687. */
  3688. /**
  3689. * body
  3690. */
  3691. /**
  3692. * The index of the hit triangle, if the hit shape was a trimesh
  3693. */
  3694. /**
  3695. * Distance to the hit. Will be set to -1 if there was no hit
  3696. */
  3697. /**
  3698. * If the ray should stop traversing the bodies
  3699. */
  3700. constructor() {
  3701. this.rayFromWorld = new Vec3();
  3702. this.rayToWorld = new Vec3();
  3703. this.hitNormalWorld = new Vec3();
  3704. this.hitPointWorld = new Vec3();
  3705. this.hasHit = false;
  3706. this.shape = null;
  3707. this.body = null;
  3708. this.hitFaceIndex = -1;
  3709. this.distance = -1;
  3710. this.shouldStop = false;
  3711. }
  3712. /**
  3713. * Reset all result data.
  3714. */
  3715. reset() {
  3716. this.rayFromWorld.setZero();
  3717. this.rayToWorld.setZero();
  3718. this.hitNormalWorld.setZero();
  3719. this.hitPointWorld.setZero();
  3720. this.hasHit = false;
  3721. this.shape = null;
  3722. this.body = null;
  3723. this.hitFaceIndex = -1;
  3724. this.distance = -1;
  3725. this.shouldStop = false;
  3726. }
  3727. /**
  3728. * abort
  3729. */
  3730. abort() {
  3731. this.shouldStop = true;
  3732. }
  3733. /**
  3734. * Set result data.
  3735. */
  3736. set(rayFromWorld, rayToWorld, hitNormalWorld, hitPointWorld, shape, body, distance) {
  3737. this.rayFromWorld.copy(rayFromWorld);
  3738. this.rayToWorld.copy(rayToWorld);
  3739. this.hitNormalWorld.copy(hitNormalWorld);
  3740. this.hitPointWorld.copy(hitPointWorld);
  3741. this.shape = shape;
  3742. this.body = body;
  3743. this.distance = distance;
  3744. }
  3745. }
  3746. let _Shape$types$SPHERE, _Shape$types$PLANE, _Shape$types$BOX, _Shape$types$CYLINDER, _Shape$types$CONVEXPO, _Shape$types$HEIGHTFI, _Shape$types$TRIMESH;
  3747. /**
  3748. * RAY_MODES
  3749. */
  3750. const RAY_MODES = {
  3751. /** CLOSEST */
  3752. CLOSEST: 1,
  3753. /** ANY */
  3754. ANY: 2,
  3755. /** ALL */
  3756. ALL: 4
  3757. };
  3758. /**
  3759. * RayMode
  3760. */
  3761. _Shape$types$SPHERE = Shape.types.SPHERE;
  3762. _Shape$types$PLANE = Shape.types.PLANE;
  3763. _Shape$types$BOX = Shape.types.BOX;
  3764. _Shape$types$CYLINDER = Shape.types.CYLINDER;
  3765. _Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON;
  3766. _Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD;
  3767. _Shape$types$TRIMESH = Shape.types.TRIMESH;
  3768. /**
  3769. * A line in 3D space that intersects bodies and return points.
  3770. */
  3771. class Ray {
  3772. /**
  3773. * from
  3774. */
  3775. /**
  3776. * to
  3777. */
  3778. /**
  3779. * direction
  3780. */
  3781. /**
  3782. * The precision of the ray. Used when checking parallelity etc.
  3783. * @default 0.0001
  3784. */
  3785. /**
  3786. * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes.
  3787. * @default true
  3788. */
  3789. /**
  3790. * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0.
  3791. * @default false
  3792. */
  3793. /**
  3794. * collisionFilterMask
  3795. * @default -1
  3796. */
  3797. /**
  3798. * collisionFilterGroup
  3799. * @default -1
  3800. */
  3801. /**
  3802. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  3803. * @default RAY.ANY
  3804. */
  3805. /**
  3806. * Current result object.
  3807. */
  3808. /**
  3809. * Will be set to `true` during intersectWorld() if the ray hit anything.
  3810. */
  3811. /**
  3812. * User-provided result callback. Will be used if mode is Ray.ALL.
  3813. */
  3814. /**
  3815. * CLOSEST
  3816. */
  3817. /**
  3818. * ANY
  3819. */
  3820. /**
  3821. * ALL
  3822. */
  3823. get [_Shape$types$SPHERE]() {
  3824. return this._intersectSphere;
  3825. }
  3826. get [_Shape$types$PLANE]() {
  3827. return this._intersectPlane;
  3828. }
  3829. get [_Shape$types$BOX]() {
  3830. return this._intersectBox;
  3831. }
  3832. get [_Shape$types$CYLINDER]() {
  3833. return this._intersectConvex;
  3834. }
  3835. get [_Shape$types$CONVEXPO]() {
  3836. return this._intersectConvex;
  3837. }
  3838. get [_Shape$types$HEIGHTFI]() {
  3839. return this._intersectHeightfield;
  3840. }
  3841. get [_Shape$types$TRIMESH]() {
  3842. return this._intersectTrimesh;
  3843. }
  3844. constructor(from, to) {
  3845. if (from === void 0) {
  3846. from = new Vec3();
  3847. }
  3848. if (to === void 0) {
  3849. to = new Vec3();
  3850. }
  3851. this.from = from.clone();
  3852. this.to = to.clone();
  3853. this.direction = new Vec3();
  3854. this.precision = 0.0001;
  3855. this.checkCollisionResponse = true;
  3856. this.skipBackfaces = false;
  3857. this.collisionFilterMask = -1;
  3858. this.collisionFilterGroup = -1;
  3859. this.mode = Ray.ANY;
  3860. this.result = new RaycastResult();
  3861. this.hasHit = false;
  3862. this.callback = result => {};
  3863. }
  3864. /**
  3865. * Do itersection against all bodies in the given World.
  3866. * @return True if the ray hit anything, otherwise false.
  3867. */
  3868. intersectWorld(world, options) {
  3869. this.mode = options.mode || Ray.ANY;
  3870. this.result = options.result || new RaycastResult();
  3871. this.skipBackfaces = !!options.skipBackfaces;
  3872. this.collisionFilterMask = typeof options.collisionFilterMask !== 'undefined' ? options.collisionFilterMask : -1;
  3873. this.collisionFilterGroup = typeof options.collisionFilterGroup !== 'undefined' ? options.collisionFilterGroup : -1;
  3874. this.checkCollisionResponse = typeof options.checkCollisionResponse !== 'undefined' ? options.checkCollisionResponse : true;
  3875. if (options.from) {
  3876. this.from.copy(options.from);
  3877. }
  3878. if (options.to) {
  3879. this.to.copy(options.to);
  3880. }
  3881. this.callback = options.callback || (() => {});
  3882. this.hasHit = false;
  3883. this.result.reset();
  3884. this.updateDirection();
  3885. this.getAABB(tmpAABB$1);
  3886. tmpArray.length = 0;
  3887. world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray);
  3888. this.intersectBodies(tmpArray);
  3889. return this.hasHit;
  3890. }
  3891. /**
  3892. * Shoot a ray at a body, get back information about the hit.
  3893. * @deprecated @param result set the result property of the Ray instead.
  3894. */
  3895. intersectBody(body, result) {
  3896. if (result) {
  3897. this.result = result;
  3898. this.updateDirection();
  3899. }
  3900. const checkCollisionResponse = this.checkCollisionResponse;
  3901. if (checkCollisionResponse && !body.collisionResponse) {
  3902. return;
  3903. }
  3904. if ((this.collisionFilterGroup & body.collisionFilterMask) === 0 || (body.collisionFilterGroup & this.collisionFilterMask) === 0) {
  3905. return;
  3906. }
  3907. const xi = intersectBody_xi;
  3908. const qi = intersectBody_qi;
  3909. for (let i = 0, N = body.shapes.length; i < N; i++) {
  3910. const shape = body.shapes[i];
  3911. if (checkCollisionResponse && !shape.collisionResponse) {
  3912. continue; // Skip
  3913. }
  3914. body.quaternion.mult(body.shapeOrientations[i], qi);
  3915. body.quaternion.vmult(body.shapeOffsets[i], xi);
  3916. xi.vadd(body.position, xi);
  3917. this.intersectShape(shape, qi, xi, body);
  3918. if (this.result.shouldStop) {
  3919. break;
  3920. }
  3921. }
  3922. }
  3923. /**
  3924. * Shoot a ray at an array bodies, get back information about the hit.
  3925. * @param bodies An array of Body objects.
  3926. * @deprecated @param result set the result property of the Ray instead.
  3927. *
  3928. */
  3929. intersectBodies(bodies, result) {
  3930. if (result) {
  3931. this.result = result;
  3932. this.updateDirection();
  3933. }
  3934. for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) {
  3935. this.intersectBody(bodies[i]);
  3936. }
  3937. }
  3938. /**
  3939. * Updates the direction vector.
  3940. */
  3941. updateDirection() {
  3942. this.to.vsub(this.from, this.direction);
  3943. this.direction.normalize();
  3944. }
  3945. intersectShape(shape, quat, position, body) {
  3946. const from = this.from; // Checking boundingSphere
  3947. const distance = distanceFromIntersection(from, this.direction, position);
  3948. if (distance > shape.boundingSphereRadius) {
  3949. return;
  3950. }
  3951. const intersectMethod = this[shape.type];
  3952. if (intersectMethod) {
  3953. intersectMethod.call(this, shape, quat, position, body, shape);
  3954. }
  3955. }
  3956. _intersectBox(box, quat, position, body, reportedShape) {
  3957. return this._intersectConvex(box.convexPolyhedronRepresentation, quat, position, body, reportedShape);
  3958. }
  3959. _intersectPlane(shape, quat, position, body, reportedShape) {
  3960. const from = this.from;
  3961. const to = this.to;
  3962. const direction = this.direction; // Get plane normal
  3963. const worldNormal = new Vec3(0, 0, 1);
  3964. quat.vmult(worldNormal, worldNormal);
  3965. const len = new Vec3();
  3966. from.vsub(position, len);
  3967. const planeToFrom = len.dot(worldNormal);
  3968. to.vsub(position, len);
  3969. const planeToTo = len.dot(worldNormal);
  3970. if (planeToFrom * planeToTo > 0) {
  3971. // "from" and "to" are on the same side of the plane... bail out
  3972. return;
  3973. }
  3974. if (from.distanceTo(to) < planeToFrom) {
  3975. return;
  3976. }
  3977. const n_dot_dir = worldNormal.dot(direction);
  3978. if (Math.abs(n_dot_dir) < this.precision) {
  3979. // No intersection
  3980. return;
  3981. }
  3982. const planePointToFrom = new Vec3();
  3983. const dir_scaled_with_t = new Vec3();
  3984. const hitPointWorld = new Vec3();
  3985. from.vsub(position, planePointToFrom);
  3986. const t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  3987. direction.scale(t, dir_scaled_with_t);
  3988. from.vadd(dir_scaled_with_t, hitPointWorld);
  3989. this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);
  3990. }
  3991. /**
  3992. * Get the world AABB of the ray.
  3993. */
  3994. getAABB(aabb) {
  3995. const {
  3996. lowerBound,
  3997. upperBound
  3998. } = aabb;
  3999. const to = this.to;
  4000. const from = this.from;
  4001. lowerBound.x = Math.min(to.x, from.x);
  4002. lowerBound.y = Math.min(to.y, from.y);
  4003. lowerBound.z = Math.min(to.z, from.z);
  4004. upperBound.x = Math.max(to.x, from.x);
  4005. upperBound.y = Math.max(to.y, from.y);
  4006. upperBound.z = Math.max(to.z, from.z);
  4007. }
  4008. _intersectHeightfield(shape, quat, position, body, reportedShape) {
  4009. shape.data;
  4010. shape.elementSize; // Convert the ray to local heightfield coordinates
  4011. const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);
  4012. localRay.from.copy(this.from);
  4013. localRay.to.copy(this.to);
  4014. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  4015. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  4016. localRay.updateDirection(); // Get the index of the data points to test against
  4017. const index = intersectHeightfield_index;
  4018. let iMinX;
  4019. let iMinY;
  4020. let iMaxX;
  4021. let iMaxY; // Set to max
  4022. iMinX = iMinY = 0;
  4023. iMaxX = iMaxY = shape.data.length - 1;
  4024. const aabb = new AABB();
  4025. localRay.getAABB(aabb);
  4026. shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);
  4027. iMinX = Math.max(iMinX, index[0]);
  4028. iMinY = Math.max(iMinY, index[1]);
  4029. shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);
  4030. iMaxX = Math.min(iMaxX, index[0] + 1);
  4031. iMaxY = Math.min(iMaxY, index[1] + 1);
  4032. for (let i = iMinX; i < iMaxX; i++) {
  4033. for (let j = iMinY; j < iMaxY; j++) {
  4034. if (this.result.shouldStop) {
  4035. return;
  4036. }
  4037. shape.getAabbAtIndex(i, j, aabb);
  4038. if (!aabb.overlapsRay(localRay)) {
  4039. continue;
  4040. } // Lower triangle
  4041. shape.getConvexTrianglePillar(i, j, false);
  4042. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  4043. this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
  4044. if (this.result.shouldStop) {
  4045. return;
  4046. } // Upper triangle
  4047. shape.getConvexTrianglePillar(i, j, true);
  4048. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  4049. this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
  4050. }
  4051. }
  4052. }
  4053. _intersectSphere(sphere, quat, position, body, reportedShape) {
  4054. const from = this.from;
  4055. const to = this.to;
  4056. const r = sphere.radius;
  4057. const a = (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2;
  4058. const b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));
  4059. const c = (from.x - position.x) ** 2 + (from.y - position.y) ** 2 + (from.z - position.z) ** 2 - r ** 2;
  4060. const delta = b ** 2 - 4 * a * c;
  4061. const intersectionPoint = Ray_intersectSphere_intersectionPoint;
  4062. const normal = Ray_intersectSphere_normal;
  4063. if (delta < 0) {
  4064. // No intersection
  4065. return;
  4066. } else if (delta === 0) {
  4067. // single intersection point
  4068. from.lerp(to, delta, intersectionPoint);
  4069. intersectionPoint.vsub(position, normal);
  4070. normal.normalize();
  4071. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4072. } else {
  4073. const d1 = (-b - Math.sqrt(delta)) / (2 * a);
  4074. const d2 = (-b + Math.sqrt(delta)) / (2 * a);
  4075. if (d1 >= 0 && d1 <= 1) {
  4076. from.lerp(to, d1, intersectionPoint);
  4077. intersectionPoint.vsub(position, normal);
  4078. normal.normalize();
  4079. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4080. }
  4081. if (this.result.shouldStop) {
  4082. return;
  4083. }
  4084. if (d2 >= 0 && d2 <= 1) {
  4085. from.lerp(to, d2, intersectionPoint);
  4086. intersectionPoint.vsub(position, normal);
  4087. normal.normalize();
  4088. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4089. }
  4090. }
  4091. }
  4092. _intersectConvex(shape, quat, position, body, reportedShape, options) {
  4093. intersectConvex_minDistNormal;
  4094. const normal = intersectConvex_normal;
  4095. const vector = intersectConvex_vector;
  4096. intersectConvex_minDistIntersect;
  4097. const faceList = options && options.faceList || null; // Checking faces
  4098. const faces = shape.faces;
  4099. const vertices = shape.vertices;
  4100. const normals = shape.faceNormals;
  4101. const direction = this.direction;
  4102. const from = this.from;
  4103. const to = this.to;
  4104. const fromToDistance = from.distanceTo(to);
  4105. const Nfaces = faceList ? faceList.length : faces.length;
  4106. const result = this.result;
  4107. for (let j = 0; !result.shouldStop && j < Nfaces; j++) {
  4108. const fi = faceList ? faceList[j] : j;
  4109. const face = faces[fi];
  4110. const faceNormal = normals[fi];
  4111. const q = quat;
  4112. const x = position; // determine if ray intersects the plane of the face
  4113. // note: this works regardless of the direction of the face normal
  4114. // Get plane point in world coordinates...
  4115. vector.copy(vertices[face[0]]);
  4116. q.vmult(vector, vector);
  4117. vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later.
  4118. vector.vsub(from, vector); // Get plane normal
  4119. q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting
  4120. const dot = direction.dot(normal); // Bail out if ray and plane are parallel
  4121. if (Math.abs(dot) < this.precision) {
  4122. continue;
  4123. } // calc distance to plane
  4124. const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray
  4125. if (scalar < 0) {
  4126. continue;
  4127. } // if (dot < 0) {
  4128. // Intersection point is from + direction * scalar
  4129. direction.scale(scalar, intersectPoint);
  4130. intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with.
  4131. a.copy(vertices[face[0]]);
  4132. q.vmult(a, a);
  4133. x.vadd(a, a);
  4134. for (let i = 1; !result.shouldStop && i < face.length - 1; i++) {
  4135. // Transform 3 vertices to world coords
  4136. b.copy(vertices[face[i]]);
  4137. c.copy(vertices[face[i + 1]]);
  4138. q.vmult(b, b);
  4139. q.vmult(c, c);
  4140. x.vadd(b, b);
  4141. x.vadd(c, c);
  4142. const distance = intersectPoint.distanceTo(from);
  4143. if (!(Ray.pointInTriangle(intersectPoint, a, b, c) || Ray.pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance) {
  4144. continue;
  4145. }
  4146. this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);
  4147. } // }
  4148. }
  4149. }
  4150. /**
  4151. * @todo Optimize by transforming the world to local space first.
  4152. * @todo Use Octree lookup
  4153. */
  4154. _intersectTrimesh(mesh, quat, position, body, reportedShape, options) {
  4155. const normal = intersectTrimesh_normal;
  4156. const triangles = intersectTrimesh_triangles;
  4157. const treeTransform = intersectTrimesh_treeTransform;
  4158. const vector = intersectConvex_vector;
  4159. const localDirection = intersectTrimesh_localDirection;
  4160. const localFrom = intersectTrimesh_localFrom;
  4161. const localTo = intersectTrimesh_localTo;
  4162. const worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  4163. const worldNormal = intersectTrimesh_worldNormal; // Checking faces
  4164. const indices = mesh.indices;
  4165. mesh.vertices; // const normals = mesh.faceNormals
  4166. const from = this.from;
  4167. const to = this.to;
  4168. const direction = this.direction;
  4169. treeTransform.position.copy(position);
  4170. treeTransform.quaternion.copy(quat); // Transform ray to local space!
  4171. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  4172. Transform.pointToLocalFrame(position, quat, from, localFrom);
  4173. Transform.pointToLocalFrame(position, quat, to, localTo);
  4174. localTo.x *= mesh.scale.x;
  4175. localTo.y *= mesh.scale.y;
  4176. localTo.z *= mesh.scale.z;
  4177. localFrom.x *= mesh.scale.x;
  4178. localFrom.y *= mesh.scale.y;
  4179. localFrom.z *= mesh.scale.z;
  4180. localTo.vsub(localFrom, localDirection);
  4181. localDirection.normalize();
  4182. const fromToDistanceSquared = localFrom.distanceSquared(localTo);
  4183. mesh.tree.rayQuery(this, treeTransform, triangles);
  4184. for (let i = 0, N = triangles.length; !this.result.shouldStop && i !== N; i++) {
  4185. const trianglesIndex = triangles[i];
  4186. mesh.getNormal(trianglesIndex, normal); // determine if ray intersects the plane of the face
  4187. // note: this works regardless of the direction of the face normal
  4188. // Get plane point in world coordinates...
  4189. mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later.
  4190. a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting
  4191. const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel
  4192. // if (Math.abs( dot ) < this.precision){
  4193. // continue;
  4194. // }
  4195. // calc distance to plane
  4196. const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray
  4197. if (scalar < 0) {
  4198. continue;
  4199. } // Intersection point is from + direction * scalar
  4200. localDirection.scale(scalar, intersectPoint);
  4201. intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices
  4202. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  4203. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  4204. const squaredDistance = intersectPoint.distanceSquared(localFrom);
  4205. if (!(Ray.pointInTriangle(intersectPoint, b, a, c) || Ray.pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared) {
  4206. continue;
  4207. } // transform intersectpoint and normal to world
  4208. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  4209. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  4210. this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);
  4211. }
  4212. triangles.length = 0;
  4213. }
  4214. /**
  4215. * @return True if the intersections should continue
  4216. */
  4217. reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) {
  4218. const from = this.from;
  4219. const to = this.to;
  4220. const distance = from.distanceTo(hitPointWorld);
  4221. const result = this.result; // Skip back faces?
  4222. if (this.skipBackfaces && normal.dot(this.direction) > 0) {
  4223. return;
  4224. }
  4225. result.hitFaceIndex = typeof hitFaceIndex !== 'undefined' ? hitFaceIndex : -1;
  4226. switch (this.mode) {
  4227. case Ray.ALL:
  4228. this.hasHit = true;
  4229. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4230. result.hasHit = true;
  4231. this.callback(result);
  4232. break;
  4233. case Ray.CLOSEST:
  4234. // Store if closer than current closest
  4235. if (distance < result.distance || !result.hasHit) {
  4236. this.hasHit = true;
  4237. result.hasHit = true;
  4238. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4239. }
  4240. break;
  4241. case Ray.ANY:
  4242. // Report and stop.
  4243. this.hasHit = true;
  4244. result.hasHit = true;
  4245. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4246. result.shouldStop = true;
  4247. break;
  4248. }
  4249. }
  4250. /**
  4251. * As per "Barycentric Technique" as named
  4252. * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division
  4253. */
  4254. static pointInTriangle(p, a, b, c) {
  4255. c.vsub(a, v0);
  4256. b.vsub(a, v1);
  4257. p.vsub(a, v2);
  4258. const dot00 = v0.dot(v0);
  4259. const dot01 = v0.dot(v1);
  4260. const dot02 = v0.dot(v2);
  4261. const dot11 = v1.dot(v1);
  4262. const dot12 = v1.dot(v2);
  4263. let u;
  4264. let v;
  4265. return (u = dot11 * dot02 - dot01 * dot12) >= 0 && (v = dot00 * dot12 - dot01 * dot02) >= 0 && u + v < dot00 * dot11 - dot01 * dot01;
  4266. }
  4267. }
  4268. Ray.CLOSEST = RAY_MODES.CLOSEST;
  4269. Ray.ANY = RAY_MODES.ANY;
  4270. Ray.ALL = RAY_MODES.ALL;
  4271. const tmpAABB$1 = new AABB();
  4272. const tmpArray = [];
  4273. const v1 = new Vec3();
  4274. const v2 = new Vec3();
  4275. const intersectBody_xi = new Vec3();
  4276. const intersectBody_qi = new Quaternion();
  4277. const intersectPoint = new Vec3();
  4278. const a = new Vec3();
  4279. const b = new Vec3();
  4280. const c = new Vec3();
  4281. new Vec3();
  4282. new RaycastResult();
  4283. const intersectConvexOptions = {
  4284. faceList: [0]
  4285. };
  4286. const worldPillarOffset = new Vec3();
  4287. const intersectHeightfield_localRay = new Ray();
  4288. const intersectHeightfield_index = [];
  4289. const Ray_intersectSphere_intersectionPoint = new Vec3();
  4290. const Ray_intersectSphere_normal = new Vec3();
  4291. const intersectConvex_normal = new Vec3();
  4292. const intersectConvex_minDistNormal = new Vec3();
  4293. const intersectConvex_minDistIntersect = new Vec3();
  4294. const intersectConvex_vector = new Vec3();
  4295. const intersectTrimesh_normal = new Vec3();
  4296. const intersectTrimesh_localDirection = new Vec3();
  4297. const intersectTrimesh_localFrom = new Vec3();
  4298. const intersectTrimesh_localTo = new Vec3();
  4299. const intersectTrimesh_worldNormal = new Vec3();
  4300. const intersectTrimesh_worldIntersectPoint = new Vec3();
  4301. new AABB();
  4302. const intersectTrimesh_triangles = [];
  4303. const intersectTrimesh_treeTransform = new Transform();
  4304. const v0 = new Vec3();
  4305. const intersect = new Vec3();
  4306. function distanceFromIntersection(from, direction, position) {
  4307. // v0 is vector from from to position
  4308. position.vsub(from, v0);
  4309. const dot = v0.dot(direction); // intersect = direction*dot + from
  4310. direction.scale(dot, intersect);
  4311. intersect.vadd(from, intersect);
  4312. const distance = position.distanceTo(intersect);
  4313. return distance;
  4314. }
  4315. /**
  4316. * Sweep and prune broadphase along one axis.
  4317. */
  4318. class SAPBroadphase extends Broadphase {
  4319. /**
  4320. * List of bodies currently in the broadphase.
  4321. */
  4322. /**
  4323. * The world to search in.
  4324. */
  4325. /**
  4326. * Axis to sort the bodies along.
  4327. * Set to 0 for x axis, and 1 for y axis.
  4328. * For best performance, pick the axis where bodies are most distributed.
  4329. */
  4330. /**
  4331. * Check if the bounds of two bodies overlap, along the given SAP axis.
  4332. */
  4333. static checkBounds(bi, bj, axisIndex) {
  4334. let biPos;
  4335. let bjPos;
  4336. if (axisIndex === 0) {
  4337. biPos = bi.position.x;
  4338. bjPos = bj.position.x;
  4339. } else if (axisIndex === 1) {
  4340. biPos = bi.position.y;
  4341. bjPos = bj.position.y;
  4342. } else if (axisIndex === 2) {
  4343. biPos = bi.position.z;
  4344. bjPos = bj.position.z;
  4345. }
  4346. const ri = bi.boundingRadius,
  4347. rj = bj.boundingRadius,
  4348. boundA2 = biPos + ri,
  4349. boundB1 = bjPos - rj;
  4350. return boundB1 < boundA2;
  4351. } // Note: these are identical, save for x/y/z lowerbound
  4352. /**
  4353. * insertionSortX
  4354. */
  4355. static insertionSortX(a) {
  4356. for (let i = 1, l = a.length; i < l; i++) {
  4357. const v = a[i];
  4358. let j;
  4359. for (j = i - 1; j >= 0; j--) {
  4360. if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) {
  4361. break;
  4362. }
  4363. a[j + 1] = a[j];
  4364. }
  4365. a[j + 1] = v;
  4366. }
  4367. return a;
  4368. }
  4369. /**
  4370. * insertionSortY
  4371. */
  4372. static insertionSortY(a) {
  4373. for (let i = 1, l = a.length; i < l; i++) {
  4374. const v = a[i];
  4375. let j;
  4376. for (j = i - 1; j >= 0; j--) {
  4377. if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) {
  4378. break;
  4379. }
  4380. a[j + 1] = a[j];
  4381. }
  4382. a[j + 1] = v;
  4383. }
  4384. return a;
  4385. }
  4386. /**
  4387. * insertionSortZ
  4388. */
  4389. static insertionSortZ(a) {
  4390. for (let i = 1, l = a.length; i < l; i++) {
  4391. const v = a[i];
  4392. let j;
  4393. for (j = i - 1; j >= 0; j--) {
  4394. if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) {
  4395. break;
  4396. }
  4397. a[j + 1] = a[j];
  4398. }
  4399. a[j + 1] = v;
  4400. }
  4401. return a;
  4402. }
  4403. constructor(world) {
  4404. super();
  4405. this.axisList = [];
  4406. this.world = null;
  4407. this.axisIndex = 0;
  4408. const axisList = this.axisList;
  4409. this._addBodyHandler = event => {
  4410. axisList.push(event.body);
  4411. };
  4412. this._removeBodyHandler = event => {
  4413. const idx = axisList.indexOf(event.body);
  4414. if (idx !== -1) {
  4415. axisList.splice(idx, 1);
  4416. }
  4417. };
  4418. if (world) {
  4419. this.setWorld(world);
  4420. }
  4421. }
  4422. /**
  4423. * Change the world
  4424. */
  4425. setWorld(world) {
  4426. // Clear the old axis array
  4427. this.axisList.length = 0; // Add all bodies from the new world
  4428. for (let i = 0; i < world.bodies.length; i++) {
  4429. this.axisList.push(world.bodies[i]);
  4430. } // Remove old handlers, if any
  4431. world.removeEventListener('addBody', this._addBodyHandler);
  4432. world.removeEventListener('removeBody', this._removeBodyHandler); // Add handlers to update the list of bodies.
  4433. world.addEventListener('addBody', this._addBodyHandler);
  4434. world.addEventListener('removeBody', this._removeBodyHandler);
  4435. this.world = world;
  4436. this.dirty = true;
  4437. }
  4438. /**
  4439. * Collect all collision pairs
  4440. */
  4441. collisionPairs(world, p1, p2) {
  4442. const bodies = this.axisList;
  4443. const N = bodies.length;
  4444. const axisIndex = this.axisIndex;
  4445. let i;
  4446. let j;
  4447. if (this.dirty) {
  4448. this.sortList();
  4449. this.dirty = false;
  4450. } // Look through the list
  4451. for (i = 0; i !== N; i++) {
  4452. const bi = bodies[i];
  4453. for (j = i + 1; j < N; j++) {
  4454. const bj = bodies[j];
  4455. if (!this.needBroadphaseCollision(bi, bj)) {
  4456. continue;
  4457. }
  4458. if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) {
  4459. break;
  4460. }
  4461. this.intersectionTest(bi, bj, p1, p2);
  4462. }
  4463. }
  4464. }
  4465. sortList() {
  4466. const axisList = this.axisList;
  4467. const axisIndex = this.axisIndex;
  4468. const N = axisList.length; // Update AABBs
  4469. for (let i = 0; i !== N; i++) {
  4470. const bi = axisList[i];
  4471. if (bi.aabbNeedsUpdate) {
  4472. bi.updateAABB();
  4473. }
  4474. } // Sort the list
  4475. if (axisIndex === 0) {
  4476. SAPBroadphase.insertionSortX(axisList);
  4477. } else if (axisIndex === 1) {
  4478. SAPBroadphase.insertionSortY(axisList);
  4479. } else if (axisIndex === 2) {
  4480. SAPBroadphase.insertionSortZ(axisList);
  4481. }
  4482. }
  4483. /**
  4484. * Computes the variance of the body positions and estimates the best axis to use.
  4485. * Will automatically set property `axisIndex`.
  4486. */
  4487. autoDetectAxis() {
  4488. let sumX = 0;
  4489. let sumX2 = 0;
  4490. let sumY = 0;
  4491. let sumY2 = 0;
  4492. let sumZ = 0;
  4493. let sumZ2 = 0;
  4494. const bodies = this.axisList;
  4495. const N = bodies.length;
  4496. const invN = 1 / N;
  4497. for (let i = 0; i !== N; i++) {
  4498. const b = bodies[i];
  4499. const centerX = b.position.x;
  4500. sumX += centerX;
  4501. sumX2 += centerX * centerX;
  4502. const centerY = b.position.y;
  4503. sumY += centerY;
  4504. sumY2 += centerY * centerY;
  4505. const centerZ = b.position.z;
  4506. sumZ += centerZ;
  4507. sumZ2 += centerZ * centerZ;
  4508. }
  4509. const varianceX = sumX2 - sumX * sumX * invN;
  4510. const varianceY = sumY2 - sumY * sumY * invN;
  4511. const varianceZ = sumZ2 - sumZ * sumZ * invN;
  4512. if (varianceX > varianceY) {
  4513. if (varianceX > varianceZ) {
  4514. this.axisIndex = 0;
  4515. } else {
  4516. this.axisIndex = 2;
  4517. }
  4518. } else if (varianceY > varianceZ) {
  4519. this.axisIndex = 1;
  4520. } else {
  4521. this.axisIndex = 2;
  4522. }
  4523. }
  4524. /**
  4525. * Returns all the bodies within an AABB.
  4526. * @param result An array to store resulting bodies in.
  4527. */
  4528. aabbQuery(world, aabb, result) {
  4529. if (result === void 0) {
  4530. result = [];
  4531. }
  4532. if (this.dirty) {
  4533. this.sortList();
  4534. this.dirty = false;
  4535. }
  4536. const axisIndex = this.axisIndex;
  4537. let axis = 'x';
  4538. if (axisIndex === 1) {
  4539. axis = 'y';
  4540. }
  4541. if (axisIndex === 2) {
  4542. axis = 'z';
  4543. }
  4544. const axisList = this.axisList;
  4545. aabb.lowerBound[axis];
  4546. aabb.upperBound[axis];
  4547. for (let i = 0; i < axisList.length; i++) {
  4548. const b = axisList[i];
  4549. if (b.aabbNeedsUpdate) {
  4550. b.updateAABB();
  4551. }
  4552. if (b.aabb.overlaps(aabb)) {
  4553. result.push(b);
  4554. }
  4555. }
  4556. return result;
  4557. }
  4558. }
  4559. class Utils {
  4560. /**
  4561. * Extend an options object with default values.
  4562. * @param options The options object. May be falsy: in this case, a new object is created and returned.
  4563. * @param defaults An object containing default values.
  4564. * @return The modified options object.
  4565. */
  4566. static defaults(options, defaults) {
  4567. if (options === void 0) {
  4568. options = {};
  4569. }
  4570. for (let key in defaults) {
  4571. if (!(key in options)) {
  4572. options[key] = defaults[key];
  4573. }
  4574. }
  4575. return options;
  4576. }
  4577. }
  4578. /**
  4579. * Constraint base class
  4580. */
  4581. class Constraint {
  4582. /**
  4583. * Equations to be solved in this constraint.
  4584. */
  4585. /**
  4586. * Body A.
  4587. */
  4588. /**
  4589. * Body B.
  4590. */
  4591. /**
  4592. * Set to false if you don't want the bodies to collide when they are connected.
  4593. */
  4594. constructor(bodyA, bodyB, options) {
  4595. if (options === void 0) {
  4596. options = {};
  4597. }
  4598. options = Utils.defaults(options, {
  4599. collideConnected: true,
  4600. wakeUpBodies: true
  4601. });
  4602. this.equations = [];
  4603. this.bodyA = bodyA;
  4604. this.bodyB = bodyB;
  4605. this.id = Constraint.idCounter++;
  4606. this.collideConnected = options.collideConnected;
  4607. if (options.wakeUpBodies) {
  4608. if (bodyA) {
  4609. bodyA.wakeUp();
  4610. }
  4611. if (bodyB) {
  4612. bodyB.wakeUp();
  4613. }
  4614. }
  4615. }
  4616. /**
  4617. * Update all the equations with data.
  4618. */
  4619. update() {
  4620. throw new Error('method update() not implmemented in this Constraint subclass!');
  4621. }
  4622. /**
  4623. * Enables all equations in the constraint.
  4624. */
  4625. enable() {
  4626. const eqs = this.equations;
  4627. for (let i = 0; i < eqs.length; i++) {
  4628. eqs[i].enabled = true;
  4629. }
  4630. }
  4631. /**
  4632. * Disables all equations in the constraint.
  4633. */
  4634. disable() {
  4635. const eqs = this.equations;
  4636. for (let i = 0; i < eqs.length; i++) {
  4637. eqs[i].enabled = false;
  4638. }
  4639. }
  4640. }
  4641. Constraint.idCounter = 0;
  4642. /**
  4643. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  4644. */
  4645. class JacobianElement {
  4646. /**
  4647. * spatial
  4648. */
  4649. /**
  4650. * rotational
  4651. */
  4652. constructor() {
  4653. this.spatial = new Vec3();
  4654. this.rotational = new Vec3();
  4655. }
  4656. /**
  4657. * Multiply with other JacobianElement
  4658. */
  4659. multiplyElement(element) {
  4660. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  4661. }
  4662. /**
  4663. * Multiply with two vectors
  4664. */
  4665. multiplyVectors(spatial, rotational) {
  4666. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  4667. }
  4668. }
  4669. /**
  4670. * Equation base class.
  4671. *
  4672. * `a`, `b` and `eps` are {@link https://www8.cs.umu.se/kurser/5DV058/VT15/lectures/SPOOKlabnotes.pdf SPOOK} parameters that default to `0.0`. See {@link https://github.com/schteppe/cannon.js/issues/238#issuecomment-147172327 this exchange} for more details on Cannon's physics implementation.
  4673. */
  4674. class Equation {
  4675. /**
  4676. * Minimum (read: negative max) force to be applied by the constraint.
  4677. */
  4678. /**
  4679. * Maximum (read: positive max) force to be applied by the constraint.
  4680. */
  4681. /**
  4682. * SPOOK parameter
  4683. */
  4684. /**
  4685. * SPOOK parameter
  4686. */
  4687. /**
  4688. * SPOOK parameter
  4689. */
  4690. /**
  4691. * A number, proportional to the force added to the bodies.
  4692. */
  4693. constructor(bi, bj, minForce, maxForce) {
  4694. if (minForce === void 0) {
  4695. minForce = -1e6;
  4696. }
  4697. if (maxForce === void 0) {
  4698. maxForce = 1e6;
  4699. }
  4700. this.id = Equation.idCounter++;
  4701. this.minForce = minForce;
  4702. this.maxForce = maxForce;
  4703. this.bi = bi;
  4704. this.bj = bj;
  4705. this.a = 0.0; // SPOOK parameter
  4706. this.b = 0.0; // SPOOK parameter
  4707. this.eps = 0.0; // SPOOK parameter
  4708. this.jacobianElementA = new JacobianElement();
  4709. this.jacobianElementB = new JacobianElement();
  4710. this.enabled = true;
  4711. this.multiplier = 0;
  4712. this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params
  4713. }
  4714. /**
  4715. * Recalculates a, b, and eps.
  4716. *
  4717. * The Equation constructor sets typical SPOOK parameters as such:
  4718. * * `stiffness` = 1e7
  4719. * * `relaxation` = 4
  4720. * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._
  4721. */
  4722. setSpookParams(stiffness, relaxation, timeStep) {
  4723. const d = relaxation;
  4724. const k = stiffness;
  4725. const h = timeStep;
  4726. this.a = 4.0 / (h * (1 + 4 * d));
  4727. this.b = 4.0 * d / (1 + 4 * d);
  4728. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  4729. }
  4730. /**
  4731. * Computes the right hand side of the SPOOK equation
  4732. */
  4733. computeB(a, b, h) {
  4734. const GW = this.computeGW();
  4735. const Gq = this.computeGq();
  4736. const GiMf = this.computeGiMf();
  4737. return -Gq * a - GW * b - GiMf * h;
  4738. }
  4739. /**
  4740. * Computes G*q, where q are the generalized body coordinates
  4741. */
  4742. computeGq() {
  4743. const GA = this.jacobianElementA;
  4744. const GB = this.jacobianElementB;
  4745. const bi = this.bi;
  4746. const bj = this.bj;
  4747. const xi = bi.position;
  4748. const xj = bj.position;
  4749. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  4750. }
  4751. /**
  4752. * Computes G*W, where W are the body velocities
  4753. */
  4754. computeGW() {
  4755. const GA = this.jacobianElementA;
  4756. const GB = this.jacobianElementB;
  4757. const bi = this.bi;
  4758. const bj = this.bj;
  4759. const vi = bi.velocity;
  4760. const vj = bj.velocity;
  4761. const wi = bi.angularVelocity;
  4762. const wj = bj.angularVelocity;
  4763. return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  4764. }
  4765. /**
  4766. * Computes G*Wlambda, where W are the body velocities
  4767. */
  4768. computeGWlambda() {
  4769. const GA = this.jacobianElementA;
  4770. const GB = this.jacobianElementB;
  4771. const bi = this.bi;
  4772. const bj = this.bj;
  4773. const vi = bi.vlambda;
  4774. const vj = bj.vlambda;
  4775. const wi = bi.wlambda;
  4776. const wj = bj.wlambda;
  4777. return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  4778. }
  4779. /**
  4780. * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
  4781. */
  4782. computeGiMf() {
  4783. const GA = this.jacobianElementA;
  4784. const GB = this.jacobianElementB;
  4785. const bi = this.bi;
  4786. const bj = this.bj;
  4787. const fi = bi.force;
  4788. const ti = bi.torque;
  4789. const fj = bj.force;
  4790. const tj = bj.torque;
  4791. const invMassi = bi.invMassSolve;
  4792. const invMassj = bj.invMassSolve;
  4793. fi.scale(invMassi, iMfi);
  4794. fj.scale(invMassj, iMfj);
  4795. bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui);
  4796. bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj);
  4797. return GA.multiplyVectors(iMfi, invIi_vmult_taui) + GB.multiplyVectors(iMfj, invIj_vmult_tauj);
  4798. }
  4799. /**
  4800. * Computes G*inv(M)*G'
  4801. */
  4802. computeGiMGt() {
  4803. const GA = this.jacobianElementA;
  4804. const GB = this.jacobianElementB;
  4805. const bi = this.bi;
  4806. const bj = this.bj;
  4807. const invMassi = bi.invMassSolve;
  4808. const invMassj = bj.invMassSolve;
  4809. const invIi = bi.invInertiaWorldSolve;
  4810. const invIj = bj.invInertiaWorldSolve;
  4811. let result = invMassi + invMassj;
  4812. invIi.vmult(GA.rotational, tmp);
  4813. result += tmp.dot(GA.rotational);
  4814. invIj.vmult(GB.rotational, tmp);
  4815. result += tmp.dot(GB.rotational);
  4816. return result;
  4817. }
  4818. /**
  4819. * Add constraint velocity to the bodies.
  4820. */
  4821. addToWlambda(deltalambda) {
  4822. const GA = this.jacobianElementA;
  4823. const GB = this.jacobianElementB;
  4824. const bi = this.bi;
  4825. const bj = this.bj;
  4826. const temp = addToWlambda_temp; // Add to linear velocity
  4827. // v_lambda += inv(M) * delta_lamba * G
  4828. bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);
  4829. bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda); // Add to angular velocity
  4830. bi.invInertiaWorldSolve.vmult(GA.rotational, temp);
  4831. bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);
  4832. bj.invInertiaWorldSolve.vmult(GB.rotational, temp);
  4833. bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);
  4834. }
  4835. /**
  4836. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  4837. */
  4838. computeC() {
  4839. return this.computeGiMGt() + this.eps;
  4840. }
  4841. }
  4842. Equation.idCounter = 0;
  4843. const iMfi = new Vec3();
  4844. const iMfj = new Vec3();
  4845. const invIi_vmult_taui = new Vec3();
  4846. const invIj_vmult_tauj = new Vec3();
  4847. const tmp = new Vec3();
  4848. const addToWlambda_temp = new Vec3();
  4849. /**
  4850. * Contact/non-penetration constraint equation
  4851. */
  4852. class ContactEquation extends Equation {
  4853. /**
  4854. * "bounciness": u1 = -e*u0
  4855. */
  4856. /**
  4857. * World-oriented vector that goes from the center of bi to the contact point.
  4858. */
  4859. /**
  4860. * World-oriented vector that starts in body j position and goes to the contact point.
  4861. */
  4862. /**
  4863. * Contact normal, pointing out of body i.
  4864. */
  4865. constructor(bodyA, bodyB, maxForce) {
  4866. if (maxForce === void 0) {
  4867. maxForce = 1e6;
  4868. }
  4869. super(bodyA, bodyB, 0, maxForce);
  4870. this.restitution = 0.0;
  4871. this.ri = new Vec3();
  4872. this.rj = new Vec3();
  4873. this.ni = new Vec3();
  4874. }
  4875. computeB(h) {
  4876. const a = this.a;
  4877. const b = this.b;
  4878. const bi = this.bi;
  4879. const bj = this.bj;
  4880. const ri = this.ri;
  4881. const rj = this.rj;
  4882. const rixn = ContactEquation_computeB_temp1;
  4883. const rjxn = ContactEquation_computeB_temp2;
  4884. const vi = bi.velocity;
  4885. const wi = bi.angularVelocity;
  4886. bi.force;
  4887. bi.torque;
  4888. const vj = bj.velocity;
  4889. const wj = bj.angularVelocity;
  4890. bj.force;
  4891. bj.torque;
  4892. const penetrationVec = ContactEquation_computeB_temp3;
  4893. const GA = this.jacobianElementA;
  4894. const GB = this.jacobianElementB;
  4895. const n = this.ni; // Caluclate cross products
  4896. ri.cross(n, rixn);
  4897. rj.cross(n, rjxn); // g = xj+rj -(xi+ri)
  4898. // G = [ -ni -rixn ni rjxn ]
  4899. n.negate(GA.spatial);
  4900. rixn.negate(GA.rotational);
  4901. GB.spatial.copy(n);
  4902. GB.rotational.copy(rjxn); // Calculate the penetration vector
  4903. penetrationVec.copy(bj.position);
  4904. penetrationVec.vadd(rj, penetrationVec);
  4905. penetrationVec.vsub(bi.position, penetrationVec);
  4906. penetrationVec.vsub(ri, penetrationVec);
  4907. const g = n.dot(penetrationVec); // Compute iteration
  4908. const ePlusOne = this.restitution + 1;
  4909. const GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  4910. const GiMf = this.computeGiMf();
  4911. const B = -g * a - GW * b - h * GiMf;
  4912. return B;
  4913. }
  4914. /**
  4915. * Get the current relative velocity in the contact point.
  4916. */
  4917. getImpactVelocityAlongNormal() {
  4918. const vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  4919. const vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  4920. const xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  4921. const xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  4922. const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  4923. this.bi.position.vadd(this.ri, xi);
  4924. this.bj.position.vadd(this.rj, xj);
  4925. this.bi.getVelocityAtWorldPoint(xi, vi);
  4926. this.bj.getVelocityAtWorldPoint(xj, vj);
  4927. vi.vsub(vj, relVel);
  4928. return this.ni.dot(relVel);
  4929. }
  4930. }
  4931. const ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  4932. const ContactEquation_computeB_temp2 = new Vec3();
  4933. const ContactEquation_computeB_temp3 = new Vec3();
  4934. const ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  4935. const ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  4936. const ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  4937. const ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  4938. const ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  4939. /**
  4940. * Connects two bodies at given offset points.
  4941. * @example
  4942. * const bodyA = new Body({ mass: 1 })
  4943. * const bodyB = new Body({ mass: 1 })
  4944. * bodyA.position.set(-1, 0, 0)
  4945. * bodyB.position.set(1, 0, 0)
  4946. * bodyA.addShape(shapeA)
  4947. * bodyB.addShape(shapeB)
  4948. * world.addBody(bodyA)
  4949. * world.addBody(bodyB)
  4950. * const localPivotA = new Vec3(1, 0, 0)
  4951. * const localPivotB = new Vec3(-1, 0, 0)
  4952. * const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB)
  4953. * world.addConstraint(constraint)
  4954. */
  4955. class PointToPointConstraint extends Constraint {
  4956. /**
  4957. * Pivot, defined locally in bodyA.
  4958. */
  4959. /**
  4960. * Pivot, defined locally in bodyB.
  4961. */
  4962. /**
  4963. * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  4964. * @param bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
  4965. * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to.
  4966. * @param maxForce The maximum force that should be applied to constrain the bodies.
  4967. */
  4968. constructor(bodyA, pivotA, bodyB, pivotB, maxForce) {
  4969. if (pivotA === void 0) {
  4970. pivotA = new Vec3();
  4971. }
  4972. if (pivotB === void 0) {
  4973. pivotB = new Vec3();
  4974. }
  4975. if (maxForce === void 0) {
  4976. maxForce = 1e6;
  4977. }
  4978. super(bodyA, bodyB);
  4979. this.pivotA = pivotA.clone();
  4980. this.pivotB = pivotB.clone();
  4981. const x = this.equationX = new ContactEquation(bodyA, bodyB);
  4982. const y = this.equationY = new ContactEquation(bodyA, bodyB);
  4983. const z = this.equationZ = new ContactEquation(bodyA, bodyB); // Equations to be fed to the solver
  4984. this.equations.push(x, y, z); // Make the equations bidirectional
  4985. x.minForce = y.minForce = z.minForce = -maxForce;
  4986. x.maxForce = y.maxForce = z.maxForce = maxForce;
  4987. x.ni.set(1, 0, 0);
  4988. y.ni.set(0, 1, 0);
  4989. z.ni.set(0, 0, 1);
  4990. }
  4991. update() {
  4992. const bodyA = this.bodyA;
  4993. const bodyB = this.bodyB;
  4994. const x = this.equationX;
  4995. const y = this.equationY;
  4996. const z = this.equationZ; // Rotate the pivots to world space
  4997. bodyA.quaternion.vmult(this.pivotA, x.ri);
  4998. bodyB.quaternion.vmult(this.pivotB, x.rj);
  4999. y.ri.copy(x.ri);
  5000. y.rj.copy(x.rj);
  5001. z.ri.copy(x.ri);
  5002. z.rj.copy(x.rj);
  5003. }
  5004. }
  5005. /**
  5006. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  5007. */
  5008. class ConeEquation extends Equation {
  5009. /**
  5010. * Local axis in A
  5011. */
  5012. /**
  5013. * Local axis in B
  5014. */
  5015. /**
  5016. * The "cone angle" to keep
  5017. */
  5018. constructor(bodyA, bodyB, options) {
  5019. if (options === void 0) {
  5020. options = {};
  5021. }
  5022. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5023. super(bodyA, bodyB, -maxForce, maxForce);
  5024. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5025. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  5026. this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  5027. }
  5028. computeB(h) {
  5029. const a = this.a;
  5030. const b = this.b;
  5031. const ni = this.axisA;
  5032. const nj = this.axisB;
  5033. const nixnj = tmpVec1$2;
  5034. const njxni = tmpVec2$2;
  5035. const GA = this.jacobianElementA;
  5036. const GB = this.jacobianElementB; // Caluclate cross products
  5037. ni.cross(nj, nixnj);
  5038. nj.cross(ni, njxni); // The angle between two vector is:
  5039. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  5040. // g = a * b
  5041. // gdot = (b x a) * wi + (a x b) * wj
  5042. // G = [0 bxa 0 axb]
  5043. // W = [vi wi vj wj]
  5044. GA.rotational.copy(njxni);
  5045. GB.rotational.copy(nixnj);
  5046. const g = Math.cos(this.angle) - ni.dot(nj);
  5047. const GW = this.computeGW();
  5048. const GiMf = this.computeGiMf();
  5049. const B = -g * a - GW * b - h * GiMf;
  5050. return B;
  5051. }
  5052. }
  5053. const tmpVec1$2 = new Vec3();
  5054. const tmpVec2$2 = new Vec3();
  5055. /**
  5056. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  5057. */
  5058. class RotationalEquation extends Equation {
  5059. /**
  5060. * World oriented rotational axis.
  5061. */
  5062. /**
  5063. * World oriented rotational axis.
  5064. */
  5065. /**
  5066. * maxAngle
  5067. */
  5068. constructor(bodyA, bodyB, options) {
  5069. if (options === void 0) {
  5070. options = {};
  5071. }
  5072. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5073. super(bodyA, bodyB, -maxForce, maxForce);
  5074. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5075. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  5076. this.maxAngle = Math.PI / 2;
  5077. }
  5078. computeB(h) {
  5079. const a = this.a;
  5080. const b = this.b;
  5081. const ni = this.axisA;
  5082. const nj = this.axisB;
  5083. const nixnj = tmpVec1$1;
  5084. const njxni = tmpVec2$1;
  5085. const GA = this.jacobianElementA;
  5086. const GB = this.jacobianElementB; // Caluclate cross products
  5087. ni.cross(nj, nixnj);
  5088. nj.cross(ni, njxni); // g = ni * nj
  5089. // gdot = (nj x ni) * wi + (ni x nj) * wj
  5090. // G = [0 njxni 0 nixnj]
  5091. // W = [vi wi vj wj]
  5092. GA.rotational.copy(njxni);
  5093. GB.rotational.copy(nixnj);
  5094. const g = Math.cos(this.maxAngle) - ni.dot(nj);
  5095. const GW = this.computeGW();
  5096. const GiMf = this.computeGiMf();
  5097. const B = -g * a - GW * b - h * GiMf;
  5098. return B;
  5099. }
  5100. }
  5101. const tmpVec1$1 = new Vec3();
  5102. const tmpVec2$1 = new Vec3();
  5103. /**
  5104. * A Cone Twist constraint, useful for ragdolls.
  5105. */
  5106. class ConeTwistConstraint extends PointToPointConstraint {
  5107. /**
  5108. * The axis direction for the constraint of the body A.
  5109. */
  5110. /**
  5111. * The axis direction for the constraint of the body B.
  5112. */
  5113. /**
  5114. * The aperture angle of the cone.
  5115. */
  5116. /**
  5117. * The twist angle of the joint.
  5118. */
  5119. constructor(bodyA, bodyB, options) {
  5120. if (options === void 0) {
  5121. options = {};
  5122. }
  5123. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between
  5124. const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  5125. const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  5126. super(bodyA, pivotA, bodyB, pivotB, maxForce);
  5127. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  5128. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  5129. this.collideConnected = !!options.collideConnected;
  5130. this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  5131. const c = this.coneEquation = new ConeEquation(bodyA, bodyB, options);
  5132. const t = this.twistEquation = new RotationalEquation(bodyA, bodyB, options);
  5133. this.twistAngle = typeof options.twistAngle !== 'undefined' ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward
  5134. c.maxForce = 0;
  5135. c.minForce = -maxForce; // Make the twist equation add torque toward the initial position
  5136. t.maxForce = 0;
  5137. t.minForce = -maxForce;
  5138. this.equations.push(c, t);
  5139. }
  5140. update() {
  5141. const bodyA = this.bodyA;
  5142. const bodyB = this.bodyB;
  5143. const cone = this.coneEquation;
  5144. const twist = this.twistEquation;
  5145. super.update(); // Update the axes to the cone constraint
  5146. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  5147. bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint
  5148. this.axisA.tangents(twist.axisA, twist.axisA);
  5149. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  5150. this.axisB.tangents(twist.axisB, twist.axisB);
  5151. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  5152. cone.angle = this.angle;
  5153. twist.maxAngle = this.twistAngle;
  5154. }
  5155. }
  5156. new Vec3();
  5157. new Vec3();
  5158. /**
  5159. * Constrains two bodies to be at a constant distance from each others center of mass.
  5160. */
  5161. class DistanceConstraint extends Constraint {
  5162. /**
  5163. * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  5164. */
  5165. /**
  5166. * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.
  5167. * @param maxForce The maximum force that should be applied to constrain the bodies.
  5168. */
  5169. constructor(bodyA, bodyB, distance, maxForce) {
  5170. if (maxForce === void 0) {
  5171. maxForce = 1e6;
  5172. }
  5173. super(bodyA, bodyB);
  5174. if (typeof distance === 'undefined') {
  5175. distance = bodyA.position.distanceTo(bodyB.position);
  5176. }
  5177. this.distance = distance;
  5178. const eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  5179. this.equations.push(eq); // Make it bidirectional
  5180. eq.minForce = -maxForce;
  5181. eq.maxForce = maxForce;
  5182. }
  5183. /**
  5184. * update
  5185. */
  5186. update() {
  5187. const bodyA = this.bodyA;
  5188. const bodyB = this.bodyB;
  5189. const eq = this.distanceEquation;
  5190. const halfDist = this.distance * 0.5;
  5191. const normal = eq.ni;
  5192. bodyB.position.vsub(bodyA.position, normal);
  5193. normal.normalize();
  5194. normal.scale(halfDist, eq.ri);
  5195. normal.scale(-halfDist, eq.rj);
  5196. }
  5197. }
  5198. /**
  5199. * Lock constraint. Will remove all degrees of freedom between the bodies.
  5200. */
  5201. class LockConstraint extends PointToPointConstraint {
  5202. constructor(bodyA, bodyB, options) {
  5203. if (options === void 0) {
  5204. options = {};
  5205. }
  5206. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between
  5207. const pivotA = new Vec3();
  5208. const pivotB = new Vec3();
  5209. const halfWay = new Vec3();
  5210. bodyA.position.vadd(bodyB.position, halfWay);
  5211. halfWay.scale(0.5, halfWay);
  5212. bodyB.pointToLocalFrame(halfWay, pivotB);
  5213. bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies
  5214. super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces
  5215. this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);
  5216. this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);
  5217. this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);
  5218. this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);
  5219. this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);
  5220. this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place
  5221. const r1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
  5222. const r2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
  5223. const r3 = this.rotationalEquation3 = new RotationalEquation(bodyA, bodyB, options);
  5224. this.equations.push(r1, r2, r3);
  5225. }
  5226. /**
  5227. * update
  5228. */
  5229. update() {
  5230. const bodyA = this.bodyA;
  5231. const bodyB = this.bodyB;
  5232. this.motorEquation;
  5233. const r1 = this.rotationalEquation1;
  5234. const r2 = this.rotationalEquation2;
  5235. const r3 = this.rotationalEquation3;
  5236. LockConstraint_update_tmpVec1;
  5237. LockConstraint_update_tmpVec2;
  5238. super.update(); // These vector pairs must be orthogonal
  5239. bodyA.vectorToWorldFrame(this.xA, r1.axisA);
  5240. bodyB.vectorToWorldFrame(this.yB, r1.axisB);
  5241. bodyA.vectorToWorldFrame(this.yA, r2.axisA);
  5242. bodyB.vectorToWorldFrame(this.zB, r2.axisB);
  5243. bodyA.vectorToWorldFrame(this.zA, r3.axisA);
  5244. bodyB.vectorToWorldFrame(this.xB, r3.axisB);
  5245. }
  5246. }
  5247. const LockConstraint_update_tmpVec1 = new Vec3();
  5248. const LockConstraint_update_tmpVec2 = new Vec3();
  5249. /**
  5250. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  5251. */
  5252. class RotationalMotorEquation extends Equation {
  5253. /**
  5254. * World oriented rotational axis.
  5255. */
  5256. /**
  5257. * World oriented rotational axis.
  5258. */
  5259. /**
  5260. * Motor velocity.
  5261. */
  5262. constructor(bodyA, bodyB, maxForce) {
  5263. if (maxForce === void 0) {
  5264. maxForce = 1e6;
  5265. }
  5266. super(bodyA, bodyB, -maxForce, maxForce);
  5267. this.axisA = new Vec3();
  5268. this.axisB = new Vec3();
  5269. this.targetVelocity = 0;
  5270. }
  5271. computeB(h) {
  5272. this.a;
  5273. const b = this.b;
  5274. this.bi;
  5275. this.bj;
  5276. const axisA = this.axisA;
  5277. const axisB = this.axisB;
  5278. const GA = this.jacobianElementA;
  5279. const GB = this.jacobianElementB; // g = 0
  5280. // gdot = axisA * wi - axisB * wj
  5281. // gdot = G * W = G * [vi wi vj wj]
  5282. // =>
  5283. // G = [0 axisA 0 -axisB]
  5284. GA.rotational.copy(axisA);
  5285. axisB.negate(GB.rotational);
  5286. const GW = this.computeGW() - this.targetVelocity;
  5287. const GiMf = this.computeGiMf();
  5288. const B = -GW * b - h * GiMf;
  5289. return B;
  5290. }
  5291. }
  5292. /**
  5293. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  5294. */
  5295. class HingeConstraint extends PointToPointConstraint {
  5296. /**
  5297. * Rotation axis, defined locally in bodyA.
  5298. */
  5299. /**
  5300. * Rotation axis, defined locally in bodyB.
  5301. */
  5302. constructor(bodyA, bodyB, options) {
  5303. if (options === void 0) {
  5304. options = {};
  5305. }
  5306. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5307. const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  5308. const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  5309. super(bodyA, pivotA, bodyB, pivotB, maxForce);
  5310. const axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5311. axisA.normalize();
  5312. const axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0);
  5313. axisB.normalize();
  5314. this.collideConnected = !!options.collideConnected;
  5315. const rotational1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
  5316. const rotational2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
  5317. const motor = this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce);
  5318. motor.enabled = false; // Not enabled by default
  5319. // Equations to be fed to the solver
  5320. this.equations.push(rotational1, rotational2, motor);
  5321. }
  5322. /**
  5323. * enableMotor
  5324. */
  5325. enableMotor() {
  5326. this.motorEquation.enabled = true;
  5327. }
  5328. /**
  5329. * disableMotor
  5330. */
  5331. disableMotor() {
  5332. this.motorEquation.enabled = false;
  5333. }
  5334. /**
  5335. * setMotorSpeed
  5336. */
  5337. setMotorSpeed(speed) {
  5338. this.motorEquation.targetVelocity = speed;
  5339. }
  5340. /**
  5341. * setMotorMaxForce
  5342. */
  5343. setMotorMaxForce(maxForce) {
  5344. this.motorEquation.maxForce = maxForce;
  5345. this.motorEquation.minForce = -maxForce;
  5346. }
  5347. /**
  5348. * update
  5349. */
  5350. update() {
  5351. const bodyA = this.bodyA;
  5352. const bodyB = this.bodyB;
  5353. const motor = this.motorEquation;
  5354. const r1 = this.rotationalEquation1;
  5355. const r2 = this.rotationalEquation2;
  5356. const worldAxisA = HingeConstraint_update_tmpVec1;
  5357. const worldAxisB = HingeConstraint_update_tmpVec2;
  5358. const axisA = this.axisA;
  5359. const axisB = this.axisB;
  5360. super.update(); // Get world axes
  5361. bodyA.quaternion.vmult(axisA, worldAxisA);
  5362. bodyB.quaternion.vmult(axisB, worldAxisB);
  5363. worldAxisA.tangents(r1.axisA, r2.axisA);
  5364. r1.axisB.copy(worldAxisB);
  5365. r2.axisB.copy(worldAxisB);
  5366. if (this.motorEquation.enabled) {
  5367. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  5368. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  5369. }
  5370. }
  5371. }
  5372. const HingeConstraint_update_tmpVec1 = new Vec3();
  5373. const HingeConstraint_update_tmpVec2 = new Vec3();
  5374. /**
  5375. * Constrains the slipping in a contact along a tangent
  5376. */
  5377. class FrictionEquation extends Equation {
  5378. // Tangent
  5379. /**
  5380. * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  5381. */
  5382. constructor(bodyA, bodyB, slipForce) {
  5383. super(bodyA, bodyB, -slipForce, slipForce);
  5384. this.ri = new Vec3();
  5385. this.rj = new Vec3();
  5386. this.t = new Vec3();
  5387. }
  5388. computeB(h) {
  5389. this.a;
  5390. const b = this.b;
  5391. this.bi;
  5392. this.bj;
  5393. const ri = this.ri;
  5394. const rj = this.rj;
  5395. const rixt = FrictionEquation_computeB_temp1;
  5396. const rjxt = FrictionEquation_computeB_temp2;
  5397. const t = this.t; // Caluclate cross products
  5398. ri.cross(t, rixt);
  5399. rj.cross(t, rjxt); // G = [-t -rixt t rjxt]
  5400. // And remember, this is a pure velocity constraint, g is always zero!
  5401. const GA = this.jacobianElementA;
  5402. const GB = this.jacobianElementB;
  5403. t.negate(GA.spatial);
  5404. rixt.negate(GA.rotational);
  5405. GB.spatial.copy(t);
  5406. GB.rotational.copy(rjxt);
  5407. const GW = this.computeGW();
  5408. const GiMf = this.computeGiMf();
  5409. const B = -GW * b - h * GiMf;
  5410. return B;
  5411. }
  5412. }
  5413. const FrictionEquation_computeB_temp1 = new Vec3();
  5414. const FrictionEquation_computeB_temp2 = new Vec3();
  5415. /**
  5416. * Defines what happens when two materials meet.
  5417. * @todo Refactor materials to materialA and materialB
  5418. */
  5419. class ContactMaterial {
  5420. /**
  5421. * Identifier of this material.
  5422. */
  5423. /**
  5424. * Participating materials.
  5425. */
  5426. /**
  5427. * Friction coefficient.
  5428. * @default 0.3
  5429. */
  5430. /**
  5431. * Restitution coefficient.
  5432. * @default 0.3
  5433. */
  5434. /**
  5435. * Stiffness of the produced contact equations.
  5436. * @default 1e7
  5437. */
  5438. /**
  5439. * Relaxation time of the produced contact equations.
  5440. * @default 3
  5441. */
  5442. /**
  5443. * Stiffness of the produced friction equations.
  5444. * @default 1e7
  5445. */
  5446. /**
  5447. * Relaxation time of the produced friction equations
  5448. * @default 3
  5449. */
  5450. constructor(m1, m2, options) {
  5451. options = Utils.defaults(options, {
  5452. friction: 0.3,
  5453. restitution: 0.3,
  5454. contactEquationStiffness: 1e7,
  5455. contactEquationRelaxation: 3,
  5456. frictionEquationStiffness: 1e7,
  5457. frictionEquationRelaxation: 3
  5458. });
  5459. this.id = ContactMaterial.idCounter++;
  5460. this.materials = [m1, m2];
  5461. this.friction = options.friction;
  5462. this.restitution = options.restitution;
  5463. this.contactEquationStiffness = options.contactEquationStiffness;
  5464. this.contactEquationRelaxation = options.contactEquationRelaxation;
  5465. this.frictionEquationStiffness = options.frictionEquationStiffness;
  5466. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  5467. }
  5468. }
  5469. ContactMaterial.idCounter = 0;
  5470. /**
  5471. * Defines a physics material.
  5472. */
  5473. class Material {
  5474. /**
  5475. * Material name.
  5476. * If options is a string, name will be set to that string.
  5477. * @todo Deprecate this
  5478. */
  5479. /** Material id. */
  5480. /**
  5481. * Friction for this material.
  5482. * If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.
  5483. */
  5484. /**
  5485. * Restitution for this material.
  5486. * If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.
  5487. */
  5488. constructor(options) {
  5489. if (options === void 0) {
  5490. options = {};
  5491. }
  5492. let name = ''; // Backwards compatibility fix
  5493. if (typeof options === 'string') {
  5494. //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`)
  5495. name = options;
  5496. options = {};
  5497. }
  5498. this.name = name;
  5499. this.id = Material.idCounter++;
  5500. this.friction = typeof options.friction !== 'undefined' ? options.friction : -1;
  5501. this.restitution = typeof options.restitution !== 'undefined' ? options.restitution : -1;
  5502. }
  5503. }
  5504. Material.idCounter = 0;
  5505. /**
  5506. * A spring, connecting two bodies.
  5507. * @example
  5508. * const spring = new Spring(boxBody, sphereBody, {
  5509. * restLength: 0,
  5510. * stiffness: 50,
  5511. * damping: 1,
  5512. * })
  5513. *
  5514. * // Compute the force after each step
  5515. * world.addEventListener('postStep', (event) => {
  5516. * spring.applyForce()
  5517. * })
  5518. */
  5519. class Spring {
  5520. /**
  5521. * Rest length of the spring. A number > 0.
  5522. * @default 1
  5523. */
  5524. /**
  5525. * Stiffness of the spring. A number >= 0.
  5526. * @default 100
  5527. */
  5528. /**
  5529. * Damping of the spring. A number >= 0.
  5530. * @default 1
  5531. */
  5532. /**
  5533. * First connected body.
  5534. */
  5535. /**
  5536. * Second connected body.
  5537. */
  5538. /**
  5539. * Anchor for bodyA in local bodyA coordinates.
  5540. * Where to hook the spring to body A, in local body coordinates.
  5541. * @default new Vec3()
  5542. */
  5543. /**
  5544. * Anchor for bodyB in local bodyB coordinates.
  5545. * Where to hook the spring to body B, in local body coordinates.
  5546. * @default new Vec3()
  5547. */
  5548. constructor(bodyA, bodyB, options) {
  5549. if (options === void 0) {
  5550. options = {};
  5551. }
  5552. this.restLength = typeof options.restLength === 'number' ? options.restLength : 1;
  5553. this.stiffness = options.stiffness || 100;
  5554. this.damping = options.damping || 1;
  5555. this.bodyA = bodyA;
  5556. this.bodyB = bodyB;
  5557. this.localAnchorA = new Vec3();
  5558. this.localAnchorB = new Vec3();
  5559. if (options.localAnchorA) {
  5560. this.localAnchorA.copy(options.localAnchorA);
  5561. }
  5562. if (options.localAnchorB) {
  5563. this.localAnchorB.copy(options.localAnchorB);
  5564. }
  5565. if (options.worldAnchorA) {
  5566. this.setWorldAnchorA(options.worldAnchorA);
  5567. }
  5568. if (options.worldAnchorB) {
  5569. this.setWorldAnchorB(options.worldAnchorB);
  5570. }
  5571. }
  5572. /**
  5573. * Set the anchor point on body A, using world coordinates.
  5574. */
  5575. setWorldAnchorA(worldAnchorA) {
  5576. this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA);
  5577. }
  5578. /**
  5579. * Set the anchor point on body B, using world coordinates.
  5580. */
  5581. setWorldAnchorB(worldAnchorB) {
  5582. this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB);
  5583. }
  5584. /**
  5585. * Get the anchor point on body A, in world coordinates.
  5586. * @param result The vector to store the result in.
  5587. */
  5588. getWorldAnchorA(result) {
  5589. this.bodyA.pointToWorldFrame(this.localAnchorA, result);
  5590. }
  5591. /**
  5592. * Get the anchor point on body B, in world coordinates.
  5593. * @param result The vector to store the result in.
  5594. */
  5595. getWorldAnchorB(result) {
  5596. this.bodyB.pointToWorldFrame(this.localAnchorB, result);
  5597. }
  5598. /**
  5599. * Apply the spring force to the connected bodies.
  5600. */
  5601. applyForce() {
  5602. const k = this.stiffness;
  5603. const d = this.damping;
  5604. const l = this.restLength;
  5605. const bodyA = this.bodyA;
  5606. const bodyB = this.bodyB;
  5607. const r = applyForce_r;
  5608. const r_unit = applyForce_r_unit;
  5609. const u = applyForce_u;
  5610. const f = applyForce_f;
  5611. const tmp = applyForce_tmp;
  5612. const worldAnchorA = applyForce_worldAnchorA;
  5613. const worldAnchorB = applyForce_worldAnchorB;
  5614. const ri = applyForce_ri;
  5615. const rj = applyForce_rj;
  5616. const ri_x_f = applyForce_ri_x_f;
  5617. const rj_x_f = applyForce_rj_x_f; // Get world anchors
  5618. this.getWorldAnchorA(worldAnchorA);
  5619. this.getWorldAnchorB(worldAnchorB); // Get offset points
  5620. worldAnchorA.vsub(bodyA.position, ri);
  5621. worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points
  5622. worldAnchorB.vsub(worldAnchorA, r);
  5623. const rlen = r.length();
  5624. r_unit.copy(r);
  5625. r_unit.normalize(); // Compute relative velocity of the anchor points, u
  5626. bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity
  5627. bodyB.angularVelocity.cross(rj, tmp);
  5628. u.vadd(tmp, u);
  5629. bodyA.angularVelocity.cross(ri, tmp);
  5630. u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u )
  5631. r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies
  5632. bodyA.force.vsub(f, bodyA.force);
  5633. bodyB.force.vadd(f, bodyB.force); // Angular force
  5634. ri.cross(f, ri_x_f);
  5635. rj.cross(f, rj_x_f);
  5636. bodyA.torque.vsub(ri_x_f, bodyA.torque);
  5637. bodyB.torque.vadd(rj_x_f, bodyB.torque);
  5638. }
  5639. }
  5640. const applyForce_r = new Vec3();
  5641. const applyForce_r_unit = new Vec3();
  5642. const applyForce_u = new Vec3();
  5643. const applyForce_f = new Vec3();
  5644. const applyForce_worldAnchorA = new Vec3();
  5645. const applyForce_worldAnchorB = new Vec3();
  5646. const applyForce_ri = new Vec3();
  5647. const applyForce_rj = new Vec3();
  5648. const applyForce_ri_x_f = new Vec3();
  5649. const applyForce_rj_x_f = new Vec3();
  5650. const applyForce_tmp = new Vec3();
  5651. /**
  5652. * WheelInfo
  5653. */
  5654. class WheelInfo {
  5655. /**
  5656. * Max travel distance of the suspension, in meters.
  5657. * @default 1
  5658. */
  5659. /**
  5660. * Speed to apply to the wheel rotation when the wheel is sliding.
  5661. * @default -0.1
  5662. */
  5663. /**
  5664. * If the customSlidingRotationalSpeed should be used.
  5665. * @default false
  5666. */
  5667. /**
  5668. * sliding
  5669. */
  5670. /**
  5671. * Connection point, defined locally in the chassis body frame.
  5672. */
  5673. /**
  5674. * chassisConnectionPointWorld
  5675. */
  5676. /**
  5677. * directionLocal
  5678. */
  5679. /**
  5680. * directionWorld
  5681. */
  5682. /**
  5683. * axleLocal
  5684. */
  5685. /**
  5686. * axleWorld
  5687. */
  5688. /**
  5689. * suspensionRestLength
  5690. * @default 1
  5691. */
  5692. /**
  5693. * suspensionMaxLength
  5694. * @default 2
  5695. */
  5696. /**
  5697. * radius
  5698. * @default 1
  5699. */
  5700. /**
  5701. * suspensionStiffness
  5702. * @default 100
  5703. */
  5704. /**
  5705. * dampingCompression
  5706. * @default 10
  5707. */
  5708. /**
  5709. * dampingRelaxation
  5710. * @default 10
  5711. */
  5712. /**
  5713. * frictionSlip
  5714. * @default 10.5
  5715. */
  5716. /** forwardAcceleration */
  5717. /** sideAcceleration */
  5718. /**
  5719. * steering
  5720. * @default 0
  5721. */
  5722. /**
  5723. * Rotation value, in radians.
  5724. * @default 0
  5725. */
  5726. /**
  5727. * deltaRotation
  5728. * @default 0
  5729. */
  5730. /**
  5731. * rollInfluence
  5732. * @default 0.01
  5733. */
  5734. /**
  5735. * maxSuspensionForce
  5736. */
  5737. /**
  5738. * engineForce
  5739. */
  5740. /**
  5741. * brake
  5742. */
  5743. /**
  5744. * isFrontWheel
  5745. * @default true
  5746. */
  5747. /**
  5748. * clippedInvContactDotSuspension
  5749. * @default 1
  5750. */
  5751. /**
  5752. * suspensionRelativeVelocity
  5753. * @default 0
  5754. */
  5755. /**
  5756. * suspensionForce
  5757. * @default 0
  5758. */
  5759. /**
  5760. * slipInfo
  5761. */
  5762. /**
  5763. * skidInfo
  5764. * @default 0
  5765. */
  5766. /**
  5767. * suspensionLength
  5768. * @default 0
  5769. */
  5770. /**
  5771. * sideImpulse
  5772. */
  5773. /**
  5774. * forwardImpulse
  5775. */
  5776. /**
  5777. * The result from raycasting.
  5778. */
  5779. /**
  5780. * Wheel world transform.
  5781. */
  5782. /**
  5783. * isInContact
  5784. */
  5785. constructor(options) {
  5786. if (options === void 0) {
  5787. options = {};
  5788. }
  5789. options = Utils.defaults(options, {
  5790. chassisConnectionPointLocal: new Vec3(),
  5791. chassisConnectionPointWorld: new Vec3(),
  5792. directionLocal: new Vec3(),
  5793. directionWorld: new Vec3(),
  5794. axleLocal: new Vec3(),
  5795. axleWorld: new Vec3(),
  5796. suspensionRestLength: 1,
  5797. suspensionMaxLength: 2,
  5798. radius: 1,
  5799. suspensionStiffness: 100,
  5800. dampingCompression: 10,
  5801. dampingRelaxation: 10,
  5802. frictionSlip: 10.5,
  5803. forwardAcceleration: 1,
  5804. sideAcceleration: 1,
  5805. steering: 0,
  5806. rotation: 0,
  5807. deltaRotation: 0,
  5808. rollInfluence: 0.01,
  5809. maxSuspensionForce: Number.MAX_VALUE,
  5810. isFrontWheel: true,
  5811. clippedInvContactDotSuspension: 1,
  5812. suspensionRelativeVelocity: 0,
  5813. suspensionForce: 0,
  5814. slipInfo: 0,
  5815. skidInfo: 0,
  5816. suspensionLength: 0,
  5817. maxSuspensionTravel: 1,
  5818. useCustomSlidingRotationalSpeed: false,
  5819. customSlidingRotationalSpeed: -0.1
  5820. });
  5821. this.maxSuspensionTravel = options.maxSuspensionTravel;
  5822. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  5823. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  5824. this.sliding = false;
  5825. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  5826. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  5827. this.directionLocal = options.directionLocal.clone();
  5828. this.directionWorld = options.directionWorld.clone();
  5829. this.axleLocal = options.axleLocal.clone();
  5830. this.axleWorld = options.axleWorld.clone();
  5831. this.suspensionRestLength = options.suspensionRestLength;
  5832. this.suspensionMaxLength = options.suspensionMaxLength;
  5833. this.radius = options.radius;
  5834. this.suspensionStiffness = options.suspensionStiffness;
  5835. this.dampingCompression = options.dampingCompression;
  5836. this.dampingRelaxation = options.dampingRelaxation;
  5837. this.frictionSlip = options.frictionSlip;
  5838. this.forwardAcceleration = options.forwardAcceleration;
  5839. this.sideAcceleration = options.sideAcceleration;
  5840. this.steering = 0;
  5841. this.rotation = 0;
  5842. this.deltaRotation = 0;
  5843. this.rollInfluence = options.rollInfluence;
  5844. this.maxSuspensionForce = options.maxSuspensionForce;
  5845. this.engineForce = 0;
  5846. this.brake = 0;
  5847. this.isFrontWheel = options.isFrontWheel;
  5848. this.clippedInvContactDotSuspension = 1;
  5849. this.suspensionRelativeVelocity = 0;
  5850. this.suspensionForce = 0;
  5851. this.slipInfo = 0;
  5852. this.skidInfo = 0;
  5853. this.suspensionLength = 0;
  5854. this.sideImpulse = 0;
  5855. this.forwardImpulse = 0;
  5856. this.raycastResult = new RaycastResult();
  5857. this.worldTransform = new Transform();
  5858. this.isInContact = false;
  5859. }
  5860. updateWheel(chassis) {
  5861. const raycastResult = this.raycastResult;
  5862. if (this.isInContact) {
  5863. const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  5864. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  5865. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  5866. const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);
  5867. if (project >= -0.1) {
  5868. this.suspensionRelativeVelocity = 0.0;
  5869. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  5870. } else {
  5871. const inv = -1 / project;
  5872. this.suspensionRelativeVelocity = projVel * inv;
  5873. this.clippedInvContactDotSuspension = inv;
  5874. }
  5875. } else {
  5876. // Not in contact : position wheel in a nice (rest length) position
  5877. raycastResult.suspensionLength = this.suspensionRestLength;
  5878. this.suspensionRelativeVelocity = 0.0;
  5879. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  5880. this.clippedInvContactDotSuspension = 1.0;
  5881. }
  5882. }
  5883. }
  5884. const chassis_velocity_at_contactPoint = new Vec3();
  5885. const relpos = new Vec3();
  5886. /**
  5887. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  5888. */
  5889. class RaycastVehicle {
  5890. /** The car chassis body. */
  5891. /** The wheels. */
  5892. /** Will be set to true if the car is sliding. */
  5893. /** Index of the right axis. x=0, y=1, z=2 */
  5894. /** Index of the forward axis. x=0, y=1, z=2 */
  5895. /** Index of the up axis. x=0, y=1, z=2 */
  5896. /** The constraints. */
  5897. /** Optional pre-step callback. */
  5898. /** Number of wheels on the ground. */
  5899. constructor(options) {
  5900. this.chassisBody = options.chassisBody;
  5901. this.wheelInfos = [];
  5902. this.sliding = false;
  5903. this.world = null;
  5904. this.indexRightAxis = typeof options.indexRightAxis !== 'undefined' ? options.indexRightAxis : 2;
  5905. this.indexForwardAxis = typeof options.indexForwardAxis !== 'undefined' ? options.indexForwardAxis : 0;
  5906. this.indexUpAxis = typeof options.indexUpAxis !== 'undefined' ? options.indexUpAxis : 1;
  5907. this.constraints = [];
  5908. this.preStepCallback = () => {};
  5909. this.currentVehicleSpeedKmHour = 0;
  5910. this.numWheelsOnGround = 0;
  5911. }
  5912. /**
  5913. * Add a wheel. For information about the options, see `WheelInfo`.
  5914. */
  5915. addWheel(options) {
  5916. if (options === void 0) {
  5917. options = {};
  5918. }
  5919. const info = new WheelInfo(options);
  5920. const index = this.wheelInfos.length;
  5921. this.wheelInfos.push(info);
  5922. return index;
  5923. }
  5924. /**
  5925. * Set the steering value of a wheel.
  5926. */
  5927. setSteeringValue(value, wheelIndex) {
  5928. const wheel = this.wheelInfos[wheelIndex];
  5929. wheel.steering = value;
  5930. }
  5931. /**
  5932. * Set the wheel force to apply on one of the wheels each time step
  5933. */
  5934. applyEngineForce(value, wheelIndex) {
  5935. this.wheelInfos[wheelIndex].engineForce = value;
  5936. }
  5937. /**
  5938. * Set the braking force of a wheel
  5939. */
  5940. setBrake(brake, wheelIndex) {
  5941. this.wheelInfos[wheelIndex].brake = brake;
  5942. }
  5943. /**
  5944. * Add the vehicle including its constraints to the world.
  5945. */
  5946. addToWorld(world) {
  5947. world.addBody(this.chassisBody);
  5948. const that = this;
  5949. this.preStepCallback = () => {
  5950. that.updateVehicle(world.dt);
  5951. };
  5952. world.addEventListener('preStep', this.preStepCallback);
  5953. this.world = world;
  5954. }
  5955. /**
  5956. * Get one of the wheel axles, world-oriented.
  5957. */
  5958. getVehicleAxisWorld(axisIndex, result) {
  5959. result.set(axisIndex === 0 ? 1 : 0, axisIndex === 1 ? 1 : 0, axisIndex === 2 ? 1 : 0);
  5960. this.chassisBody.vectorToWorldFrame(result, result);
  5961. }
  5962. updateVehicle(timeStep) {
  5963. const wheelInfos = this.wheelInfos;
  5964. const numWheels = wheelInfos.length;
  5965. const chassisBody = this.chassisBody;
  5966. for (let i = 0; i < numWheels; i++) {
  5967. this.updateWheelTransform(i);
  5968. }
  5969. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();
  5970. const forwardWorld = new Vec3();
  5971. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  5972. if (forwardWorld.dot(chassisBody.velocity) < 0) {
  5973. this.currentVehicleSpeedKmHour *= -1;
  5974. } // simulate suspension
  5975. for (let i = 0; i < numWheels; i++) {
  5976. this.castRay(wheelInfos[i]);
  5977. }
  5978. this.updateSuspension(timeStep);
  5979. const impulse = new Vec3();
  5980. const relpos = new Vec3();
  5981. for (let i = 0; i < numWheels; i++) {
  5982. //apply suspension force
  5983. const wheel = wheelInfos[i];
  5984. let suspensionForce = wheel.suspensionForce;
  5985. if (suspensionForce > wheel.maxSuspensionForce) {
  5986. suspensionForce = wheel.maxSuspensionForce;
  5987. }
  5988. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  5989. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  5990. chassisBody.applyImpulse(impulse, relpos);
  5991. }
  5992. this.updateFriction(timeStep);
  5993. const hitNormalWorldScaledWithProj = new Vec3();
  5994. const fwd = new Vec3();
  5995. const vel = new Vec3();
  5996. for (let i = 0; i < numWheels; i++) {
  5997. const wheel = wheelInfos[i]; //const relpos = new Vec3();
  5998. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  5999. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); // Hack to get the rotation in the correct direction
  6000. let m = 1;
  6001. switch (this.indexUpAxis) {
  6002. case 1:
  6003. m = -1;
  6004. break;
  6005. }
  6006. if (wheel.isInContact) {
  6007. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  6008. const proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  6009. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  6010. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  6011. const proj2 = fwd.dot(vel);
  6012. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  6013. }
  6014. if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed) {
  6015. // Apply custom rotation when accelerating and sliding
  6016. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  6017. } // Lock wheels
  6018. if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) {
  6019. wheel.deltaRotation = 0;
  6020. }
  6021. wheel.rotation += wheel.deltaRotation; // Use the old value
  6022. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  6023. }
  6024. }
  6025. updateSuspension(deltaTime) {
  6026. const chassisBody = this.chassisBody;
  6027. const chassisMass = chassisBody.mass;
  6028. const wheelInfos = this.wheelInfos;
  6029. const numWheels = wheelInfos.length;
  6030. for (let w_it = 0; w_it < numWheels; w_it++) {
  6031. const wheel = wheelInfos[w_it];
  6032. if (wheel.isInContact) {
  6033. let force; // Spring
  6034. const susp_length = wheel.suspensionRestLength;
  6035. const current_length = wheel.suspensionLength;
  6036. const length_diff = susp_length - current_length;
  6037. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; // Damper
  6038. const projected_rel_vel = wheel.suspensionRelativeVelocity;
  6039. let susp_damping;
  6040. if (projected_rel_vel < 0) {
  6041. susp_damping = wheel.dampingCompression;
  6042. } else {
  6043. susp_damping = wheel.dampingRelaxation;
  6044. }
  6045. force -= susp_damping * projected_rel_vel;
  6046. wheel.suspensionForce = force * chassisMass;
  6047. if (wheel.suspensionForce < 0) {
  6048. wheel.suspensionForce = 0;
  6049. }
  6050. } else {
  6051. wheel.suspensionForce = 0;
  6052. }
  6053. }
  6054. }
  6055. /**
  6056. * Remove the vehicle including its constraints from the world.
  6057. */
  6058. removeFromWorld(world) {
  6059. this.constraints;
  6060. world.removeBody(this.chassisBody);
  6061. world.removeEventListener('preStep', this.preStepCallback);
  6062. this.world = null;
  6063. }
  6064. castRay(wheel) {
  6065. const rayvector = castRay_rayvector;
  6066. const target = castRay_target;
  6067. this.updateWheelTransformWorld(wheel);
  6068. const chassisBody = this.chassisBody;
  6069. let depth = -1;
  6070. const raylen = wheel.suspensionRestLength + wheel.radius;
  6071. wheel.directionWorld.scale(raylen, rayvector);
  6072. const source = wheel.chassisConnectionPointWorld;
  6073. source.vadd(rayvector, target);
  6074. const raycastResult = wheel.raycastResult;
  6075. raycastResult.reset(); // Turn off ray collision with the chassis temporarily
  6076. const oldState = chassisBody.collisionResponse;
  6077. chassisBody.collisionResponse = false; // Cast ray against world
  6078. this.world.rayTest(source, target, raycastResult);
  6079. chassisBody.collisionResponse = oldState;
  6080. const object = raycastResult.body;
  6081. wheel.raycastResult.groundObject = 0;
  6082. if (object) {
  6083. depth = raycastResult.distance;
  6084. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  6085. wheel.isInContact = true;
  6086. const hitDistance = raycastResult.distance;
  6087. wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel
  6088. const minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  6089. const maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  6090. if (wheel.suspensionLength < minSuspensionLength) {
  6091. wheel.suspensionLength = minSuspensionLength;
  6092. }
  6093. if (wheel.suspensionLength > maxSuspensionLength) {
  6094. wheel.suspensionLength = maxSuspensionLength;
  6095. wheel.raycastResult.reset();
  6096. }
  6097. const denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  6098. const chassis_velocity_at_contactPoint = new Vec3();
  6099. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  6100. const projVel = wheel.raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);
  6101. if (denominator >= -0.1) {
  6102. wheel.suspensionRelativeVelocity = 0;
  6103. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  6104. } else {
  6105. const inv = -1 / denominator;
  6106. wheel.suspensionRelativeVelocity = projVel * inv;
  6107. wheel.clippedInvContactDotSuspension = inv;
  6108. }
  6109. } else {
  6110. //put wheel info as in rest position
  6111. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  6112. wheel.suspensionRelativeVelocity = 0.0;
  6113. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  6114. wheel.clippedInvContactDotSuspension = 1.0;
  6115. }
  6116. return depth;
  6117. }
  6118. updateWheelTransformWorld(wheel) {
  6119. wheel.isInContact = false;
  6120. const chassisBody = this.chassisBody;
  6121. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  6122. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  6123. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  6124. }
  6125. /**
  6126. * Update one of the wheel transform.
  6127. * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.
  6128. * @param wheelIndex The wheel index to update.
  6129. */
  6130. updateWheelTransform(wheelIndex) {
  6131. const up = tmpVec4;
  6132. const right = tmpVec5;
  6133. const fwd = tmpVec6;
  6134. const wheel = this.wheelInfos[wheelIndex];
  6135. this.updateWheelTransformWorld(wheel);
  6136. wheel.directionLocal.scale(-1, up);
  6137. right.copy(wheel.axleLocal);
  6138. up.cross(right, fwd);
  6139. fwd.normalize();
  6140. right.normalize(); // Rotate around steering over the wheelAxle
  6141. const steering = wheel.steering;
  6142. const steeringOrn = new Quaternion();
  6143. steeringOrn.setFromAxisAngle(up, steering);
  6144. const rotatingOrn = new Quaternion();
  6145. rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel
  6146. const q = wheel.worldTransform.quaternion;
  6147. this.chassisBody.quaternion.mult(steeringOrn, q);
  6148. q.mult(rotatingOrn, q);
  6149. q.normalize(); // world position of the wheel
  6150. const p = wheel.worldTransform.position;
  6151. p.copy(wheel.directionWorld);
  6152. p.scale(wheel.suspensionLength, p);
  6153. p.vadd(wheel.chassisConnectionPointWorld, p);
  6154. }
  6155. /**
  6156. * Get the world transform of one of the wheels
  6157. */
  6158. getWheelTransformWorld(wheelIndex) {
  6159. return this.wheelInfos[wheelIndex].worldTransform;
  6160. }
  6161. updateFriction(timeStep) {
  6162. const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards
  6163. const wheelInfos = this.wheelInfos;
  6164. const numWheels = wheelInfos.length;
  6165. const chassisBody = this.chassisBody;
  6166. const forwardWS = updateFriction_forwardWS;
  6167. const axle = updateFriction_axle;
  6168. this.numWheelsOnGround = 0;
  6169. for (let i = 0; i < numWheels; i++) {
  6170. const wheel = wheelInfos[i];
  6171. const groundObject = wheel.raycastResult.body;
  6172. if (groundObject) {
  6173. this.numWheelsOnGround++;
  6174. }
  6175. wheel.sideImpulse = 0;
  6176. wheel.forwardImpulse = 0;
  6177. if (!forwardWS[i]) {
  6178. forwardWS[i] = new Vec3();
  6179. }
  6180. if (!axle[i]) {
  6181. axle[i] = new Vec3();
  6182. }
  6183. }
  6184. for (let i = 0; i < numWheels; i++) {
  6185. const wheel = wheelInfos[i];
  6186. const groundObject = wheel.raycastResult.body;
  6187. if (groundObject) {
  6188. const axlei = axle[i];
  6189. const wheelTrans = this.getWheelTransformWorld(i); // Get world axle
  6190. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  6191. const surfNormalWS = wheel.raycastResult.hitNormalWorld;
  6192. const proj = axlei.dot(surfNormalWS);
  6193. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  6194. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  6195. axlei.normalize();
  6196. surfNormalWS.cross(axlei, forwardWS[i]);
  6197. forwardWS[i].normalize();
  6198. wheel.sideImpulse = resolveSingleBilateral(chassisBody, wheel.raycastResult.hitPointWorld, groundObject, wheel.raycastResult.hitPointWorld, axlei);
  6199. wheel.sideImpulse *= sideFrictionStiffness2;
  6200. }
  6201. }
  6202. const sideFactor = 1;
  6203. const fwdFactor = 0.5;
  6204. this.sliding = false;
  6205. for (let i = 0; i < numWheels; i++) {
  6206. const wheel = wheelInfos[i];
  6207. const groundObject = wheel.raycastResult.body;
  6208. let rollingFriction = 0;
  6209. wheel.slipInfo = 1;
  6210. if (groundObject) {
  6211. const defaultRollingFrictionImpulse = 0;
  6212. const maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  6213. // rollingFriction = calcRollingFriction(contactPt);
  6214. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  6215. rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0;
  6216. const factor = maxImpulse / rollingFriction;
  6217. wheel.slipInfo *= factor;
  6218. } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  6219. wheel.forwardImpulse = 0;
  6220. wheel.skidInfo = 1;
  6221. if (groundObject) {
  6222. wheel.skidInfo = 1;
  6223. const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  6224. const maximpSide = maximp;
  6225. const maximpSquared = maximp * maximpSide;
  6226. wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep;
  6227. const x = wheel.forwardImpulse * fwdFactor / wheel.forwardAcceleration;
  6228. const y = wheel.sideImpulse * sideFactor / wheel.sideAcceleration;
  6229. const impulseSquared = x * x + y * y;
  6230. wheel.sliding = false;
  6231. if (impulseSquared > maximpSquared) {
  6232. this.sliding = true;
  6233. wheel.sliding = true;
  6234. const factor = maximp / Math.sqrt(impulseSquared);
  6235. wheel.skidInfo *= factor;
  6236. }
  6237. }
  6238. }
  6239. if (this.sliding) {
  6240. for (let i = 0; i < numWheels; i++) {
  6241. const wheel = wheelInfos[i];
  6242. if (wheel.sideImpulse !== 0) {
  6243. if (wheel.skidInfo < 1) {
  6244. wheel.forwardImpulse *= wheel.skidInfo;
  6245. wheel.sideImpulse *= wheel.skidInfo;
  6246. }
  6247. }
  6248. }
  6249. } // apply the impulses
  6250. for (let i = 0; i < numWheels; i++) {
  6251. const wheel = wheelInfos[i];
  6252. const rel_pos = new Vec3();
  6253. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position
  6254. //rel_pos.copy(wheel.raycastResult.hitPointWorld);
  6255. if (wheel.forwardImpulse !== 0) {
  6256. const impulse = new Vec3();
  6257. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  6258. chassisBody.applyImpulse(impulse, rel_pos);
  6259. }
  6260. if (wheel.sideImpulse !== 0) {
  6261. const groundObject = wheel.raycastResult.body;
  6262. const rel_pos2 = new Vec3();
  6263. wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  6264. const sideImp = new Vec3();
  6265. axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence.
  6266. // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).
  6267. chassisBody.vectorToLocalFrame(rel_pos, rel_pos);
  6268. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  6269. chassisBody.vectorToWorldFrame(rel_pos, rel_pos);
  6270. chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground
  6271. sideImp.scale(-1, sideImp);
  6272. groundObject.applyImpulse(sideImp, rel_pos2);
  6273. }
  6274. }
  6275. }
  6276. }
  6277. new Vec3();
  6278. new Vec3();
  6279. new Vec3();
  6280. const tmpVec4 = new Vec3();
  6281. const tmpVec5 = new Vec3();
  6282. const tmpVec6 = new Vec3();
  6283. new Ray();
  6284. new Vec3();
  6285. const castRay_rayvector = new Vec3();
  6286. const castRay_target = new Vec3();
  6287. const directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)];
  6288. const updateFriction_surfNormalWS_scaled_proj = new Vec3();
  6289. const updateFriction_axle = [];
  6290. const updateFriction_forwardWS = [];
  6291. const sideFrictionStiffness2 = 1;
  6292. const calcRollingFriction_vel1 = new Vec3();
  6293. const calcRollingFriction_vel2 = new Vec3();
  6294. const calcRollingFriction_vel = new Vec3();
  6295. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  6296. let j1 = 0;
  6297. const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3();
  6298. // const rel_pos2 = new Vec3();
  6299. const vel1 = calcRollingFriction_vel1;
  6300. const vel2 = calcRollingFriction_vel2;
  6301. const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1);
  6302. // contactPosWorld.vsub(body1.position, rel_pos2);
  6303. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  6304. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  6305. vel1.vsub(vel2, vel);
  6306. const vrel = frictionDirectionWorld.dot(vel);
  6307. const denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  6308. const denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  6309. const relaxation = 1;
  6310. const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity
  6311. j1 = -vrel * jacDiagABInv;
  6312. if (maxImpulse < j1) {
  6313. j1 = maxImpulse;
  6314. }
  6315. if (j1 < -maxImpulse) {
  6316. j1 = -maxImpulse;
  6317. }
  6318. return j1;
  6319. }
  6320. const computeImpulseDenominator_r0 = new Vec3();
  6321. const computeImpulseDenominator_c0 = new Vec3();
  6322. const computeImpulseDenominator_vec = new Vec3();
  6323. const computeImpulseDenominator_m = new Vec3();
  6324. function computeImpulseDenominator(body, pos, normal) {
  6325. const r0 = computeImpulseDenominator_r0;
  6326. const c0 = computeImpulseDenominator_c0;
  6327. const vec = computeImpulseDenominator_vec;
  6328. const m = computeImpulseDenominator_m;
  6329. pos.vsub(body.position, r0);
  6330. r0.cross(normal, c0);
  6331. body.invInertiaWorld.vmult(c0, m);
  6332. m.cross(r0, vec);
  6333. return body.invMass + normal.dot(vec);
  6334. }
  6335. const resolveSingleBilateral_vel1 = new Vec3();
  6336. const resolveSingleBilateral_vel2 = new Vec3();
  6337. const resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects
  6338. function resolveSingleBilateral(body1, pos1, body2, pos2, normal) {
  6339. const normalLenSqr = normal.lengthSquared();
  6340. if (normalLenSqr > 1.1) {
  6341. return 0; // no impulse
  6342. } // const rel_pos1 = new Vec3();
  6343. // const rel_pos2 = new Vec3();
  6344. // pos1.vsub(body1.position, rel_pos1);
  6345. // pos2.vsub(body2.position, rel_pos2);
  6346. const vel1 = resolveSingleBilateral_vel1;
  6347. const vel2 = resolveSingleBilateral_vel2;
  6348. const vel = resolveSingleBilateral_vel;
  6349. body1.getVelocityAtWorldPoint(pos1, vel1);
  6350. body2.getVelocityAtWorldPoint(pos2, vel2);
  6351. vel1.vsub(vel2, vel);
  6352. const rel_vel = normal.dot(vel);
  6353. const contactDamping = 0.2;
  6354. const massTerm = 1 / (body1.invMass + body2.invMass);
  6355. const impulse = -contactDamping * rel_vel * massTerm;
  6356. return impulse;
  6357. }
  6358. /**
  6359. * Spherical shape
  6360. * @example
  6361. * const radius = 1
  6362. * const sphereShape = new CANNON.Sphere(radius)
  6363. * const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape })
  6364. * world.addBody(sphereBody)
  6365. */
  6366. class Sphere extends Shape {
  6367. /**
  6368. * The radius of the sphere.
  6369. */
  6370. /**
  6371. *
  6372. * @param radius The radius of the sphere, a non-negative number.
  6373. */
  6374. constructor(radius) {
  6375. super({
  6376. type: Shape.types.SPHERE
  6377. });
  6378. this.radius = radius !== undefined ? radius : 1.0;
  6379. if (this.radius < 0) {
  6380. throw new Error('The sphere radius cannot be negative.');
  6381. }
  6382. this.updateBoundingSphereRadius();
  6383. }
  6384. /** calculateLocalInertia */
  6385. calculateLocalInertia(mass, target) {
  6386. if (target === void 0) {
  6387. target = new Vec3();
  6388. }
  6389. const I = 2.0 * mass * this.radius * this.radius / 5.0;
  6390. target.x = I;
  6391. target.y = I;
  6392. target.z = I;
  6393. return target;
  6394. }
  6395. /** volume */
  6396. volume() {
  6397. return 4.0 * Math.PI * Math.pow(this.radius, 3) / 3.0;
  6398. }
  6399. updateBoundingSphereRadius() {
  6400. this.boundingSphereRadius = this.radius;
  6401. }
  6402. calculateWorldAABB(pos, quat, min, max) {
  6403. const r = this.radius;
  6404. const axes = ['x', 'y', 'z'];
  6405. for (let i = 0; i < axes.length; i++) {
  6406. const ax = axes[i];
  6407. min[ax] = pos[ax] - r;
  6408. max[ax] = pos[ax] + r;
  6409. }
  6410. }
  6411. }
  6412. /**
  6413. * Simple vehicle helper class with spherical rigid body wheels.
  6414. */
  6415. class RigidVehicle {
  6416. /**
  6417. * The bodies of the wheels.
  6418. */
  6419. /**
  6420. * The chassis body.
  6421. */
  6422. /**
  6423. * The constraints.
  6424. */
  6425. /**
  6426. * The wheel axes.
  6427. */
  6428. /**
  6429. * The wheel forces.
  6430. */
  6431. constructor(options) {
  6432. if (options === void 0) {
  6433. options = {};
  6434. }
  6435. this.wheelBodies = [];
  6436. this.coordinateSystem = typeof options.coordinateSystem !== 'undefined' ? options.coordinateSystem.clone() : new Vec3(1, 2, 3);
  6437. if (options.chassisBody) {
  6438. this.chassisBody = options.chassisBody;
  6439. } else {
  6440. // No chassis body given. Create it!
  6441. this.chassisBody = new Body({
  6442. mass: 1,
  6443. shape: new Box(new Vec3(5, 0.5, 2))
  6444. });
  6445. }
  6446. this.constraints = [];
  6447. this.wheelAxes = [];
  6448. this.wheelForces = [];
  6449. }
  6450. /**
  6451. * Add a wheel
  6452. */
  6453. addWheel(options) {
  6454. if (options === void 0) {
  6455. options = {};
  6456. }
  6457. let wheelBody;
  6458. if (options.body) {
  6459. wheelBody = options.body;
  6460. } else {
  6461. // No wheel body given. Create it!
  6462. wheelBody = new Body({
  6463. mass: 1,
  6464. shape: new Sphere(1.2)
  6465. });
  6466. }
  6467. this.wheelBodies.push(wheelBody);
  6468. this.wheelForces.push(0); // Position constrain wheels
  6469. const position = typeof options.position !== 'undefined' ? options.position.clone() : new Vec3(); // Set position locally to the chassis
  6470. const worldPosition = new Vec3();
  6471. this.chassisBody.pointToWorldFrame(position, worldPosition);
  6472. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel
  6473. const axis = typeof options.axis !== 'undefined' ? options.axis.clone() : new Vec3(0, 0, 1);
  6474. this.wheelAxes.push(axis);
  6475. const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  6476. pivotA: position,
  6477. axisA: axis,
  6478. pivotB: Vec3.ZERO,
  6479. axisB: axis,
  6480. collideConnected: false
  6481. });
  6482. this.constraints.push(hingeConstraint);
  6483. return this.wheelBodies.length - 1;
  6484. }
  6485. /**
  6486. * Set the steering value of a wheel.
  6487. * @todo check coordinateSystem
  6488. */
  6489. setSteeringValue(value, wheelIndex) {
  6490. // Set angle of the hinge axis
  6491. const axis = this.wheelAxes[wheelIndex];
  6492. const c = Math.cos(value);
  6493. const s = Math.sin(value);
  6494. const x = axis.x;
  6495. const z = axis.z;
  6496. this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z);
  6497. }
  6498. /**
  6499. * Set the target rotational speed of the hinge constraint.
  6500. */
  6501. setMotorSpeed(value, wheelIndex) {
  6502. const hingeConstraint = this.constraints[wheelIndex];
  6503. hingeConstraint.enableMotor();
  6504. hingeConstraint.motorTargetVelocity = value;
  6505. }
  6506. /**
  6507. * Set the target rotational speed of the hinge constraint.
  6508. */
  6509. disableMotor(wheelIndex) {
  6510. const hingeConstraint = this.constraints[wheelIndex];
  6511. hingeConstraint.disableMotor();
  6512. }
  6513. /**
  6514. * Set the wheel force to apply on one of the wheels each time step
  6515. */
  6516. setWheelForce(value, wheelIndex) {
  6517. this.wheelForces[wheelIndex] = value;
  6518. }
  6519. /**
  6520. * Apply a torque on one of the wheels.
  6521. */
  6522. applyWheelForce(value, wheelIndex) {
  6523. const axis = this.wheelAxes[wheelIndex];
  6524. const wheelBody = this.wheelBodies[wheelIndex];
  6525. const bodyTorque = wheelBody.torque;
  6526. axis.scale(value, torque);
  6527. wheelBody.vectorToWorldFrame(torque, torque);
  6528. bodyTorque.vadd(torque, bodyTorque);
  6529. }
  6530. /**
  6531. * Add the vehicle including its constraints to the world.
  6532. */
  6533. addToWorld(world) {
  6534. const constraints = this.constraints;
  6535. const bodies = this.wheelBodies.concat([this.chassisBody]);
  6536. for (let i = 0; i < bodies.length; i++) {
  6537. world.addBody(bodies[i]);
  6538. }
  6539. for (let i = 0; i < constraints.length; i++) {
  6540. world.addConstraint(constraints[i]);
  6541. }
  6542. world.addEventListener('preStep', this._update.bind(this));
  6543. }
  6544. _update() {
  6545. const wheelForces = this.wheelForces;
  6546. for (let i = 0; i < wheelForces.length; i++) {
  6547. this.applyWheelForce(wheelForces[i], i);
  6548. }
  6549. }
  6550. /**
  6551. * Remove the vehicle including its constraints from the world.
  6552. */
  6553. removeFromWorld(world) {
  6554. const constraints = this.constraints;
  6555. const bodies = this.wheelBodies.concat([this.chassisBody]);
  6556. for (let i = 0; i < bodies.length; i++) {
  6557. world.removeBody(bodies[i]);
  6558. }
  6559. for (let i = 0; i < constraints.length; i++) {
  6560. world.removeConstraint(constraints[i]);
  6561. }
  6562. }
  6563. /**
  6564. * Get current rotational velocity of a wheel
  6565. */
  6566. getWheelSpeed(wheelIndex) {
  6567. const axis = this.wheelAxes[wheelIndex];
  6568. const wheelBody = this.wheelBodies[wheelIndex];
  6569. const w = wheelBody.angularVelocity;
  6570. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  6571. return w.dot(worldAxis);
  6572. }
  6573. }
  6574. const torque = new Vec3();
  6575. const worldAxis = new Vec3();
  6576. /**
  6577. * Smoothed-particle hydrodynamics system
  6578. * @todo Make parameters customizable in the constructor
  6579. */
  6580. class SPHSystem {
  6581. /**
  6582. * The particles array.
  6583. */
  6584. /**
  6585. * Density of the system (kg/m3).
  6586. * @default 1
  6587. */
  6588. /**
  6589. * Distance below which two particles are considered to be neighbors.
  6590. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  6591. * @default 1
  6592. */
  6593. /**
  6594. * @default 1
  6595. */
  6596. /**
  6597. * Viscosity of the system.
  6598. * @default 0.01
  6599. */
  6600. /**
  6601. * @default 0.000001
  6602. */
  6603. constructor() {
  6604. this.particles = [];
  6605. this.density = 1;
  6606. this.smoothingRadius = 1;
  6607. this.speedOfSound = 1;
  6608. this.viscosity = 0.01;
  6609. this.eps = 0.000001; // Stuff Computed per particle
  6610. this.pressures = [];
  6611. this.densities = [];
  6612. this.neighbors = [];
  6613. }
  6614. /**
  6615. * Add a particle to the system.
  6616. */
  6617. add(particle) {
  6618. this.particles.push(particle);
  6619. if (this.neighbors.length < this.particles.length) {
  6620. this.neighbors.push([]);
  6621. }
  6622. }
  6623. /**
  6624. * Remove a particle from the system.
  6625. */
  6626. remove(particle) {
  6627. const idx = this.particles.indexOf(particle);
  6628. if (idx !== -1) {
  6629. this.particles.splice(idx, 1);
  6630. if (this.neighbors.length > this.particles.length) {
  6631. this.neighbors.pop();
  6632. }
  6633. }
  6634. }
  6635. /**
  6636. * Get neighbors within smoothing volume, save in the array neighbors
  6637. */
  6638. getNeighbors(particle, neighbors) {
  6639. const N = this.particles.length;
  6640. const id = particle.id;
  6641. const R2 = this.smoothingRadius * this.smoothingRadius;
  6642. const dist = SPHSystem_getNeighbors_dist;
  6643. for (let i = 0; i !== N; i++) {
  6644. const p = this.particles[i];
  6645. p.position.vsub(particle.position, dist);
  6646. if (id !== p.id && dist.lengthSquared() < R2) {
  6647. neighbors.push(p);
  6648. }
  6649. }
  6650. }
  6651. update() {
  6652. const N = this.particles.length;
  6653. const dist = SPHSystem_update_dist;
  6654. const cs = this.speedOfSound;
  6655. const eps = this.eps;
  6656. for (let i = 0; i !== N; i++) {
  6657. const p = this.particles[i]; // Current particle
  6658. const neighbors = this.neighbors[i]; // Get neighbors
  6659. neighbors.length = 0;
  6660. this.getNeighbors(p, neighbors);
  6661. neighbors.push(this.particles[i]); // Add current too
  6662. const numNeighbors = neighbors.length; // Accumulate density for the particle
  6663. let sum = 0.0;
  6664. for (let j = 0; j !== numNeighbors; j++) {
  6665. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  6666. p.position.vsub(neighbors[j].position, dist);
  6667. const len = dist.length();
  6668. const weight = this.w(len);
  6669. sum += neighbors[j].mass * weight;
  6670. } // Save
  6671. this.densities[i] = sum;
  6672. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  6673. } // Add forces
  6674. // Sum to these accelerations
  6675. const a_pressure = SPHSystem_update_a_pressure;
  6676. const a_visc = SPHSystem_update_a_visc;
  6677. const gradW = SPHSystem_update_gradW;
  6678. const r_vec = SPHSystem_update_r_vec;
  6679. const u = SPHSystem_update_u;
  6680. for (let i = 0; i !== N; i++) {
  6681. const particle = this.particles[i];
  6682. a_pressure.set(0, 0, 0);
  6683. a_visc.set(0, 0, 0); // Init vars
  6684. let Pij;
  6685. let nabla;
  6686. const neighbors = this.neighbors[i];
  6687. const numNeighbors = neighbors.length; //printf("Neighbors: ");
  6688. for (let j = 0; j !== numNeighbors; j++) {
  6689. const neighbor = neighbors[j]; //printf("%d ",nj);
  6690. // Get r once for all..
  6691. particle.position.vsub(neighbor.position, r_vec);
  6692. const r = r_vec.length(); // Pressure contribution
  6693. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + this.pressures[j] / (this.densities[j] * this.densities[j] + eps));
  6694. this.gradw(r_vec, gradW); // Add to pressure acceleration
  6695. gradW.scale(Pij, gradW);
  6696. a_pressure.vadd(gradW, a_pressure); // Viscosity contribution
  6697. neighbor.velocity.vsub(particle.velocity, u);
  6698. u.scale(1.0 / (0.0001 + this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass, u);
  6699. nabla = this.nablaw(r);
  6700. u.scale(nabla, u); // Add to viscosity acceleration
  6701. a_visc.vadd(u, a_visc);
  6702. } // Calculate force
  6703. a_visc.scale(particle.mass, a_visc);
  6704. a_pressure.scale(particle.mass, a_pressure); // Add force to particles
  6705. particle.force.vadd(a_visc, particle.force);
  6706. particle.force.vadd(a_pressure, particle.force);
  6707. }
  6708. } // Calculate the weight using the W(r) weightfunction
  6709. w(r) {
  6710. // 315
  6711. const h = this.smoothingRadius;
  6712. return 315.0 / (64.0 * Math.PI * h ** 9) * (h * h - r * r) ** 3;
  6713. } // calculate gradient of the weight function
  6714. gradw(rVec, resultVec) {
  6715. const r = rVec.length();
  6716. const h = this.smoothingRadius;
  6717. rVec.scale(945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) ** 2, resultVec);
  6718. } // Calculate nabla(W)
  6719. nablaw(r) {
  6720. const h = this.smoothingRadius;
  6721. const nabla = 945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) * (7 * r * r - 3 * h * h);
  6722. return nabla;
  6723. }
  6724. }
  6725. const SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation
  6726. const SPHSystem_update_dist = new Vec3(); // Relative velocity
  6727. const SPHSystem_update_a_pressure = new Vec3();
  6728. const SPHSystem_update_a_visc = new Vec3();
  6729. const SPHSystem_update_gradW = new Vec3();
  6730. const SPHSystem_update_r_vec = new Vec3();
  6731. const SPHSystem_update_u = new Vec3();
  6732. /**
  6733. * Cylinder class.
  6734. * @example
  6735. * const radiusTop = 0.5
  6736. * const radiusBottom = 0.5
  6737. * const height = 2
  6738. * const numSegments = 12
  6739. * const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments)
  6740. * const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape })
  6741. * world.addBody(cylinderBody)
  6742. */
  6743. class Cylinder extends ConvexPolyhedron {
  6744. /** The radius of the top of the Cylinder. */
  6745. /** The radius of the bottom of the Cylinder. */
  6746. /** The height of the Cylinder. */
  6747. /** The number of segments to build the cylinder out of. */
  6748. /**
  6749. * @param radiusTop The radius of the top of the Cylinder.
  6750. * @param radiusBottom The radius of the bottom of the Cylinder.
  6751. * @param height The height of the Cylinder.
  6752. * @param numSegments The number of segments to build the cylinder out of.
  6753. */
  6754. constructor(radiusTop, radiusBottom, height, numSegments) {
  6755. if (radiusTop === void 0) {
  6756. radiusTop = 1;
  6757. }
  6758. if (radiusBottom === void 0) {
  6759. radiusBottom = 1;
  6760. }
  6761. if (height === void 0) {
  6762. height = 1;
  6763. }
  6764. if (numSegments === void 0) {
  6765. numSegments = 8;
  6766. }
  6767. if (radiusTop < 0) {
  6768. throw new Error('The cylinder radiusTop cannot be negative.');
  6769. }
  6770. if (radiusBottom < 0) {
  6771. throw new Error('The cylinder radiusBottom cannot be negative.');
  6772. }
  6773. const N = numSegments;
  6774. const vertices = [];
  6775. const axes = [];
  6776. const faces = [];
  6777. const bottomface = [];
  6778. const topface = [];
  6779. const cos = Math.cos;
  6780. const sin = Math.sin; // First bottom point
  6781. vertices.push(new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)));
  6782. bottomface.push(0); // First top point
  6783. vertices.push(new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)));
  6784. topface.push(1);
  6785. for (let i = 0; i < N; i++) {
  6786. const theta = 2 * Math.PI / N * (i + 1);
  6787. const thetaN = 2 * Math.PI / N * (i + 0.5);
  6788. if (i < N - 1) {
  6789. // Bottom
  6790. vertices.push(new Vec3(-radiusBottom * sin(theta), -height * 0.5, radiusBottom * cos(theta)));
  6791. bottomface.push(2 * i + 2); // Top
  6792. vertices.push(new Vec3(-radiusTop * sin(theta), height * 0.5, radiusTop * cos(theta)));
  6793. topface.push(2 * i + 3); // Face
  6794. faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]);
  6795. } else {
  6796. faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect
  6797. } // Axis: we can cut off half of them if we have even number of segments
  6798. if (N % 2 === 1 || i < N / 2) {
  6799. axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN)));
  6800. }
  6801. }
  6802. faces.push(bottomface);
  6803. axes.push(new Vec3(0, 1, 0)); // Reorder top face
  6804. const temp = [];
  6805. for (let i = 0; i < topface.length; i++) {
  6806. temp.push(topface[topface.length - i - 1]);
  6807. }
  6808. faces.push(temp);
  6809. super({
  6810. vertices,
  6811. faces,
  6812. axes
  6813. });
  6814. this.type = Shape.types.CYLINDER;
  6815. this.radiusTop = radiusTop;
  6816. this.radiusBottom = radiusBottom;
  6817. this.height = height;
  6818. this.numSegments = numSegments;
  6819. }
  6820. }
  6821. /**
  6822. * Particle shape.
  6823. * @example
  6824. * const particleShape = new CANNON.Particle()
  6825. * const particleBody = new CANNON.Body({ mass: 1, shape: particleShape })
  6826. * world.addBody(particleBody)
  6827. */
  6828. class Particle extends Shape {
  6829. constructor() {
  6830. super({
  6831. type: Shape.types.PARTICLE
  6832. });
  6833. }
  6834. /**
  6835. * calculateLocalInertia
  6836. */
  6837. calculateLocalInertia(mass, target) {
  6838. if (target === void 0) {
  6839. target = new Vec3();
  6840. }
  6841. target.set(0, 0, 0);
  6842. return target;
  6843. }
  6844. volume() {
  6845. return 0;
  6846. }
  6847. updateBoundingSphereRadius() {
  6848. this.boundingSphereRadius = 0;
  6849. }
  6850. calculateWorldAABB(pos, quat, min, max) {
  6851. // Get each axis max
  6852. min.copy(pos);
  6853. max.copy(pos);
  6854. }
  6855. }
  6856. /**
  6857. * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos.
  6858. * @example
  6859. * const planeShape = new CANNON.Plane()
  6860. * const planeBody = new CANNON.Body({ mass: 0, shape: planeShape })
  6861. * planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up
  6862. * world.addBody(planeBody)
  6863. */
  6864. class Plane extends Shape {
  6865. /** worldNormal */
  6866. /** worldNormalNeedsUpdate */
  6867. constructor() {
  6868. super({
  6869. type: Shape.types.PLANE
  6870. }); // World oriented normal
  6871. this.worldNormal = new Vec3();
  6872. this.worldNormalNeedsUpdate = true;
  6873. this.boundingSphereRadius = Number.MAX_VALUE;
  6874. }
  6875. /** computeWorldNormal */
  6876. computeWorldNormal(quat) {
  6877. const n = this.worldNormal;
  6878. n.set(0, 0, 1);
  6879. quat.vmult(n, n);
  6880. this.worldNormalNeedsUpdate = false;
  6881. }
  6882. calculateLocalInertia(mass, target) {
  6883. if (target === void 0) {
  6884. target = new Vec3();
  6885. }
  6886. return target;
  6887. }
  6888. volume() {
  6889. return (// The plane is infinite...
  6890. Number.MAX_VALUE
  6891. );
  6892. }
  6893. calculateWorldAABB(pos, quat, min, max) {
  6894. // The plane AABB is infinite, except if the normal is pointing along any axis
  6895. tempNormal.set(0, 0, 1); // Default plane normal is z
  6896. quat.vmult(tempNormal, tempNormal);
  6897. const maxVal = Number.MAX_VALUE;
  6898. min.set(-maxVal, -maxVal, -maxVal);
  6899. max.set(maxVal, maxVal, maxVal);
  6900. if (tempNormal.x === 1) {
  6901. max.x = pos.x;
  6902. } else if (tempNormal.x === -1) {
  6903. min.x = pos.x;
  6904. }
  6905. if (tempNormal.y === 1) {
  6906. max.y = pos.y;
  6907. } else if (tempNormal.y === -1) {
  6908. min.y = pos.y;
  6909. }
  6910. if (tempNormal.z === 1) {
  6911. max.z = pos.z;
  6912. } else if (tempNormal.z === -1) {
  6913. min.z = pos.z;
  6914. }
  6915. }
  6916. updateBoundingSphereRadius() {
  6917. this.boundingSphereRadius = Number.MAX_VALUE;
  6918. }
  6919. }
  6920. const tempNormal = new Vec3();
  6921. /**
  6922. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  6923. * @todo Should be possible to use along all axes, not just y
  6924. * @todo should be possible to scale along all axes
  6925. * @todo Refactor elementSize to elementSizeX and elementSizeY
  6926. *
  6927. * @example
  6928. * // Generate some height data (y-values).
  6929. * const data = []
  6930. * for (let i = 0; i < 1000; i++) {
  6931. * const y = 0.5 * Math.cos(0.2 * i)
  6932. * data.push(y)
  6933. * }
  6934. *
  6935. * // Create the heightfield shape
  6936. * const heightfieldShape = new CANNON.Heightfield(data, {
  6937. * elementSize: 1 // Distance between the data points in X and Y directions
  6938. * })
  6939. * const heightfieldBody = new CANNON.Body({ shape: heightfieldShape })
  6940. * world.addBody(heightfieldBody)
  6941. */
  6942. class Heightfield extends Shape {
  6943. /**
  6944. * An array of numbers, or height values, that are spread out along the x axis.
  6945. */
  6946. /**
  6947. * Max value of the data points in the data array.
  6948. */
  6949. /**
  6950. * Minimum value of the data points in the data array.
  6951. */
  6952. /**
  6953. * World spacing between the data points in X and Y direction.
  6954. * @todo elementSizeX and Y
  6955. * @default 1
  6956. */
  6957. /**
  6958. * @default true
  6959. */
  6960. /**
  6961. * @param data An array of numbers, or height values, that are spread out along the x axis.
  6962. */
  6963. constructor(data, options) {
  6964. if (options === void 0) {
  6965. options = {};
  6966. }
  6967. options = Utils.defaults(options, {
  6968. maxValue: null,
  6969. minValue: null,
  6970. elementSize: 1
  6971. });
  6972. super({
  6973. type: Shape.types.HEIGHTFIELD
  6974. });
  6975. this.data = data;
  6976. this.maxValue = options.maxValue;
  6977. this.minValue = options.minValue;
  6978. this.elementSize = options.elementSize;
  6979. if (options.minValue === null) {
  6980. this.updateMinValue();
  6981. }
  6982. if (options.maxValue === null) {
  6983. this.updateMaxValue();
  6984. }
  6985. this.cacheEnabled = true;
  6986. this.pillarConvex = new ConvexPolyhedron();
  6987. this.pillarOffset = new Vec3();
  6988. this.updateBoundingSphereRadius(); // "i_j_isUpper" => { convex: ..., offset: ... }
  6989. // for example:
  6990. // _cachedPillars["0_2_1"]
  6991. this._cachedPillars = {};
  6992. }
  6993. /**
  6994. * Call whenever you change the data array.
  6995. */
  6996. update() {
  6997. this._cachedPillars = {};
  6998. }
  6999. /**
  7000. * Update the `minValue` property
  7001. */
  7002. updateMinValue() {
  7003. const data = this.data;
  7004. let minValue = data[0][0];
  7005. for (let i = 0; i !== data.length; i++) {
  7006. for (let j = 0; j !== data[i].length; j++) {
  7007. const v = data[i][j];
  7008. if (v < minValue) {
  7009. minValue = v;
  7010. }
  7011. }
  7012. }
  7013. this.minValue = minValue;
  7014. }
  7015. /**
  7016. * Update the `maxValue` property
  7017. */
  7018. updateMaxValue() {
  7019. const data = this.data;
  7020. let maxValue = data[0][0];
  7021. for (let i = 0; i !== data.length; i++) {
  7022. for (let j = 0; j !== data[i].length; j++) {
  7023. const v = data[i][j];
  7024. if (v > maxValue) {
  7025. maxValue = v;
  7026. }
  7027. }
  7028. }
  7029. this.maxValue = maxValue;
  7030. }
  7031. /**
  7032. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  7033. */
  7034. setHeightValueAtIndex(xi, yi, value) {
  7035. const data = this.data;
  7036. data[xi][yi] = value; // Invalidate cache
  7037. this.clearCachedConvexTrianglePillar(xi, yi, false);
  7038. if (xi > 0) {
  7039. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  7040. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  7041. }
  7042. if (yi > 0) {
  7043. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  7044. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  7045. }
  7046. if (yi > 0 && xi > 0) {
  7047. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  7048. }
  7049. }
  7050. /**
  7051. * Get max/min in a rectangle in the matrix data
  7052. * @param result An array to store the results in.
  7053. * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  7054. */
  7055. getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result) {
  7056. if (result === void 0) {
  7057. result = [];
  7058. }
  7059. // Get max and min of the data
  7060. const data = this.data; // Set first value
  7061. let max = this.minValue;
  7062. for (let i = iMinX; i <= iMaxX; i++) {
  7063. for (let j = iMinY; j <= iMaxY; j++) {
  7064. const height = data[i][j];
  7065. if (height > max) {
  7066. max = height;
  7067. }
  7068. }
  7069. }
  7070. result[0] = this.minValue;
  7071. result[1] = max;
  7072. }
  7073. /**
  7074. * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
  7075. * @param result Two-element array
  7076. * @param clamp If the position should be clamped to the heightfield edge.
  7077. */
  7078. getIndexOfPosition(x, y, result, clamp) {
  7079. // Get the index of the data points to test against
  7080. const w = this.elementSize;
  7081. const data = this.data;
  7082. let xi = Math.floor(x / w);
  7083. let yi = Math.floor(y / w);
  7084. result[0] = xi;
  7085. result[1] = yi;
  7086. if (clamp) {
  7087. // Clamp index to edges
  7088. if (xi < 0) {
  7089. xi = 0;
  7090. }
  7091. if (yi < 0) {
  7092. yi = 0;
  7093. }
  7094. if (xi >= data.length - 1) {
  7095. xi = data.length - 1;
  7096. }
  7097. if (yi >= data[0].length - 1) {
  7098. yi = data[0].length - 1;
  7099. }
  7100. } // Bail out if we are out of the terrain
  7101. if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) {
  7102. return false;
  7103. }
  7104. return true;
  7105. }
  7106. getTriangleAt(x, y, edgeClamp, a, b, c) {
  7107. const idx = getHeightAt_idx;
  7108. this.getIndexOfPosition(x, y, idx, edgeClamp);
  7109. let xi = idx[0];
  7110. let yi = idx[1];
  7111. const data = this.data;
  7112. if (edgeClamp) {
  7113. xi = Math.min(data.length - 2, Math.max(0, xi));
  7114. yi = Math.min(data[0].length - 2, Math.max(0, yi));
  7115. }
  7116. const elementSize = this.elementSize;
  7117. const lowerDist2 = (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2;
  7118. const upperDist2 = (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2;
  7119. const upper = lowerDist2 > upperDist2;
  7120. this.getTriangle(xi, yi, upper, a, b, c);
  7121. return upper;
  7122. }
  7123. getNormalAt(x, y, edgeClamp, result) {
  7124. const a = getNormalAt_a;
  7125. const b = getNormalAt_b;
  7126. const c = getNormalAt_c;
  7127. const e0 = getNormalAt_e0;
  7128. const e1 = getNormalAt_e1;
  7129. this.getTriangleAt(x, y, edgeClamp, a, b, c);
  7130. b.vsub(a, e0);
  7131. c.vsub(a, e1);
  7132. e0.cross(e1, result);
  7133. result.normalize();
  7134. }
  7135. /**
  7136. * Get an AABB of a square in the heightfield
  7137. * @param xi
  7138. * @param yi
  7139. * @param result
  7140. */
  7141. getAabbAtIndex(xi, yi, _ref) {
  7142. let {
  7143. lowerBound,
  7144. upperBound
  7145. } = _ref;
  7146. const data = this.data;
  7147. const elementSize = this.elementSize;
  7148. lowerBound.set(xi * elementSize, yi * elementSize, data[xi][yi]);
  7149. upperBound.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);
  7150. }
  7151. /**
  7152. * Get the height in the heightfield at a given position
  7153. */
  7154. getHeightAt(x, y, edgeClamp) {
  7155. const data = this.data;
  7156. const a = getHeightAt_a;
  7157. const b = getHeightAt_b;
  7158. const c = getHeightAt_c;
  7159. const idx = getHeightAt_idx;
  7160. this.getIndexOfPosition(x, y, idx, edgeClamp);
  7161. let xi = idx[0];
  7162. let yi = idx[1];
  7163. if (edgeClamp) {
  7164. xi = Math.min(data.length - 2, Math.max(0, xi));
  7165. yi = Math.min(data[0].length - 2, Math.max(0, yi));
  7166. }
  7167. const upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);
  7168. barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);
  7169. const w = getHeightAt_weights;
  7170. if (upper) {
  7171. // Top triangle verts
  7172. return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;
  7173. } else {
  7174. // Top triangle verts
  7175. return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;
  7176. }
  7177. }
  7178. getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) {
  7179. return `${xi}_${yi}_${getUpperTriangle ? 1 : 0}`;
  7180. }
  7181. getCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7182. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  7183. }
  7184. setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, convex, offset) {
  7185. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  7186. convex,
  7187. offset
  7188. };
  7189. }
  7190. clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7191. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  7192. }
  7193. /**
  7194. * Get a triangle from the heightfield
  7195. */
  7196. getTriangle(xi, yi, upper, a, b, c) {
  7197. const data = this.data;
  7198. const elementSize = this.elementSize;
  7199. if (upper) {
  7200. // Top triangle verts
  7201. a.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);
  7202. b.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);
  7203. c.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);
  7204. } else {
  7205. // Top triangle verts
  7206. a.set(xi * elementSize, yi * elementSize, data[xi][yi]);
  7207. b.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);
  7208. c.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);
  7209. }
  7210. }
  7211. /**
  7212. * Get a triangle in the terrain in the form of a triangular convex shape.
  7213. */
  7214. getConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7215. let result = this.pillarConvex;
  7216. let offsetResult = this.pillarOffset;
  7217. if (this.cacheEnabled) {
  7218. const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  7219. if (data) {
  7220. this.pillarConvex = data.convex;
  7221. this.pillarOffset = data.offset;
  7222. return;
  7223. }
  7224. result = new ConvexPolyhedron();
  7225. offsetResult = new Vec3();
  7226. this.pillarConvex = result;
  7227. this.pillarOffset = offsetResult;
  7228. }
  7229. const data = this.data;
  7230. const elementSize = this.elementSize;
  7231. const faces = result.faces; // Reuse verts if possible
  7232. result.vertices.length = 6;
  7233. for (let i = 0; i < 6; i++) {
  7234. if (!result.vertices[i]) {
  7235. result.vertices[i] = new Vec3();
  7236. }
  7237. } // Reuse faces if possible
  7238. faces.length = 5;
  7239. for (let i = 0; i < 5; i++) {
  7240. if (!faces[i]) {
  7241. faces[i] = [];
  7242. }
  7243. }
  7244. const verts = result.vertices;
  7245. const h = (Math.min(data[xi][yi], data[xi + 1][yi], data[xi][yi + 1], data[xi + 1][yi + 1]) - this.minValue) / 2 + this.minValue;
  7246. if (!getUpperTriangle) {
  7247. // Center of the triangle pillar - all polygons are given relative to this one
  7248. offsetResult.set((xi + 0.25) * elementSize, // sort of center of a triangle
  7249. (yi + 0.25) * elementSize, h // vertical center
  7250. ); // Top triangle verts
  7251. verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h);
  7252. verts[1].set(0.75 * elementSize, -0.25 * elementSize, data[xi + 1][yi] - h);
  7253. verts[2].set(-0.25 * elementSize, 0.75 * elementSize, data[xi][yi + 1] - h); // bottom triangle verts
  7254. verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
  7255. verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
  7256. verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle
  7257. faces[0][0] = 0;
  7258. faces[0][1] = 1;
  7259. faces[0][2] = 2; // bottom triangle
  7260. faces[1][0] = 5;
  7261. faces[1][1] = 4;
  7262. faces[1][2] = 3; // -x facing quad
  7263. faces[2][0] = 0;
  7264. faces[2][1] = 2;
  7265. faces[2][2] = 5;
  7266. faces[2][3] = 3; // -y facing quad
  7267. faces[3][0] = 1;
  7268. faces[3][1] = 0;
  7269. faces[3][2] = 3;
  7270. faces[3][3] = 4; // +xy facing quad
  7271. faces[4][0] = 4;
  7272. faces[4][1] = 5;
  7273. faces[4][2] = 2;
  7274. faces[4][3] = 1;
  7275. } else {
  7276. // Center of the triangle pillar - all polygons are given relative to this one
  7277. offsetResult.set((xi + 0.75) * elementSize, // sort of center of a triangle
  7278. (yi + 0.75) * elementSize, h // vertical center
  7279. ); // Top triangle verts
  7280. verts[0].set(0.25 * elementSize, 0.25 * elementSize, data[xi + 1][yi + 1] - h);
  7281. verts[1].set(-0.75 * elementSize, 0.25 * elementSize, data[xi][yi + 1] - h);
  7282. verts[2].set(0.25 * elementSize, -0.75 * elementSize, data[xi + 1][yi] - h); // bottom triangle verts
  7283. verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
  7284. verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
  7285. verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle
  7286. faces[0][0] = 0;
  7287. faces[0][1] = 1;
  7288. faces[0][2] = 2; // bottom triangle
  7289. faces[1][0] = 5;
  7290. faces[1][1] = 4;
  7291. faces[1][2] = 3; // +x facing quad
  7292. faces[2][0] = 2;
  7293. faces[2][1] = 5;
  7294. faces[2][2] = 3;
  7295. faces[2][3] = 0; // +y facing quad
  7296. faces[3][0] = 3;
  7297. faces[3][1] = 4;
  7298. faces[3][2] = 1;
  7299. faces[3][3] = 0; // -xy facing quad
  7300. faces[4][0] = 1;
  7301. faces[4][1] = 4;
  7302. faces[4][2] = 5;
  7303. faces[4][3] = 2;
  7304. }
  7305. result.computeNormals();
  7306. result.computeEdges();
  7307. result.updateBoundingSphereRadius();
  7308. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  7309. }
  7310. calculateLocalInertia(mass, target) {
  7311. if (target === void 0) {
  7312. target = new Vec3();
  7313. }
  7314. target.set(0, 0, 0);
  7315. return target;
  7316. }
  7317. volume() {
  7318. return (// The terrain is infinite
  7319. Number.MAX_VALUE
  7320. );
  7321. }
  7322. calculateWorldAABB(pos, quat, min, max) {
  7323. /** @TODO do it properly */
  7324. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7325. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7326. }
  7327. updateBoundingSphereRadius() {
  7328. // Use the bounding box of the min/max values
  7329. const data = this.data;
  7330. const s = this.elementSize;
  7331. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).length();
  7332. }
  7333. /**
  7334. * Sets the height values from an image. Currently only supported in browser.
  7335. */
  7336. setHeightsFromImage(image, scale) {
  7337. const {
  7338. x,
  7339. z,
  7340. y
  7341. } = scale;
  7342. const canvas = document.createElement('canvas');
  7343. canvas.width = image.width;
  7344. canvas.height = image.height;
  7345. const context = canvas.getContext('2d');
  7346. context.drawImage(image, 0, 0);
  7347. const imageData = context.getImageData(0, 0, image.width, image.height);
  7348. const matrix = this.data;
  7349. matrix.length = 0;
  7350. this.elementSize = Math.abs(x) / imageData.width;
  7351. for (let i = 0; i < imageData.height; i++) {
  7352. const row = [];
  7353. for (let j = 0; j < imageData.width; j++) {
  7354. const a = imageData.data[(i * imageData.height + j) * 4];
  7355. const b = imageData.data[(i * imageData.height + j) * 4 + 1];
  7356. const c = imageData.data[(i * imageData.height + j) * 4 + 2];
  7357. const height = (a + b + c) / 4 / 255 * z;
  7358. if (x < 0) {
  7359. row.push(height);
  7360. } else {
  7361. row.unshift(height);
  7362. }
  7363. }
  7364. if (y < 0) {
  7365. matrix.unshift(row);
  7366. } else {
  7367. matrix.push(row);
  7368. }
  7369. }
  7370. this.updateMaxValue();
  7371. this.updateMinValue();
  7372. this.update();
  7373. }
  7374. }
  7375. const getHeightAt_idx = [];
  7376. const getHeightAt_weights = new Vec3();
  7377. const getHeightAt_a = new Vec3();
  7378. const getHeightAt_b = new Vec3();
  7379. const getHeightAt_c = new Vec3();
  7380. const getNormalAt_a = new Vec3();
  7381. const getNormalAt_b = new Vec3();
  7382. const getNormalAt_c = new Vec3();
  7383. const getNormalAt_e0 = new Vec3();
  7384. const getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system
  7385. function barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result) {
  7386. result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
  7387. result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
  7388. result.z = 1 - result.x - result.y;
  7389. }
  7390. /**
  7391. * OctreeNode
  7392. */
  7393. class OctreeNode {
  7394. /** The root node */
  7395. /** Boundary of this node */
  7396. /** Contained data at the current node level */
  7397. /** Children to this node */
  7398. constructor(options) {
  7399. if (options === void 0) {
  7400. options = {};
  7401. }
  7402. this.root = options.root || null;
  7403. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  7404. this.data = [];
  7405. this.children = [];
  7406. }
  7407. /**
  7408. * reset
  7409. */
  7410. reset() {
  7411. this.children.length = this.data.length = 0;
  7412. }
  7413. /**
  7414. * Insert data into this node
  7415. * @return True if successful, otherwise false
  7416. */
  7417. insert(aabb, elementData, level) {
  7418. if (level === void 0) {
  7419. level = 0;
  7420. }
  7421. const nodeData = this.data; // Ignore objects that do not belong in this node
  7422. if (!this.aabb.contains(aabb)) {
  7423. return false; // object cannot be added
  7424. }
  7425. const children = this.children;
  7426. const maxDepth = this.maxDepth || this.root.maxDepth;
  7427. if (level < maxDepth) {
  7428. // Subdivide if there are no children yet
  7429. let subdivided = false;
  7430. if (!children.length) {
  7431. this.subdivide();
  7432. subdivided = true;
  7433. } // add to whichever node will accept it
  7434. for (let i = 0; i !== 8; i++) {
  7435. if (children[i].insert(aabb, elementData, level + 1)) {
  7436. return true;
  7437. }
  7438. }
  7439. if (subdivided) {
  7440. // No children accepted! Might as well just remove em since they contain none
  7441. children.length = 0;
  7442. }
  7443. } // Too deep, or children didnt want it. add it in current node
  7444. nodeData.push(elementData);
  7445. return true;
  7446. }
  7447. /**
  7448. * Create 8 equally sized children nodes and put them in the `children` array.
  7449. */
  7450. subdivide() {
  7451. const aabb = this.aabb;
  7452. const l = aabb.lowerBound;
  7453. const u = aabb.upperBound;
  7454. const children = this.children;
  7455. children.push(new OctreeNode({
  7456. aabb: new AABB({
  7457. lowerBound: new Vec3(0, 0, 0)
  7458. })
  7459. }), new OctreeNode({
  7460. aabb: new AABB({
  7461. lowerBound: new Vec3(1, 0, 0)
  7462. })
  7463. }), new OctreeNode({
  7464. aabb: new AABB({
  7465. lowerBound: new Vec3(1, 1, 0)
  7466. })
  7467. }), new OctreeNode({
  7468. aabb: new AABB({
  7469. lowerBound: new Vec3(1, 1, 1)
  7470. })
  7471. }), new OctreeNode({
  7472. aabb: new AABB({
  7473. lowerBound: new Vec3(0, 1, 1)
  7474. })
  7475. }), new OctreeNode({
  7476. aabb: new AABB({
  7477. lowerBound: new Vec3(0, 0, 1)
  7478. })
  7479. }), new OctreeNode({
  7480. aabb: new AABB({
  7481. lowerBound: new Vec3(1, 0, 1)
  7482. })
  7483. }), new OctreeNode({
  7484. aabb: new AABB({
  7485. lowerBound: new Vec3(0, 1, 0)
  7486. })
  7487. }));
  7488. u.vsub(l, halfDiagonal);
  7489. halfDiagonal.scale(0.5, halfDiagonal);
  7490. const root = this.root || this;
  7491. for (let i = 0; i !== 8; i++) {
  7492. const child = children[i]; // Set current node as root
  7493. child.root = root; // Compute bounds
  7494. const lowerBound = child.aabb.lowerBound;
  7495. lowerBound.x *= halfDiagonal.x;
  7496. lowerBound.y *= halfDiagonal.y;
  7497. lowerBound.z *= halfDiagonal.z;
  7498. lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal
  7499. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  7500. }
  7501. }
  7502. /**
  7503. * Get all data, potentially within an AABB
  7504. * @return The "result" object
  7505. */
  7506. aabbQuery(aabb, result) {
  7507. this.data; // abort if the range does not intersect this node
  7508. // if (!this.aabb.overlaps(aabb)){
  7509. // return result;
  7510. // }
  7511. // Add objects at this level
  7512. // Array.prototype.push.apply(result, nodeData);
  7513. // Add child data
  7514. // @todo unwrap recursion into a queue / loop, that's faster in JS
  7515. this.children; // for (let i = 0, N = this.children.length; i !== N; i++) {
  7516. // children[i].aabbQuery(aabb, result);
  7517. // }
  7518. const queue = [this];
  7519. while (queue.length) {
  7520. const node = queue.pop();
  7521. if (node.aabb.overlaps(aabb)) {
  7522. Array.prototype.push.apply(result, node.data);
  7523. }
  7524. Array.prototype.push.apply(queue, node.children);
  7525. }
  7526. return result;
  7527. }
  7528. /**
  7529. * Get all data, potentially intersected by a ray.
  7530. * @return The "result" object
  7531. */
  7532. rayQuery(ray, treeTransform, result) {
  7533. // Use aabb query for now.
  7534. /** @todo implement real ray query which needs less lookups */
  7535. ray.getAABB(tmpAABB);
  7536. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  7537. this.aabbQuery(tmpAABB, result);
  7538. return result;
  7539. }
  7540. /**
  7541. * removeEmptyNodes
  7542. */
  7543. removeEmptyNodes() {
  7544. for (let i = this.children.length - 1; i >= 0; i--) {
  7545. this.children[i].removeEmptyNodes();
  7546. if (!this.children[i].children.length && !this.children[i].data.length) {
  7547. this.children.splice(i, 1);
  7548. }
  7549. }
  7550. }
  7551. }
  7552. /**
  7553. * Octree
  7554. */
  7555. class Octree extends OctreeNode {
  7556. /**
  7557. * Maximum subdivision depth
  7558. * @default 8
  7559. */
  7560. /**
  7561. * @param aabb The total AABB of the tree
  7562. */
  7563. constructor(aabb, options) {
  7564. if (options === void 0) {
  7565. options = {};
  7566. }
  7567. super({
  7568. root: null,
  7569. aabb
  7570. });
  7571. this.maxDepth = typeof options.maxDepth !== 'undefined' ? options.maxDepth : 8;
  7572. }
  7573. }
  7574. const halfDiagonal = new Vec3();
  7575. const tmpAABB = new AABB();
  7576. /**
  7577. * Trimesh.
  7578. * @example
  7579. * // How to make a mesh with a single triangle
  7580. * const vertices = [
  7581. * 0, 0, 0, // vertex 0
  7582. * 1, 0, 0, // vertex 1
  7583. * 0, 1, 0 // vertex 2
  7584. * ]
  7585. * const indices = [
  7586. * 0, 1, 2 // triangle 0
  7587. * ]
  7588. * const trimeshShape = new CANNON.Trimesh(vertices, indices)
  7589. */
  7590. class Trimesh extends Shape {
  7591. /**
  7592. * vertices
  7593. */
  7594. /**
  7595. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  7596. */
  7597. /**
  7598. * The normals data.
  7599. */
  7600. /**
  7601. * The local AABB of the mesh.
  7602. */
  7603. /**
  7604. * References to vertex pairs, making up all unique edges in the trimesh.
  7605. */
  7606. /**
  7607. * Local scaling of the mesh. Use .setScale() to set it.
  7608. */
  7609. /**
  7610. * The indexed triangles. Use .updateTree() to update it.
  7611. */
  7612. constructor(vertices, indices) {
  7613. super({
  7614. type: Shape.types.TRIMESH
  7615. });
  7616. this.vertices = new Float32Array(vertices);
  7617. this.indices = new Int16Array(indices);
  7618. this.normals = new Float32Array(indices.length);
  7619. this.aabb = new AABB();
  7620. this.edges = null;
  7621. this.scale = new Vec3(1, 1, 1);
  7622. this.tree = new Octree();
  7623. this.updateEdges();
  7624. this.updateNormals();
  7625. this.updateAABB();
  7626. this.updateBoundingSphereRadius();
  7627. this.updateTree();
  7628. }
  7629. /**
  7630. * updateTree
  7631. */
  7632. updateTree() {
  7633. const tree = this.tree;
  7634. tree.reset();
  7635. tree.aabb.copy(this.aabb);
  7636. const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  7637. tree.aabb.lowerBound.x *= 1 / scale.x;
  7638. tree.aabb.lowerBound.y *= 1 / scale.y;
  7639. tree.aabb.lowerBound.z *= 1 / scale.z;
  7640. tree.aabb.upperBound.x *= 1 / scale.x;
  7641. tree.aabb.upperBound.y *= 1 / scale.y;
  7642. tree.aabb.upperBound.z *= 1 / scale.z; // Insert all triangles
  7643. const triangleAABB = new AABB();
  7644. const a = new Vec3();
  7645. const b = new Vec3();
  7646. const c = new Vec3();
  7647. const points = [a, b, c];
  7648. for (let i = 0; i < this.indices.length / 3; i++) {
  7649. //this.getTriangleVertices(i, a, b, c);
  7650. // Get unscaled triangle verts
  7651. const i3 = i * 3;
  7652. this._getUnscaledVertex(this.indices[i3], a);
  7653. this._getUnscaledVertex(this.indices[i3 + 1], b);
  7654. this._getUnscaledVertex(this.indices[i3 + 2], c);
  7655. triangleAABB.setFromPoints(points);
  7656. tree.insert(triangleAABB, i);
  7657. }
  7658. tree.removeEmptyNodes();
  7659. }
  7660. /**
  7661. * Get triangles in a local AABB from the trimesh.
  7662. * @param result An array of integers, referencing the queried triangles.
  7663. */
  7664. getTrianglesInAABB(aabb, result) {
  7665. unscaledAABB.copy(aabb); // Scale it to local
  7666. const scale = this.scale;
  7667. const isx = scale.x;
  7668. const isy = scale.y;
  7669. const isz = scale.z;
  7670. const l = unscaledAABB.lowerBound;
  7671. const u = unscaledAABB.upperBound;
  7672. l.x /= isx;
  7673. l.y /= isy;
  7674. l.z /= isz;
  7675. u.x /= isx;
  7676. u.y /= isy;
  7677. u.z /= isz;
  7678. return this.tree.aabbQuery(unscaledAABB, result);
  7679. }
  7680. /**
  7681. * setScale
  7682. */
  7683. setScale(scale) {
  7684. const wasUniform = this.scale.x === this.scale.y && this.scale.y === this.scale.z;
  7685. const isUniform = scale.x === scale.y && scale.y === scale.z;
  7686. if (!(wasUniform && isUniform)) {
  7687. // Non-uniform scaling. Need to update normals.
  7688. this.updateNormals();
  7689. }
  7690. this.scale.copy(scale);
  7691. this.updateAABB();
  7692. this.updateBoundingSphereRadius();
  7693. }
  7694. /**
  7695. * Compute the normals of the faces. Will save in the `.normals` array.
  7696. */
  7697. updateNormals() {
  7698. const n = computeNormals_n; // Generate normals
  7699. const normals = this.normals;
  7700. for (let i = 0; i < this.indices.length / 3; i++) {
  7701. const i3 = i * 3;
  7702. const a = this.indices[i3];
  7703. const b = this.indices[i3 + 1];
  7704. const c = this.indices[i3 + 2];
  7705. this.getVertex(a, va);
  7706. this.getVertex(b, vb);
  7707. this.getVertex(c, vc);
  7708. Trimesh.computeNormal(vb, va, vc, n);
  7709. normals[i3] = n.x;
  7710. normals[i3 + 1] = n.y;
  7711. normals[i3 + 2] = n.z;
  7712. }
  7713. }
  7714. /**
  7715. * Update the `.edges` property
  7716. */
  7717. updateEdges() {
  7718. const edges = {};
  7719. const add = (a, b) => {
  7720. const key = a < b ? `${a}_${b}` : `${b}_${a}`;
  7721. edges[key] = true;
  7722. };
  7723. for (let i = 0; i < this.indices.length / 3; i++) {
  7724. const i3 = i * 3;
  7725. const a = this.indices[i3];
  7726. const b = this.indices[i3 + 1];
  7727. const c = this.indices[i3 + 2];
  7728. add(a, b);
  7729. add(b, c);
  7730. add(c, a);
  7731. }
  7732. const keys = Object.keys(edges);
  7733. this.edges = new Int16Array(keys.length * 2);
  7734. for (let i = 0; i < keys.length; i++) {
  7735. const indices = keys[i].split('_');
  7736. this.edges[2 * i] = parseInt(indices[0], 10);
  7737. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  7738. }
  7739. }
  7740. /**
  7741. * Get an edge vertex
  7742. * @param firstOrSecond 0 or 1, depending on which one of the vertices you need.
  7743. * @param vertexStore Where to store the result
  7744. */
  7745. getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) {
  7746. const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  7747. this.getVertex(vertexIndex, vertexStore);
  7748. }
  7749. /**
  7750. * Get a vector along an edge.
  7751. */
  7752. getEdgeVector(edgeIndex, vectorStore) {
  7753. const va = getEdgeVector_va;
  7754. const vb = getEdgeVector_vb;
  7755. this.getEdgeVertex(edgeIndex, 0, va);
  7756. this.getEdgeVertex(edgeIndex, 1, vb);
  7757. vb.vsub(va, vectorStore);
  7758. }
  7759. /**
  7760. * Get face normal given 3 vertices
  7761. */
  7762. static computeNormal(va, vb, vc, target) {
  7763. vb.vsub(va, ab);
  7764. vc.vsub(vb, cb);
  7765. cb.cross(ab, target);
  7766. if (!target.isZero()) {
  7767. target.normalize();
  7768. }
  7769. }
  7770. /**
  7771. * Get vertex i.
  7772. * @return The "out" vector object
  7773. */
  7774. getVertex(i, out) {
  7775. const scale = this.scale;
  7776. this._getUnscaledVertex(i, out);
  7777. out.x *= scale.x;
  7778. out.y *= scale.y;
  7779. out.z *= scale.z;
  7780. return out;
  7781. }
  7782. /**
  7783. * Get raw vertex i
  7784. * @return The "out" vector object
  7785. */
  7786. _getUnscaledVertex(i, out) {
  7787. const i3 = i * 3;
  7788. const vertices = this.vertices;
  7789. return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]);
  7790. }
  7791. /**
  7792. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  7793. * @return The "out" vector object
  7794. */
  7795. getWorldVertex(i, pos, quat, out) {
  7796. this.getVertex(i, out);
  7797. Transform.pointToWorldFrame(pos, quat, out, out);
  7798. return out;
  7799. }
  7800. /**
  7801. * Get the three vertices for triangle i.
  7802. */
  7803. getTriangleVertices(i, a, b, c) {
  7804. const i3 = i * 3;
  7805. this.getVertex(this.indices[i3], a);
  7806. this.getVertex(this.indices[i3 + 1], b);
  7807. this.getVertex(this.indices[i3 + 2], c);
  7808. }
  7809. /**
  7810. * Compute the normal of triangle i.
  7811. * @return The "target" vector object
  7812. */
  7813. getNormal(i, target) {
  7814. const i3 = i * 3;
  7815. return target.set(this.normals[i3], this.normals[i3 + 1], this.normals[i3 + 2]);
  7816. }
  7817. /**
  7818. * @return The "target" vector object
  7819. */
  7820. calculateLocalInertia(mass, target) {
  7821. // Approximate with box inertia
  7822. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  7823. this.computeLocalAABB(cli_aabb);
  7824. const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x;
  7825. const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y;
  7826. const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  7827. return target.set(1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x));
  7828. }
  7829. /**
  7830. * Compute the local AABB for the trimesh
  7831. */
  7832. computeLocalAABB(aabb) {
  7833. const l = aabb.lowerBound;
  7834. const u = aabb.upperBound;
  7835. const n = this.vertices.length;
  7836. this.vertices;
  7837. const v = computeLocalAABB_worldVert;
  7838. this.getVertex(0, v);
  7839. l.copy(v);
  7840. u.copy(v);
  7841. for (let i = 0; i !== n; i++) {
  7842. this.getVertex(i, v);
  7843. if (v.x < l.x) {
  7844. l.x = v.x;
  7845. } else if (v.x > u.x) {
  7846. u.x = v.x;
  7847. }
  7848. if (v.y < l.y) {
  7849. l.y = v.y;
  7850. } else if (v.y > u.y) {
  7851. u.y = v.y;
  7852. }
  7853. if (v.z < l.z) {
  7854. l.z = v.z;
  7855. } else if (v.z > u.z) {
  7856. u.z = v.z;
  7857. }
  7858. }
  7859. }
  7860. /**
  7861. * Update the `.aabb` property
  7862. */
  7863. updateAABB() {
  7864. this.computeLocalAABB(this.aabb);
  7865. }
  7866. /**
  7867. * Will update the `.boundingSphereRadius` property
  7868. */
  7869. updateBoundingSphereRadius() {
  7870. // Assume points are distributed with local (0,0,0) as center
  7871. let max2 = 0;
  7872. const vertices = this.vertices;
  7873. const v = new Vec3();
  7874. for (let i = 0, N = vertices.length / 3; i !== N; i++) {
  7875. this.getVertex(i, v);
  7876. const norm2 = v.lengthSquared();
  7877. if (norm2 > max2) {
  7878. max2 = norm2;
  7879. }
  7880. }
  7881. this.boundingSphereRadius = Math.sqrt(max2);
  7882. }
  7883. /**
  7884. * calculateWorldAABB
  7885. */
  7886. calculateWorldAABB(pos, quat, min, max) {
  7887. /*
  7888. const n = this.vertices.length / 3,
  7889. verts = this.vertices;
  7890. const minx,miny,minz,maxx,maxy,maxz;
  7891. const v = tempWorldVertex;
  7892. for(let i=0; i<n; i++){
  7893. this.getVertex(i, v);
  7894. quat.vmult(v, v);
  7895. pos.vadd(v, v);
  7896. if (v.x < minx || minx===undefined){
  7897. minx = v.x;
  7898. } else if(v.x > maxx || maxx===undefined){
  7899. maxx = v.x;
  7900. }
  7901. if (v.y < miny || miny===undefined){
  7902. miny = v.y;
  7903. } else if(v.y > maxy || maxy===undefined){
  7904. maxy = v.y;
  7905. }
  7906. if (v.z < minz || minz===undefined){
  7907. minz = v.z;
  7908. } else if(v.z > maxz || maxz===undefined){
  7909. maxz = v.z;
  7910. }
  7911. }
  7912. min.set(minx,miny,minz);
  7913. max.set(maxx,maxy,maxz);
  7914. */
  7915. // Faster approximation using local AABB
  7916. const frame = calculateWorldAABB_frame;
  7917. const result = calculateWorldAABB_aabb;
  7918. frame.position = pos;
  7919. frame.quaternion = quat;
  7920. this.aabb.toWorldFrame(frame, result);
  7921. min.copy(result.lowerBound);
  7922. max.copy(result.upperBound);
  7923. }
  7924. /**
  7925. * Get approximate volume
  7926. */
  7927. volume() {
  7928. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  7929. }
  7930. /**
  7931. * Create a Trimesh instance, shaped as a torus.
  7932. */
  7933. static createTorus(radius, tube, radialSegments, tubularSegments, arc) {
  7934. if (radius === void 0) {
  7935. radius = 1;
  7936. }
  7937. if (tube === void 0) {
  7938. tube = 0.5;
  7939. }
  7940. if (radialSegments === void 0) {
  7941. radialSegments = 8;
  7942. }
  7943. if (tubularSegments === void 0) {
  7944. tubularSegments = 6;
  7945. }
  7946. if (arc === void 0) {
  7947. arc = Math.PI * 2;
  7948. }
  7949. const vertices = [];
  7950. const indices = [];
  7951. for (let j = 0; j <= radialSegments; j++) {
  7952. for (let i = 0; i <= tubularSegments; i++) {
  7953. const u = i / tubularSegments * arc;
  7954. const v = j / radialSegments * Math.PI * 2;
  7955. const x = (radius + tube * Math.cos(v)) * Math.cos(u);
  7956. const y = (radius + tube * Math.cos(v)) * Math.sin(u);
  7957. const z = tube * Math.sin(v);
  7958. vertices.push(x, y, z);
  7959. }
  7960. }
  7961. for (let j = 1; j <= radialSegments; j++) {
  7962. for (let i = 1; i <= tubularSegments; i++) {
  7963. const a = (tubularSegments + 1) * j + i - 1;
  7964. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  7965. const c = (tubularSegments + 1) * (j - 1) + i;
  7966. const d = (tubularSegments + 1) * j + i;
  7967. indices.push(a, b, d);
  7968. indices.push(b, c, d);
  7969. }
  7970. }
  7971. return new Trimesh(vertices, indices);
  7972. }
  7973. }
  7974. const computeNormals_n = new Vec3();
  7975. const unscaledAABB = new AABB();
  7976. const getEdgeVector_va = new Vec3();
  7977. const getEdgeVector_vb = new Vec3();
  7978. const cb = new Vec3();
  7979. const ab = new Vec3();
  7980. const va = new Vec3();
  7981. const vb = new Vec3();
  7982. const vc = new Vec3();
  7983. const cli_aabb = new AABB();
  7984. const computeLocalAABB_worldVert = new Vec3();
  7985. const calculateWorldAABB_frame = new Transform();
  7986. const calculateWorldAABB_aabb = new AABB();
  7987. /**
  7988. * Constraint equation solver base class.
  7989. */
  7990. class Solver {
  7991. /**
  7992. * All equations to be solved
  7993. */
  7994. /**
  7995. * @todo remove useless constructor
  7996. */
  7997. constructor() {
  7998. this.equations = [];
  7999. }
  8000. /**
  8001. * Should be implemented in subclasses!
  8002. * @todo use abstract
  8003. * @return number of iterations performed
  8004. */
  8005. solve(dt, world) {
  8006. return (// Should return the number of iterations done!
  8007. 0
  8008. );
  8009. }
  8010. /**
  8011. * Add an equation
  8012. */
  8013. addEquation(eq) {
  8014. if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) {
  8015. this.equations.push(eq);
  8016. }
  8017. }
  8018. /**
  8019. * Remove an equation
  8020. */
  8021. removeEquation(eq) {
  8022. const eqs = this.equations;
  8023. const i = eqs.indexOf(eq);
  8024. if (i !== -1) {
  8025. eqs.splice(i, 1);
  8026. }
  8027. }
  8028. /**
  8029. * Add all equations
  8030. */
  8031. removeAllEquations() {
  8032. this.equations.length = 0;
  8033. }
  8034. }
  8035. /**
  8036. * Constraint equation Gauss-Seidel solver.
  8037. * @todo The spook parameters should be specified for each constraint, not globally.
  8038. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  8039. */
  8040. class GSSolver extends Solver {
  8041. /**
  8042. * The number of solver iterations determines quality of the constraints in the world.
  8043. * The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
  8044. */
  8045. /**
  8046. * When tolerance is reached, the system is assumed to be converged.
  8047. */
  8048. /**
  8049. * @todo remove useless constructor
  8050. */
  8051. constructor() {
  8052. super();
  8053. this.iterations = 10;
  8054. this.tolerance = 1e-7;
  8055. }
  8056. /**
  8057. * Solve
  8058. * @return number of iterations performed
  8059. */
  8060. solve(dt, world) {
  8061. let iter = 0;
  8062. const maxIter = this.iterations;
  8063. const tolSquared = this.tolerance * this.tolerance;
  8064. const equations = this.equations;
  8065. const Neq = equations.length;
  8066. const bodies = world.bodies;
  8067. const Nbodies = bodies.length;
  8068. const h = dt;
  8069. let B;
  8070. let invC;
  8071. let deltalambda;
  8072. let deltalambdaTot;
  8073. let GWlambda;
  8074. let lambdaj; // Update solve mass
  8075. if (Neq !== 0) {
  8076. for (let i = 0; i !== Nbodies; i++) {
  8077. bodies[i].updateSolveMassProperties();
  8078. }
  8079. } // Things that do not change during iteration can be computed once
  8080. const invCs = GSSolver_solve_invCs;
  8081. const Bs = GSSolver_solve_Bs;
  8082. const lambda = GSSolver_solve_lambda;
  8083. invCs.length = Neq;
  8084. Bs.length = Neq;
  8085. lambda.length = Neq;
  8086. for (let i = 0; i !== Neq; i++) {
  8087. const c = equations[i];
  8088. lambda[i] = 0.0;
  8089. Bs[i] = c.computeB(h);
  8090. invCs[i] = 1.0 / c.computeC();
  8091. }
  8092. if (Neq !== 0) {
  8093. // Reset vlambda
  8094. for (let i = 0; i !== Nbodies; i++) {
  8095. const b = bodies[i];
  8096. const vlambda = b.vlambda;
  8097. const wlambda = b.wlambda;
  8098. vlambda.set(0, 0, 0);
  8099. wlambda.set(0, 0, 0);
  8100. } // Iterate over equations
  8101. for (iter = 0; iter !== maxIter; iter++) {
  8102. // Accumulate the total error for each iteration.
  8103. deltalambdaTot = 0.0;
  8104. for (let j = 0; j !== Neq; j++) {
  8105. const c = equations[j]; // Compute iteration
  8106. B = Bs[j];
  8107. invC = invCs[j];
  8108. lambdaj = lambda[j];
  8109. GWlambda = c.computeGWlambda();
  8110. deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval
  8111. if (lambdaj + deltalambda < c.minForce) {
  8112. deltalambda = c.minForce - lambdaj;
  8113. } else if (lambdaj + deltalambda > c.maxForce) {
  8114. deltalambda = c.maxForce - lambdaj;
  8115. }
  8116. lambda[j] += deltalambda;
  8117. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  8118. c.addToWlambda(deltalambda);
  8119. } // If the total error is small enough - stop iterate
  8120. if (deltalambdaTot * deltalambdaTot < tolSquared) {
  8121. break;
  8122. }
  8123. } // Add result to velocity
  8124. for (let i = 0; i !== Nbodies; i++) {
  8125. const b = bodies[i];
  8126. const v = b.velocity;
  8127. const w = b.angularVelocity;
  8128. b.vlambda.vmul(b.linearFactor, b.vlambda);
  8129. v.vadd(b.vlambda, v);
  8130. b.wlambda.vmul(b.angularFactor, b.wlambda);
  8131. w.vadd(b.wlambda, w);
  8132. } // Set the `.multiplier` property of each equation
  8133. let l = equations.length;
  8134. const invDt = 1 / h;
  8135. while (l--) {
  8136. equations[l].multiplier = lambda[l] * invDt;
  8137. }
  8138. }
  8139. return iter;
  8140. }
  8141. } // Just temporary number holders that we want to reuse each iteration.
  8142. const GSSolver_solve_lambda = [];
  8143. const GSSolver_solve_invCs = [];
  8144. const GSSolver_solve_Bs = [];
  8145. /**
  8146. * Splits the equations into islands and solves them independently. Can improve performance.
  8147. */
  8148. class SplitSolver extends Solver {
  8149. /**
  8150. * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
  8151. */
  8152. /**
  8153. * When tolerance is reached, the system is assumed to be converged.
  8154. */
  8155. /** subsolver */
  8156. constructor(subsolver) {
  8157. super();
  8158. this.iterations = 10;
  8159. this.tolerance = 1e-7;
  8160. this.subsolver = subsolver;
  8161. this.nodes = [];
  8162. this.nodePool = []; // Create needed nodes, reuse if possible
  8163. while (this.nodePool.length < 128) {
  8164. this.nodePool.push(this.createNode());
  8165. }
  8166. }
  8167. /**
  8168. * createNode
  8169. */
  8170. createNode() {
  8171. return {
  8172. body: null,
  8173. children: [],
  8174. eqs: [],
  8175. visited: false
  8176. };
  8177. }
  8178. /**
  8179. * Solve the subsystems
  8180. * @return number of iterations performed
  8181. */
  8182. solve(dt, world) {
  8183. const nodes = SplitSolver_solve_nodes;
  8184. const nodePool = this.nodePool;
  8185. const bodies = world.bodies;
  8186. const equations = this.equations;
  8187. const Neq = equations.length;
  8188. const Nbodies = bodies.length;
  8189. const subsolver = this.subsolver; // Create needed nodes, reuse if possible
  8190. while (nodePool.length < Nbodies) {
  8191. nodePool.push(this.createNode());
  8192. }
  8193. nodes.length = Nbodies;
  8194. for (let i = 0; i < Nbodies; i++) {
  8195. nodes[i] = nodePool[i];
  8196. } // Reset node values
  8197. for (let i = 0; i !== Nbodies; i++) {
  8198. const node = nodes[i];
  8199. node.body = bodies[i];
  8200. node.children.length = 0;
  8201. node.eqs.length = 0;
  8202. node.visited = false;
  8203. }
  8204. for (let k = 0; k !== Neq; k++) {
  8205. const eq = equations[k];
  8206. const i = bodies.indexOf(eq.bi);
  8207. const j = bodies.indexOf(eq.bj);
  8208. const ni = nodes[i];
  8209. const nj = nodes[j];
  8210. ni.children.push(nj);
  8211. ni.eqs.push(eq);
  8212. nj.children.push(ni);
  8213. nj.eqs.push(eq);
  8214. }
  8215. let child;
  8216. let n = 0;
  8217. let eqs = SplitSolver_solve_eqs;
  8218. subsolver.tolerance = this.tolerance;
  8219. subsolver.iterations = this.iterations;
  8220. const dummyWorld = SplitSolver_solve_dummyWorld;
  8221. while (child = getUnvisitedNode(nodes)) {
  8222. eqs.length = 0;
  8223. dummyWorld.bodies.length = 0;
  8224. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  8225. const Neqs = eqs.length;
  8226. eqs = eqs.sort(sortById);
  8227. for (let i = 0; i !== Neqs; i++) {
  8228. subsolver.addEquation(eqs[i]);
  8229. }
  8230. subsolver.solve(dt, dummyWorld);
  8231. subsolver.removeAllEquations();
  8232. n++;
  8233. }
  8234. return n;
  8235. }
  8236. } // Returns the number of subsystems
  8237. const SplitSolver_solve_nodes = []; // All allocated node objects
  8238. const SplitSolver_solve_eqs = []; // Temp array
  8239. const SplitSolver_solve_dummyWorld = {
  8240. bodies: []
  8241. }; // Temp object
  8242. const STATIC = Body.STATIC;
  8243. function getUnvisitedNode(nodes) {
  8244. const Nnodes = nodes.length;
  8245. for (let i = 0; i !== Nnodes; i++) {
  8246. const node = nodes[i];
  8247. if (!node.visited && !(node.body.type & STATIC)) {
  8248. return node;
  8249. }
  8250. }
  8251. return false;
  8252. }
  8253. const queue = [];
  8254. function bfs(root, visitFunc, bds, eqs) {
  8255. queue.push(root);
  8256. root.visited = true;
  8257. visitFunc(root, bds, eqs);
  8258. while (queue.length) {
  8259. const node = queue.pop(); // Loop over unvisited child nodes
  8260. let child;
  8261. while (child = getUnvisitedNode(node.children)) {
  8262. child.visited = true;
  8263. visitFunc(child, bds, eqs);
  8264. queue.push(child);
  8265. }
  8266. }
  8267. }
  8268. function visitFunc(node, bds, eqs) {
  8269. bds.push(node.body);
  8270. const Neqs = node.eqs.length;
  8271. for (let i = 0; i !== Neqs; i++) {
  8272. const eq = node.eqs[i];
  8273. if (!eqs.includes(eq)) {
  8274. eqs.push(eq);
  8275. }
  8276. }
  8277. }
  8278. function sortById(a, b) {
  8279. return b.id - a.id;
  8280. }
  8281. /**
  8282. * For pooling objects that can be reused.
  8283. */
  8284. class Pool {
  8285. constructor() {
  8286. this.objects = [];
  8287. this.type = Object;
  8288. }
  8289. /**
  8290. * Release an object after use
  8291. */
  8292. release() {
  8293. const Nargs = arguments.length;
  8294. for (let i = 0; i !== Nargs; i++) {
  8295. this.objects.push(i < 0 || arguments.length <= i ? undefined : arguments[i]);
  8296. }
  8297. return this;
  8298. }
  8299. /**
  8300. * Get an object
  8301. */
  8302. get() {
  8303. if (this.objects.length === 0) {
  8304. return this.constructObject();
  8305. } else {
  8306. return this.objects.pop();
  8307. }
  8308. }
  8309. /**
  8310. * Construct an object. Should be implemented in each subclass.
  8311. */
  8312. constructObject() {
  8313. throw new Error('constructObject() not implemented in this Pool subclass yet!');
  8314. }
  8315. /**
  8316. * @return Self, for chaining
  8317. */
  8318. resize(size) {
  8319. const objects = this.objects;
  8320. while (objects.length > size) {
  8321. objects.pop();
  8322. }
  8323. while (objects.length < size) {
  8324. objects.push(this.constructObject());
  8325. }
  8326. return this;
  8327. }
  8328. }
  8329. /**
  8330. * Vec3Pool
  8331. */
  8332. class Vec3Pool extends Pool {
  8333. constructor() {
  8334. super(...arguments);
  8335. this.type = Vec3;
  8336. }
  8337. /**
  8338. * Construct a vector
  8339. */
  8340. constructObject() {
  8341. return new Vec3();
  8342. }
  8343. }
  8344. // Naming rule: based of the order in SHAPE_TYPES,
  8345. // the first part of the method is formed by the
  8346. // shape type that comes before, in the second part
  8347. // there is the shape type that comes after in the SHAPE_TYPES list
  8348. const COLLISION_TYPES = {
  8349. sphereSphere: Shape.types.SPHERE,
  8350. spherePlane: Shape.types.SPHERE | Shape.types.PLANE,
  8351. boxBox: Shape.types.BOX | Shape.types.BOX,
  8352. sphereBox: Shape.types.SPHERE | Shape.types.BOX,
  8353. planeBox: Shape.types.PLANE | Shape.types.BOX,
  8354. convexConvex: Shape.types.CONVEXPOLYHEDRON,
  8355. sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON,
  8356. planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON,
  8357. boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON,
  8358. sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD,
  8359. boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD,
  8360. convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD,
  8361. sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE,
  8362. planeParticle: Shape.types.PLANE | Shape.types.PARTICLE,
  8363. boxParticle: Shape.types.BOX | Shape.types.PARTICLE,
  8364. convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON,
  8365. cylinderCylinder: Shape.types.CYLINDER,
  8366. sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER,
  8367. planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER,
  8368. boxCylinder: Shape.types.BOX | Shape.types.CYLINDER,
  8369. convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER,
  8370. heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER,
  8371. particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER,
  8372. sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH,
  8373. planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH
  8374. };
  8375. /**
  8376. * Helper class for the World. Generates ContactEquations.
  8377. * @todo Sphere-ConvexPolyhedron contacts
  8378. * @todo Contact reduction
  8379. * @todo should move methods to prototype
  8380. */
  8381. class Narrowphase {
  8382. /**
  8383. * Internal storage of pooled contact points.
  8384. */
  8385. /**
  8386. * Pooled vectors.
  8387. */
  8388. get [COLLISION_TYPES.sphereSphere]() {
  8389. return this.sphereSphere;
  8390. }
  8391. get [COLLISION_TYPES.spherePlane]() {
  8392. return this.spherePlane;
  8393. }
  8394. get [COLLISION_TYPES.boxBox]() {
  8395. return this.boxBox;
  8396. }
  8397. get [COLLISION_TYPES.sphereBox]() {
  8398. return this.sphereBox;
  8399. }
  8400. get [COLLISION_TYPES.planeBox]() {
  8401. return this.planeBox;
  8402. }
  8403. get [COLLISION_TYPES.convexConvex]() {
  8404. return this.convexConvex;
  8405. }
  8406. get [COLLISION_TYPES.sphereConvex]() {
  8407. return this.sphereConvex;
  8408. }
  8409. get [COLLISION_TYPES.planeConvex]() {
  8410. return this.planeConvex;
  8411. }
  8412. get [COLLISION_TYPES.boxConvex]() {
  8413. return this.boxConvex;
  8414. }
  8415. get [COLLISION_TYPES.sphereHeightfield]() {
  8416. return this.sphereHeightfield;
  8417. }
  8418. get [COLLISION_TYPES.boxHeightfield]() {
  8419. return this.boxHeightfield;
  8420. }
  8421. get [COLLISION_TYPES.convexHeightfield]() {
  8422. return this.convexHeightfield;
  8423. }
  8424. get [COLLISION_TYPES.sphereParticle]() {
  8425. return this.sphereParticle;
  8426. }
  8427. get [COLLISION_TYPES.planeParticle]() {
  8428. return this.planeParticle;
  8429. }
  8430. get [COLLISION_TYPES.boxParticle]() {
  8431. return this.boxParticle;
  8432. }
  8433. get [COLLISION_TYPES.convexParticle]() {
  8434. return this.convexParticle;
  8435. }
  8436. get [COLLISION_TYPES.cylinderCylinder]() {
  8437. return this.convexConvex;
  8438. }
  8439. get [COLLISION_TYPES.sphereCylinder]() {
  8440. return this.sphereConvex;
  8441. }
  8442. get [COLLISION_TYPES.planeCylinder]() {
  8443. return this.planeConvex;
  8444. }
  8445. get [COLLISION_TYPES.boxCylinder]() {
  8446. return this.boxConvex;
  8447. }
  8448. get [COLLISION_TYPES.convexCylinder]() {
  8449. return this.convexConvex;
  8450. }
  8451. get [COLLISION_TYPES.heightfieldCylinder]() {
  8452. return this.heightfieldCylinder;
  8453. }
  8454. get [COLLISION_TYPES.particleCylinder]() {
  8455. return this.particleCylinder;
  8456. }
  8457. get [COLLISION_TYPES.sphereTrimesh]() {
  8458. return this.sphereTrimesh;
  8459. }
  8460. get [COLLISION_TYPES.planeTrimesh]() {
  8461. return this.planeTrimesh;
  8462. } // get [COLLISION_TYPES.convexTrimesh]() {
  8463. // return this.convexTrimesh
  8464. // }
  8465. constructor(world) {
  8466. this.contactPointPool = [];
  8467. this.frictionEquationPool = [];
  8468. this.result = [];
  8469. this.frictionResult = [];
  8470. this.v3pool = new Vec3Pool();
  8471. this.world = world;
  8472. this.currentContactMaterial = world.defaultContactMaterial;
  8473. this.enableFrictionReduction = false;
  8474. }
  8475. /**
  8476. * Make a contact object, by using the internal pool or creating a new one.
  8477. */
  8478. createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) {
  8479. let c;
  8480. if (this.contactPointPool.length) {
  8481. c = this.contactPointPool.pop();
  8482. c.bi = bi;
  8483. c.bj = bj;
  8484. } else {
  8485. c = new ContactEquation(bi, bj);
  8486. }
  8487. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  8488. const cm = this.currentContactMaterial;
  8489. c.restitution = cm.restitution;
  8490. c.setSpookParams(cm.contactEquationStiffness, cm.contactEquationRelaxation, this.world.dt);
  8491. const matA = si.material || bi.material;
  8492. const matB = sj.material || bj.material;
  8493. if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) {
  8494. c.restitution = matA.restitution * matB.restitution;
  8495. }
  8496. c.si = overrideShapeA || si;
  8497. c.sj = overrideShapeB || sj;
  8498. return c;
  8499. }
  8500. createFrictionEquationsFromContact(contactEquation, outArray) {
  8501. const bodyA = contactEquation.bi;
  8502. const bodyB = contactEquation.bj;
  8503. const shapeA = contactEquation.si;
  8504. const shapeB = contactEquation.sj;
  8505. const world = this.world;
  8506. const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them
  8507. let friction = cm.friction;
  8508. const matA = shapeA.material || bodyA.material;
  8509. const matB = shapeB.material || bodyB.material;
  8510. if (matA && matB && matA.friction >= 0 && matB.friction >= 0) {
  8511. friction = matA.friction * matB.friction;
  8512. }
  8513. if (friction > 0) {
  8514. // Create 2 tangent equations
  8515. // Users may provide a force different from global gravity to use when computing contact friction.
  8516. const mug = friction * (world.frictionGravity || world.gravity).length();
  8517. let reducedMass = bodyA.invMass + bodyB.invMass;
  8518. if (reducedMass > 0) {
  8519. reducedMass = 1 / reducedMass;
  8520. }
  8521. const pool = this.frictionEquationPool;
  8522. const c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
  8523. const c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
  8524. c1.bi = c2.bi = bodyA;
  8525. c1.bj = c2.bj = bodyB;
  8526. c1.minForce = c2.minForce = -mug * reducedMass;
  8527. c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors
  8528. c1.ri.copy(contactEquation.ri);
  8529. c1.rj.copy(contactEquation.rj);
  8530. c2.ri.copy(contactEquation.ri);
  8531. c2.rj.copy(contactEquation.rj); // Construct tangents
  8532. contactEquation.ni.tangents(c1.t, c2.t); // Set spook params
  8533. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  8534. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  8535. c1.enabled = c2.enabled = contactEquation.enabled;
  8536. outArray.push(c1, c2);
  8537. return true;
  8538. }
  8539. return false;
  8540. }
  8541. /**
  8542. * Take the average N latest contact point on the plane.
  8543. */
  8544. createFrictionFromAverage(numContacts) {
  8545. // The last contactEquation
  8546. let c = this.result[this.result.length - 1]; // Create the result: two "average" friction equations
  8547. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  8548. return;
  8549. }
  8550. const f1 = this.frictionResult[this.frictionResult.length - 2];
  8551. const f2 = this.frictionResult[this.frictionResult.length - 1];
  8552. averageNormal.setZero();
  8553. averageContactPointA.setZero();
  8554. averageContactPointB.setZero();
  8555. const bodyA = c.bi;
  8556. c.bj;
  8557. for (let i = 0; i !== numContacts; i++) {
  8558. c = this.result[this.result.length - 1 - i];
  8559. if (c.bi !== bodyA) {
  8560. averageNormal.vadd(c.ni, averageNormal);
  8561. averageContactPointA.vadd(c.ri, averageContactPointA);
  8562. averageContactPointB.vadd(c.rj, averageContactPointB);
  8563. } else {
  8564. averageNormal.vsub(c.ni, averageNormal);
  8565. averageContactPointA.vadd(c.rj, averageContactPointA);
  8566. averageContactPointB.vadd(c.ri, averageContactPointB);
  8567. }
  8568. }
  8569. const invNumContacts = 1 / numContacts;
  8570. averageContactPointA.scale(invNumContacts, f1.ri);
  8571. averageContactPointB.scale(invNumContacts, f1.rj);
  8572. f2.ri.copy(f1.ri); // Should be the same
  8573. f2.rj.copy(f1.rj);
  8574. averageNormal.normalize();
  8575. averageNormal.tangents(f1.t, f2.t); // return eq;
  8576. }
  8577. /**
  8578. * Generate all contacts between a list of body pairs
  8579. * @param p1 Array of body indices
  8580. * @param p2 Array of body indices
  8581. * @param result Array to store generated contacts
  8582. * @param oldcontacts Optional. Array of reusable contact objects
  8583. */
  8584. getContacts(p1, p2, world, result, oldcontacts, frictionResult, frictionPool) {
  8585. // Save old contact objects
  8586. this.contactPointPool = oldcontacts;
  8587. this.frictionEquationPool = frictionPool;
  8588. this.result = result;
  8589. this.frictionResult = frictionResult;
  8590. const qi = tmpQuat1;
  8591. const qj = tmpQuat2;
  8592. const xi = tmpVec1;
  8593. const xj = tmpVec2;
  8594. for (let k = 0, N = p1.length; k !== N; k++) {
  8595. // Get current collision bodies
  8596. const bi = p1[k];
  8597. const bj = p2[k]; // Get contact material
  8598. let bodyContactMaterial = null;
  8599. if (bi.material && bj.material) {
  8600. bodyContactMaterial = world.getContactMaterial(bi.material, bj.material) || null;
  8601. }
  8602. const justTest = bi.type & Body.KINEMATIC && bj.type & Body.STATIC || bi.type & Body.STATIC && bj.type & Body.KINEMATIC || bi.type & Body.KINEMATIC && bj.type & Body.KINEMATIC;
  8603. for (let i = 0; i < bi.shapes.length; i++) {
  8604. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  8605. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  8606. xi.vadd(bi.position, xi);
  8607. const si = bi.shapes[i];
  8608. for (let j = 0; j < bj.shapes.length; j++) {
  8609. // Compute world transform of shapes
  8610. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  8611. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  8612. xj.vadd(bj.position, xj);
  8613. const sj = bj.shapes[j];
  8614. if (!(si.collisionFilterMask & sj.collisionFilterGroup && sj.collisionFilterMask & si.collisionFilterGroup)) {
  8615. continue;
  8616. }
  8617. if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
  8618. continue;
  8619. } // Get collision material
  8620. let shapeContactMaterial = null;
  8621. if (si.material && sj.material) {
  8622. shapeContactMaterial = world.getContactMaterial(si.material, sj.material) || null;
  8623. }
  8624. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial; // Get contacts
  8625. const resolverIndex = si.type | sj.type;
  8626. const resolver = this[resolverIndex];
  8627. if (resolver) {
  8628. let retval = false; // TO DO: investigate why sphereParticle and convexParticle
  8629. // resolvers expect si and sj shapes to be in reverse order
  8630. // (i.e. larger integer value type first instead of smaller first)
  8631. if (si.type < sj.type) {
  8632. retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8633. } else {
  8634. retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);
  8635. }
  8636. if (retval && justTest) {
  8637. // Register overlap
  8638. world.shapeOverlapKeeper.set(si.id, sj.id);
  8639. world.bodyOverlapKeeper.set(bi.id, bj.id);
  8640. }
  8641. }
  8642. }
  8643. }
  8644. }
  8645. }
  8646. sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8647. if (justTest) {
  8648. return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2;
  8649. } // We will have only one contact in this case
  8650. const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal
  8651. xj.vsub(xi, contactEq.ni);
  8652. contactEq.ni.normalize(); // Contact point locations
  8653. contactEq.ri.copy(contactEq.ni);
  8654. contactEq.rj.copy(contactEq.ni);
  8655. contactEq.ri.scale(si.radius, contactEq.ri);
  8656. contactEq.rj.scale(-sj.radius, contactEq.rj);
  8657. contactEq.ri.vadd(xi, contactEq.ri);
  8658. contactEq.ri.vsub(bi.position, contactEq.ri);
  8659. contactEq.rj.vadd(xj, contactEq.rj);
  8660. contactEq.rj.vsub(bj.position, contactEq.rj);
  8661. this.result.push(contactEq);
  8662. this.createFrictionEquationsFromContact(contactEq, this.frictionResult);
  8663. }
  8664. spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8665. // We will have one contact in this case
  8666. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal
  8667. r.ni.set(0, 0, 1);
  8668. qj.vmult(r.ni, r.ni);
  8669. r.ni.negate(r.ni); // body i is the sphere, flip normal
  8670. r.ni.normalize(); // Needed?
  8671. // Vector from sphere center to contact point
  8672. r.ni.scale(si.radius, r.ri); // Project down sphere on plane
  8673. xi.vsub(xj, point_on_plane_to_sphere);
  8674. r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  8675. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane
  8676. if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) {
  8677. if (justTest) {
  8678. return true;
  8679. } // Make it relative to the body
  8680. const ri = r.ri;
  8681. const rj = r.rj;
  8682. ri.vadd(xi, ri);
  8683. ri.vsub(bi.position, ri);
  8684. rj.vadd(xj, rj);
  8685. rj.vsub(bj.position, rj);
  8686. this.result.push(r);
  8687. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8688. }
  8689. }
  8690. boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8691. si.convexPolyhedronRepresentation.material = si.material;
  8692. sj.convexPolyhedronRepresentation.material = sj.material;
  8693. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  8694. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  8695. return this.convexConvex(si.convexPolyhedronRepresentation, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8696. }
  8697. sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8698. const v3pool = this.v3pool; // we refer to the box as body j
  8699. const sides = sphereBox_sides;
  8700. xi.vsub(xj, box_to_sphere);
  8701. sj.getSideNormals(sides, qj);
  8702. const R = si.radius;
  8703. let found = false; // Store the resulting side penetration info
  8704. const side_ns = sphereBox_side_ns;
  8705. const side_ns1 = sphereBox_side_ns1;
  8706. const side_ns2 = sphereBox_side_ns2;
  8707. let side_h = null;
  8708. let side_penetrations = 0;
  8709. let side_dot1 = 0;
  8710. let side_dot2 = 0;
  8711. let side_distance = null;
  8712. for (let idx = 0, nsides = sides.length; idx !== nsides && found === false; idx++) {
  8713. // Get the plane side normal (ns)
  8714. const ns = sphereBox_ns;
  8715. ns.copy(sides[idx]);
  8716. const h = ns.length();
  8717. ns.normalize(); // The normal/distance dot product tells which side of the plane we are
  8718. const dot = box_to_sphere.dot(ns);
  8719. if (dot < h + R && dot > 0) {
  8720. // Intersects plane. Now check the other two dimensions
  8721. const ns1 = sphereBox_ns1;
  8722. const ns2 = sphereBox_ns2;
  8723. ns1.copy(sides[(idx + 1) % 3]);
  8724. ns2.copy(sides[(idx + 2) % 3]);
  8725. const h1 = ns1.length();
  8726. const h2 = ns2.length();
  8727. ns1.normalize();
  8728. ns2.normalize();
  8729. const dot1 = box_to_sphere.dot(ns1);
  8730. const dot2 = box_to_sphere.dot(ns2);
  8731. if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) {
  8732. const dist = Math.abs(dot - h - R);
  8733. if (side_distance === null || dist < side_distance) {
  8734. side_distance = dist;
  8735. side_dot1 = dot1;
  8736. side_dot2 = dot2;
  8737. side_h = h;
  8738. side_ns.copy(ns);
  8739. side_ns1.copy(ns1);
  8740. side_ns2.copy(ns2);
  8741. side_penetrations++;
  8742. if (justTest) {
  8743. return true;
  8744. }
  8745. }
  8746. }
  8747. }
  8748. }
  8749. if (side_penetrations) {
  8750. found = true;
  8751. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8752. side_ns.scale(-R, r.ri); // Sphere r
  8753. r.ni.copy(side_ns);
  8754. r.ni.negate(r.ni); // Normal should be out of sphere
  8755. side_ns.scale(side_h, side_ns);
  8756. side_ns1.scale(side_dot1, side_ns1);
  8757. side_ns.vadd(side_ns1, side_ns);
  8758. side_ns2.scale(side_dot2, side_ns2);
  8759. side_ns.vadd(side_ns2, r.rj); // Make relative to bodies
  8760. r.ri.vadd(xi, r.ri);
  8761. r.ri.vsub(bi.position, r.ri);
  8762. r.rj.vadd(xj, r.rj);
  8763. r.rj.vsub(bj.position, r.rj);
  8764. this.result.push(r);
  8765. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8766. } // Check corners
  8767. let rj = v3pool.get();
  8768. const sphere_to_corner = sphereBox_sphere_to_corner;
  8769. for (let j = 0; j !== 2 && !found; j++) {
  8770. for (let k = 0; k !== 2 && !found; k++) {
  8771. for (let l = 0; l !== 2 && !found; l++) {
  8772. rj.set(0, 0, 0);
  8773. if (j) {
  8774. rj.vadd(sides[0], rj);
  8775. } else {
  8776. rj.vsub(sides[0], rj);
  8777. }
  8778. if (k) {
  8779. rj.vadd(sides[1], rj);
  8780. } else {
  8781. rj.vsub(sides[1], rj);
  8782. }
  8783. if (l) {
  8784. rj.vadd(sides[2], rj);
  8785. } else {
  8786. rj.vsub(sides[2], rj);
  8787. } // World position of corner
  8788. xj.vadd(rj, sphere_to_corner);
  8789. sphere_to_corner.vsub(xi, sphere_to_corner);
  8790. if (sphere_to_corner.lengthSquared() < R * R) {
  8791. if (justTest) {
  8792. return true;
  8793. }
  8794. found = true;
  8795. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8796. r.ri.copy(sphere_to_corner);
  8797. r.ri.normalize();
  8798. r.ni.copy(r.ri);
  8799. r.ri.scale(R, r.ri);
  8800. r.rj.copy(rj); // Make relative to bodies
  8801. r.ri.vadd(xi, r.ri);
  8802. r.ri.vsub(bi.position, r.ri);
  8803. r.rj.vadd(xj, r.rj);
  8804. r.rj.vsub(bj.position, r.rj);
  8805. this.result.push(r);
  8806. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8807. }
  8808. }
  8809. }
  8810. }
  8811. v3pool.release(rj);
  8812. rj = null; // Check edges
  8813. const edgeTangent = v3pool.get();
  8814. const edgeCenter = v3pool.get();
  8815. const r = v3pool.get(); // r = edge center to sphere center
  8816. const orthogonal = v3pool.get();
  8817. const dist = v3pool.get();
  8818. const Nsides = sides.length;
  8819. for (let j = 0; j !== Nsides && !found; j++) {
  8820. for (let k = 0; k !== Nsides && !found; k++) {
  8821. if (j % 3 !== k % 3) {
  8822. // Get edge tangent
  8823. sides[k].cross(sides[j], edgeTangent);
  8824. edgeTangent.normalize();
  8825. sides[j].vadd(sides[k], edgeCenter);
  8826. r.copy(xi);
  8827. r.vsub(edgeCenter, r);
  8828. r.vsub(xj, r);
  8829. const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  8830. edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction
  8831. // Find the third side orthogonal to this one
  8832. let l = 0;
  8833. while (l === j % 3 || l === k % 3) {
  8834. l++;
  8835. } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  8836. dist.copy(xi);
  8837. dist.vsub(orthogonal, dist);
  8838. dist.vsub(edgeCenter, dist);
  8839. dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it
  8840. const tdist = Math.abs(orthonorm);
  8841. const ndist = dist.length();
  8842. if (tdist < sides[l].length() && ndist < R) {
  8843. if (justTest) {
  8844. return true;
  8845. }
  8846. found = true;
  8847. const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8848. edgeCenter.vadd(orthogonal, res.rj); // box rj
  8849. res.rj.copy(res.rj);
  8850. dist.negate(res.ni);
  8851. res.ni.normalize();
  8852. res.ri.copy(res.rj);
  8853. res.ri.vadd(xj, res.ri);
  8854. res.ri.vsub(xi, res.ri);
  8855. res.ri.normalize();
  8856. res.ri.scale(R, res.ri); // Make relative to bodies
  8857. res.ri.vadd(xi, res.ri);
  8858. res.ri.vsub(bi.position, res.ri);
  8859. res.rj.vadd(xj, res.rj);
  8860. res.rj.vsub(bj.position, res.rj);
  8861. this.result.push(res);
  8862. this.createFrictionEquationsFromContact(res, this.frictionResult);
  8863. }
  8864. }
  8865. }
  8866. }
  8867. v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist);
  8868. }
  8869. planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8870. sj.convexPolyhedronRepresentation.material = sj.material;
  8871. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  8872. sj.convexPolyhedronRepresentation.id = sj.id;
  8873. return this.planeConvex(si, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8874. }
  8875. convexConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest, faceListA, faceListB) {
  8876. const sepAxis = convexConvex_sepAxis;
  8877. if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
  8878. return;
  8879. }
  8880. if (si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB)) {
  8881. const res = [];
  8882. const q = convexConvex_q;
  8883. si.clipAgainstHull(xi, qi, sj, xj, qj, sepAxis, -100, 100, res);
  8884. let numContacts = 0;
  8885. for (let j = 0; j !== res.length; j++) {
  8886. if (justTest) {
  8887. return true;
  8888. }
  8889. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8890. const ri = r.ri;
  8891. const rj = r.rj;
  8892. sepAxis.negate(r.ni);
  8893. res[j].normal.negate(q);
  8894. q.scale(res[j].depth, q);
  8895. res[j].point.vadd(q, ri);
  8896. rj.copy(res[j].point); // Contact points are in world coordinates. Transform back to relative
  8897. ri.vsub(xi, ri);
  8898. rj.vsub(xj, rj); // Make relative to bodies
  8899. ri.vadd(xi, ri);
  8900. ri.vsub(bi.position, ri);
  8901. rj.vadd(xj, rj);
  8902. rj.vsub(bj.position, rj);
  8903. this.result.push(r);
  8904. numContacts++;
  8905. if (!this.enableFrictionReduction) {
  8906. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8907. }
  8908. }
  8909. if (this.enableFrictionReduction && numContacts) {
  8910. this.createFrictionFromAverage(numContacts);
  8911. }
  8912. }
  8913. }
  8914. sphereConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8915. const v3pool = this.v3pool;
  8916. xi.vsub(xj, convex_to_sphere);
  8917. const normals = sj.faceNormals;
  8918. const faces = sj.faces;
  8919. const verts = sj.vertices;
  8920. const R = si.radius;
  8921. // return;
  8922. // }
  8923. let found = false; // Check corners
  8924. for (let i = 0; i !== verts.length; i++) {
  8925. const v = verts[i]; // World position of corner
  8926. const worldCorner = sphereConvex_worldCorner;
  8927. qj.vmult(v, worldCorner);
  8928. xj.vadd(worldCorner, worldCorner);
  8929. const sphere_to_corner = sphereConvex_sphereToCorner;
  8930. worldCorner.vsub(xi, sphere_to_corner);
  8931. if (sphere_to_corner.lengthSquared() < R * R) {
  8932. if (justTest) {
  8933. return true;
  8934. }
  8935. found = true;
  8936. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8937. r.ri.copy(sphere_to_corner);
  8938. r.ri.normalize();
  8939. r.ni.copy(r.ri);
  8940. r.ri.scale(R, r.ri);
  8941. worldCorner.vsub(xj, r.rj); // Should be relative to the body.
  8942. r.ri.vadd(xi, r.ri);
  8943. r.ri.vsub(bi.position, r.ri); // Should be relative to the body.
  8944. r.rj.vadd(xj, r.rj);
  8945. r.rj.vsub(bj.position, r.rj);
  8946. this.result.push(r);
  8947. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8948. return;
  8949. }
  8950. } // Check side (plane) intersections
  8951. for (let i = 0, nfaces = faces.length; i !== nfaces && found === false; i++) {
  8952. const normal = normals[i];
  8953. const face = faces[i]; // Get world-transformed normal of the face
  8954. const worldNormal = sphereConvex_worldNormal;
  8955. qj.vmult(normal, worldNormal); // Get a world vertex from the face
  8956. const worldPoint = sphereConvex_worldPoint;
  8957. qj.vmult(verts[face[0]], worldPoint);
  8958. worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal
  8959. const worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  8960. worldNormal.scale(-R, worldSpherePointClosestToPlane);
  8961. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere
  8962. const penetrationVec = sphereConvex_penetrationVec;
  8963. worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap.
  8964. const penetration = penetrationVec.dot(worldNormal);
  8965. const worldPointToSphere = sphereConvex_sphereToWorldPoint;
  8966. xi.vsub(worldPoint, worldPointToSphere);
  8967. if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) {
  8968. // Intersects plane. Now check if the sphere is inside the face polygon
  8969. const faceVerts = []; // Face vertices, in world coords
  8970. for (let j = 0, Nverts = face.length; j !== Nverts; j++) {
  8971. const worldVertex = v3pool.get();
  8972. qj.vmult(verts[face[j]], worldVertex);
  8973. xj.vadd(worldVertex, worldVertex);
  8974. faceVerts.push(worldVertex);
  8975. }
  8976. if (pointInPolygon(faceVerts, worldNormal, xi)) {
  8977. // Is the sphere center in the face polygon?
  8978. if (justTest) {
  8979. return true;
  8980. }
  8981. found = true;
  8982. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8983. worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact
  8984. worldNormal.negate(r.ni); // Normal pointing out of sphere
  8985. const penetrationVec2 = v3pool.get();
  8986. worldNormal.scale(-penetration, penetrationVec2);
  8987. const penetrationSpherePoint = v3pool.get();
  8988. worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  8989. xi.vsub(xj, r.rj);
  8990. r.rj.vadd(penetrationSpherePoint, r.rj);
  8991. r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body.
  8992. r.rj.vadd(xj, r.rj);
  8993. r.rj.vsub(bj.position, r.rj); // Should be relative to the body.
  8994. r.ri.vadd(xi, r.ri);
  8995. r.ri.vsub(bi.position, r.ri);
  8996. v3pool.release(penetrationVec2);
  8997. v3pool.release(penetrationSpherePoint);
  8998. this.result.push(r);
  8999. this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices
  9000. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9001. v3pool.release(faceVerts[j]);
  9002. }
  9003. return; // We only expect *one* face contact
  9004. } else {
  9005. // Edge?
  9006. for (let j = 0; j !== face.length; j++) {
  9007. // Get two world transformed vertices
  9008. const v1 = v3pool.get();
  9009. const v2 = v3pool.get();
  9010. qj.vmult(verts[face[(j + 1) % face.length]], v1);
  9011. qj.vmult(verts[face[(j + 2) % face.length]], v2);
  9012. xj.vadd(v1, v1);
  9013. xj.vadd(v2, v2); // Construct edge vector
  9014. const edge = sphereConvex_edge;
  9015. v2.vsub(v1, edge); // Construct the same vector, but normalized
  9016. const edgeUnit = sphereConvex_edgeUnit;
  9017. edge.unit(edgeUnit); // p is xi projected onto the edge
  9018. const p = v3pool.get();
  9019. const v1_to_xi = v3pool.get();
  9020. xi.vsub(v1, v1_to_xi);
  9021. const dot = v1_to_xi.dot(edgeUnit);
  9022. edgeUnit.scale(dot, p);
  9023. p.vadd(v1, p); // Compute a vector from p to the center of the sphere
  9024. const xi_to_p = v3pool.get();
  9025. p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius
  9026. // AND if p is in between v1 and v2
  9027. if (dot > 0 && dot * dot < edge.lengthSquared() && xi_to_p.lengthSquared() < R * R) {
  9028. // Collision if the edge-sphere distance is less than the radius
  9029. // Edge contact!
  9030. if (justTest) {
  9031. return true;
  9032. }
  9033. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9034. p.vsub(xj, r.rj);
  9035. p.vsub(xi, r.ni);
  9036. r.ni.normalize();
  9037. r.ni.scale(R, r.ri); // Should be relative to the body.
  9038. r.rj.vadd(xj, r.rj);
  9039. r.rj.vsub(bj.position, r.rj); // Should be relative to the body.
  9040. r.ri.vadd(xi, r.ri);
  9041. r.ri.vsub(bi.position, r.ri);
  9042. this.result.push(r);
  9043. this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices
  9044. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9045. v3pool.release(faceVerts[j]);
  9046. }
  9047. v3pool.release(v1);
  9048. v3pool.release(v2);
  9049. v3pool.release(p);
  9050. v3pool.release(xi_to_p);
  9051. v3pool.release(v1_to_xi);
  9052. return;
  9053. }
  9054. v3pool.release(v1);
  9055. v3pool.release(v2);
  9056. v3pool.release(p);
  9057. v3pool.release(xi_to_p);
  9058. v3pool.release(v1_to_xi);
  9059. }
  9060. } // Release world vertices
  9061. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9062. v3pool.release(faceVerts[j]);
  9063. }
  9064. }
  9065. }
  9066. }
  9067. planeConvex(planeShape, convexShape, planePosition, convexPosition, planeQuat, convexQuat, planeBody, convexBody, si, sj, justTest) {
  9068. // Simply return the points behind the plane.
  9069. const worldVertex = planeConvex_v;
  9070. const worldNormal = planeConvex_normal;
  9071. worldNormal.set(0, 0, 1);
  9072. planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation
  9073. let numContacts = 0;
  9074. const relpos = planeConvex_relpos;
  9075. for (let i = 0; i !== convexShape.vertices.length; i++) {
  9076. // Get world convex vertex
  9077. worldVertex.copy(convexShape.vertices[i]);
  9078. convexQuat.vmult(worldVertex, worldVertex);
  9079. convexPosition.vadd(worldVertex, worldVertex);
  9080. worldVertex.vsub(planePosition, relpos);
  9081. const dot = worldNormal.dot(relpos);
  9082. if (dot <= 0.0) {
  9083. if (justTest) {
  9084. return true;
  9085. }
  9086. const r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj); // Get vertex position projected on plane
  9087. const projected = planeConvex_projected;
  9088. worldNormal.scale(worldNormal.dot(relpos), projected);
  9089. worldVertex.vsub(projected, projected);
  9090. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  9091. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  9092. // rj is now just the vector from the convex center to the vertex
  9093. worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body
  9094. r.ri.vadd(planePosition, r.ri);
  9095. r.ri.vsub(planeBody.position, r.ri);
  9096. r.rj.vadd(convexPosition, r.rj);
  9097. r.rj.vsub(convexBody.position, r.rj);
  9098. this.result.push(r);
  9099. numContacts++;
  9100. if (!this.enableFrictionReduction) {
  9101. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9102. }
  9103. }
  9104. }
  9105. if (this.enableFrictionReduction && numContacts) {
  9106. this.createFrictionFromAverage(numContacts);
  9107. }
  9108. }
  9109. boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9110. si.convexPolyhedronRepresentation.material = si.material;
  9111. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9112. return this.convexConvex(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9113. }
  9114. sphereHeightfield(sphereShape, hfShape, spherePos, hfPos, sphereQuat, hfQuat, sphereBody, hfBody, rsi, rsj, justTest) {
  9115. const data = hfShape.data;
  9116. const radius = sphereShape.radius;
  9117. const w = hfShape.elementSize;
  9118. const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local!
  9119. const localSpherePos = sphereHeightfield_tmp1;
  9120. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against
  9121. let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1;
  9122. let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1;
  9123. let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1;
  9124. let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain
  9125. if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
  9126. return;
  9127. } // Clamp index to edges
  9128. if (iMinX < 0) {
  9129. iMinX = 0;
  9130. }
  9131. if (iMaxX < 0) {
  9132. iMaxX = 0;
  9133. }
  9134. if (iMinY < 0) {
  9135. iMinY = 0;
  9136. }
  9137. if (iMaxY < 0) {
  9138. iMaxY = 0;
  9139. }
  9140. if (iMinX >= data.length) {
  9141. iMinX = data.length - 1;
  9142. }
  9143. if (iMaxX >= data.length) {
  9144. iMaxX = data.length - 1;
  9145. }
  9146. if (iMaxY >= data[0].length) {
  9147. iMaxY = data[0].length - 1;
  9148. }
  9149. if (iMinY >= data[0].length) {
  9150. iMinY = data[0].length - 1;
  9151. }
  9152. const minMax = [];
  9153. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  9154. const min = minMax[0];
  9155. const max = minMax[1]; // Bail out if we can't touch the bounding height box
  9156. if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) {
  9157. return;
  9158. }
  9159. const result = this.result;
  9160. for (let i = iMinX; i < iMaxX; i++) {
  9161. for (let j = iMinY; j < iMaxY; j++) {
  9162. const numContactsBefore = result.length;
  9163. let intersecting = false; // Lower triangle
  9164. hfShape.getConvexTrianglePillar(i, j, false);
  9165. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9166. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  9167. intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
  9168. }
  9169. if (justTest && intersecting) {
  9170. return true;
  9171. } // Upper triangle
  9172. hfShape.getConvexTrianglePillar(i, j, true);
  9173. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9174. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  9175. intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
  9176. }
  9177. if (justTest && intersecting) {
  9178. return true;
  9179. }
  9180. const numContacts = result.length - numContactsBefore;
  9181. if (numContacts > 2) {
  9182. return;
  9183. }
  9184. /*
  9185. // Skip all but 1
  9186. for (let k = 0; k < numContacts - 1; k++) {
  9187. result.pop();
  9188. }
  9189. */
  9190. }
  9191. }
  9192. }
  9193. boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9194. si.convexPolyhedronRepresentation.material = si.material;
  9195. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9196. return this.convexHeightfield(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9197. }
  9198. convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest) {
  9199. const data = hfShape.data;
  9200. const w = hfShape.elementSize;
  9201. const radius = convexShape.boundingSphereRadius;
  9202. const worldPillarOffset = convexHeightfield_tmp2;
  9203. const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local!
  9204. const localConvexPos = convexHeightfield_tmp1;
  9205. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against
  9206. let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1;
  9207. let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1;
  9208. let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1;
  9209. let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain
  9210. if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
  9211. return;
  9212. } // Clamp index to edges
  9213. if (iMinX < 0) {
  9214. iMinX = 0;
  9215. }
  9216. if (iMaxX < 0) {
  9217. iMaxX = 0;
  9218. }
  9219. if (iMinY < 0) {
  9220. iMinY = 0;
  9221. }
  9222. if (iMaxY < 0) {
  9223. iMaxY = 0;
  9224. }
  9225. if (iMinX >= data.length) {
  9226. iMinX = data.length - 1;
  9227. }
  9228. if (iMaxX >= data.length) {
  9229. iMaxX = data.length - 1;
  9230. }
  9231. if (iMaxY >= data[0].length) {
  9232. iMaxY = data[0].length - 1;
  9233. }
  9234. if (iMinY >= data[0].length) {
  9235. iMinY = data[0].length - 1;
  9236. }
  9237. const minMax = [];
  9238. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  9239. const min = minMax[0];
  9240. const max = minMax[1]; // Bail out if we're cant touch the bounding height box
  9241. if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) {
  9242. return;
  9243. }
  9244. for (let i = iMinX; i < iMaxX; i++) {
  9245. for (let j = iMinY; j < iMaxY; j++) {
  9246. let intersecting = false; // Lower triangle
  9247. hfShape.getConvexTrianglePillar(i, j, false);
  9248. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9249. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  9250. intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
  9251. }
  9252. if (justTest && intersecting) {
  9253. return true;
  9254. } // Upper triangle
  9255. hfShape.getConvexTrianglePillar(i, j, true);
  9256. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9257. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  9258. intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
  9259. }
  9260. if (justTest && intersecting) {
  9261. return true;
  9262. }
  9263. }
  9264. }
  9265. }
  9266. sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9267. // The normal is the unit vector from sphere center to particle center
  9268. const normal = particleSphere_normal;
  9269. normal.set(0, 0, 1);
  9270. xi.vsub(xj, normal);
  9271. const lengthSquared = normal.lengthSquared();
  9272. if (lengthSquared <= sj.radius * sj.radius) {
  9273. if (justTest) {
  9274. return true;
  9275. }
  9276. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9277. normal.normalize();
  9278. r.rj.copy(normal);
  9279. r.rj.scale(sj.radius, r.rj);
  9280. r.ni.copy(normal); // Contact normal
  9281. r.ni.negate(r.ni);
  9282. r.ri.set(0, 0, 0); // Center of particle
  9283. this.result.push(r);
  9284. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9285. }
  9286. }
  9287. planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9288. const normal = particlePlane_normal;
  9289. normal.set(0, 0, 1);
  9290. bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation
  9291. const relpos = particlePlane_relpos;
  9292. xi.vsub(bj.position, relpos);
  9293. const dot = normal.dot(relpos);
  9294. if (dot <= 0.0) {
  9295. if (justTest) {
  9296. return true;
  9297. }
  9298. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9299. r.ni.copy(normal); // Contact normal is the plane normal
  9300. r.ni.negate(r.ni);
  9301. r.ri.set(0, 0, 0); // Center of particle
  9302. // Get particle position projected on plane
  9303. const projected = particlePlane_projected;
  9304. normal.scale(normal.dot(xi), projected);
  9305. xi.vsub(projected, projected); //projected.vadd(bj.position,projected);
  9306. // rj is now the projected world position minus plane position
  9307. r.rj.copy(projected);
  9308. this.result.push(r);
  9309. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9310. }
  9311. }
  9312. boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9313. si.convexPolyhedronRepresentation.material = si.material;
  9314. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9315. return this.convexParticle(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9316. }
  9317. convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9318. let penetratedFaceIndex = -1;
  9319. const penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  9320. const worldPenetrationVec = convexParticle_worldPenetrationVec;
  9321. let minPenetration = null;
  9322. const local = convexParticle_local;
  9323. local.copy(xi);
  9324. local.vsub(xj, local); // Convert position to relative the convex origin
  9325. qj.conjugate(cqj);
  9326. cqj.vmult(local, local);
  9327. if (sj.pointIsInside(local)) {
  9328. if (sj.worldVerticesNeedsUpdate) {
  9329. sj.computeWorldVertices(xj, qj);
  9330. }
  9331. if (sj.worldFaceNormalsNeedsUpdate) {
  9332. sj.computeWorldFaceNormals(qj);
  9333. } // For each world polygon in the polyhedra
  9334. for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) {
  9335. // Construct world face vertices
  9336. const verts = [sj.worldVertices[sj.faces[i][0]]];
  9337. const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane.
  9338. xi.vsub(verts[0], convexParticle_vertexToParticle);
  9339. const penetration = -normal.dot(convexParticle_vertexToParticle);
  9340. if (minPenetration === null || Math.abs(penetration) < Math.abs(minPenetration)) {
  9341. if (justTest) {
  9342. return true;
  9343. }
  9344. minPenetration = penetration;
  9345. penetratedFaceIndex = i;
  9346. penetratedFaceNormal.copy(normal);
  9347. }
  9348. }
  9349. if (penetratedFaceIndex !== -1) {
  9350. // Setup contact
  9351. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9352. penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face
  9353. worldPenetrationVec.vadd(xi, worldPenetrationVec);
  9354. worldPenetrationVec.vsub(xj, worldPenetrationVec);
  9355. r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  9356. //projectedToFace.copy(r.rj);
  9357. //qj.vmult(r.rj,r.rj);
  9358. penetratedFaceNormal.negate(r.ni); // Contact normal
  9359. r.ri.set(0, 0, 0); // Center of particle
  9360. const ri = r.ri;
  9361. const rj = r.rj; // Make relative to bodies
  9362. ri.vadd(xi, ri);
  9363. ri.vsub(bi.position, ri);
  9364. rj.vadd(xj, rj);
  9365. rj.vsub(bj.position, rj);
  9366. this.result.push(r);
  9367. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9368. } else {
  9369. console.warn('Point found inside convex, but did not find penetrating face!');
  9370. }
  9371. }
  9372. }
  9373. heightfieldCylinder(hfShape, convexShape, hfPos, convexPos, hfQuat, convexQuat, hfBody, convexBody, rsi, rsj, justTest) {
  9374. return this.convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest);
  9375. }
  9376. particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9377. return this.convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest);
  9378. }
  9379. sphereTrimesh(sphereShape, trimeshShape, spherePos, trimeshPos, sphereQuat, trimeshQuat, sphereBody, trimeshBody, rsi, rsj, justTest) {
  9380. const edgeVertexA = sphereTrimesh_edgeVertexA;
  9381. const edgeVertexB = sphereTrimesh_edgeVertexB;
  9382. const edgeVector = sphereTrimesh_edgeVector;
  9383. const edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  9384. const localSpherePos = sphereTrimesh_localSpherePos;
  9385. const tmp = sphereTrimesh_tmp;
  9386. const localSphereAABB = sphereTrimesh_localSphereAABB;
  9387. const v2 = sphereTrimesh_v2;
  9388. const relpos = sphereTrimesh_relpos;
  9389. const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh
  9390. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos); // Get the aabb of the sphere locally in the trimesh
  9391. const sphereRadius = sphereShape.radius;
  9392. localSphereAABB.lowerBound.set(localSpherePos.x - sphereRadius, localSpherePos.y - sphereRadius, localSpherePos.z - sphereRadius);
  9393. localSphereAABB.upperBound.set(localSpherePos.x + sphereRadius, localSpherePos.y + sphereRadius, localSpherePos.z + sphereRadius);
  9394. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  9395. // Vertices
  9396. const v = sphereTrimesh_v;
  9397. const radiusSquared = sphereShape.radius * sphereShape.radius;
  9398. for (let i = 0; i < triangles.length; i++) {
  9399. for (let j = 0; j < 3; j++) {
  9400. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere
  9401. v.vsub(localSpherePos, relpos);
  9402. if (relpos.lengthSquared() <= radiusSquared) {
  9403. // Safe up
  9404. v2.copy(v);
  9405. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  9406. v.vsub(spherePos, relpos);
  9407. if (justTest) {
  9408. return true;
  9409. }
  9410. let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9411. r.ni.copy(relpos);
  9412. r.ni.normalize(); // ri is the vector from sphere center to the sphere surface
  9413. r.ri.copy(r.ni);
  9414. r.ri.scale(sphereShape.radius, r.ri);
  9415. r.ri.vadd(spherePos, r.ri);
  9416. r.ri.vsub(sphereBody.position, r.ri);
  9417. r.rj.copy(v);
  9418. r.rj.vsub(trimeshBody.position, r.rj); // Store result
  9419. this.result.push(r);
  9420. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9421. }
  9422. }
  9423. } // Check all edges
  9424. for (let i = 0; i < triangles.length; i++) {
  9425. for (let j = 0; j < 3; j++) {
  9426. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  9427. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + (j + 1) % 3], edgeVertexB);
  9428. edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge
  9429. localSpherePos.vsub(edgeVertexB, tmp);
  9430. const positionAlongEdgeB = tmp.dot(edgeVector);
  9431. localSpherePos.vsub(edgeVertexA, tmp);
  9432. let positionAlongEdgeA = tmp.dot(edgeVector);
  9433. if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) {
  9434. // Now check the orthogonal distance from edge to sphere center
  9435. localSpherePos.vsub(edgeVertexA, tmp);
  9436. edgeVectorUnit.copy(edgeVector);
  9437. edgeVectorUnit.normalize();
  9438. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  9439. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  9440. tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  9441. const dist = tmp.distanceTo(localSpherePos);
  9442. if (dist < sphereShape.radius) {
  9443. if (justTest) {
  9444. return true;
  9445. }
  9446. const r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9447. tmp.vsub(localSpherePos, r.ni);
  9448. r.ni.normalize();
  9449. r.ni.scale(sphereShape.radius, r.ri);
  9450. r.ri.vadd(spherePos, r.ri);
  9451. r.ri.vsub(sphereBody.position, r.ri);
  9452. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  9453. tmp.vsub(trimeshBody.position, r.rj);
  9454. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  9455. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  9456. this.result.push(r);
  9457. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9458. }
  9459. }
  9460. }
  9461. } // Triangle faces
  9462. const va = sphereTrimesh_va;
  9463. const vb = sphereTrimesh_vb;
  9464. const vc = sphereTrimesh_vc;
  9465. const normal = sphereTrimesh_normal;
  9466. for (let i = 0, N = triangles.length; i !== N; i++) {
  9467. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  9468. trimeshShape.getNormal(triangles[i], normal);
  9469. localSpherePos.vsub(va, tmp);
  9470. let dist = tmp.dot(normal);
  9471. normal.scale(dist, tmp);
  9472. localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane
  9473. dist = tmp.distanceTo(localSpherePos);
  9474. if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) {
  9475. if (justTest) {
  9476. return true;
  9477. }
  9478. let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9479. tmp.vsub(localSpherePos, r.ni);
  9480. r.ni.normalize();
  9481. r.ni.scale(sphereShape.radius, r.ri);
  9482. r.ri.vadd(spherePos, r.ri);
  9483. r.ri.vsub(sphereBody.position, r.ri);
  9484. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  9485. tmp.vsub(trimeshBody.position, r.rj);
  9486. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  9487. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  9488. this.result.push(r);
  9489. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9490. }
  9491. }
  9492. triangles.length = 0;
  9493. }
  9494. planeTrimesh(planeShape, trimeshShape, planePos, trimeshPos, planeQuat, trimeshQuat, planeBody, trimeshBody, rsi, rsj, justTest) {
  9495. // Make contacts!
  9496. const v = new Vec3();
  9497. const normal = planeTrimesh_normal;
  9498. normal.set(0, 0, 1);
  9499. planeQuat.vmult(normal, normal); // Turn normal according to plane
  9500. for (let i = 0; i < trimeshShape.vertices.length / 3; i++) {
  9501. // Get world vertex from trimesh
  9502. trimeshShape.getVertex(i, v); // Safe up
  9503. const v2 = new Vec3();
  9504. v2.copy(v);
  9505. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side
  9506. const relpos = planeTrimesh_relpos;
  9507. v.vsub(planePos, relpos);
  9508. const dot = normal.dot(relpos);
  9509. if (dot <= 0.0) {
  9510. if (justTest) {
  9511. return true;
  9512. }
  9513. const r = this.createContactEquation(planeBody, trimeshBody, planeShape, trimeshShape, rsi, rsj);
  9514. r.ni.copy(normal); // Contact normal is the plane normal
  9515. // Get vertex position projected on plane
  9516. const projected = planeTrimesh_projected;
  9517. normal.scale(relpos.dot(normal), projected);
  9518. v.vsub(projected, projected); // ri is the projected world position minus plane position
  9519. r.ri.copy(projected);
  9520. r.ri.vsub(planeBody.position, r.ri);
  9521. r.rj.copy(v);
  9522. r.rj.vsub(trimeshBody.position, r.rj); // Store result
  9523. this.result.push(r);
  9524. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9525. }
  9526. }
  9527. } // convexTrimesh(
  9528. // si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion,
  9529. // bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null,
  9530. // faceListA?: number[] | null, faceListB?: number[] | null,
  9531. // ) {
  9532. // const sepAxis = convexConvex_sepAxis;
  9533. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  9534. // return;
  9535. // }
  9536. // // Construct a temp hull for each triangle
  9537. // const hullB = new ConvexPolyhedron();
  9538. // hullB.faces = [[0,1,2]];
  9539. // const va = new Vec3();
  9540. // const vb = new Vec3();
  9541. // const vc = new Vec3();
  9542. // hullB.vertices = [
  9543. // va,
  9544. // vb,
  9545. // vc
  9546. // ];
  9547. // for (let i = 0; i < sj.indices.length / 3; i++) {
  9548. // const triangleNormal = new Vec3();
  9549. // sj.getNormal(i, triangleNormal);
  9550. // hullB.faceNormals = [triangleNormal];
  9551. // sj.getTriangleVertices(i, va, vb, vc);
  9552. // let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  9553. // if(!d){
  9554. // triangleNormal.scale(-1, triangleNormal);
  9555. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  9556. // if(!d){
  9557. // continue;
  9558. // }
  9559. // }
  9560. // const res: ConvexPolyhedronContactPoint[] = [];
  9561. // const q = convexConvex_q;
  9562. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  9563. // for(let j = 0; j !== res.length; j++){
  9564. // const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  9565. // ri = r.ri,
  9566. // rj = r.rj;
  9567. // r.ni.copy(triangleNormal);
  9568. // r.ni.negate(r.ni);
  9569. // res[j].normal.negate(q);
  9570. // q.mult(res[j].depth, q);
  9571. // res[j].point.vadd(q, ri);
  9572. // rj.copy(res[j].point);
  9573. // // Contact points are in world coordinates. Transform back to relative
  9574. // ri.vsub(xi,ri);
  9575. // rj.vsub(xj,rj);
  9576. // // Make relative to bodies
  9577. // ri.vadd(xi, ri);
  9578. // ri.vsub(bi.position, ri);
  9579. // rj.vadd(xj, rj);
  9580. // rj.vsub(bj.position, rj);
  9581. // result.push(r);
  9582. // }
  9583. // }
  9584. // }
  9585. }
  9586. const averageNormal = new Vec3();
  9587. const averageContactPointA = new Vec3();
  9588. const averageContactPointB = new Vec3();
  9589. const tmpVec1 = new Vec3();
  9590. const tmpVec2 = new Vec3();
  9591. const tmpQuat1 = new Quaternion();
  9592. const tmpQuat2 = new Quaternion();
  9593. const planeTrimesh_normal = new Vec3();
  9594. const planeTrimesh_relpos = new Vec3();
  9595. const planeTrimesh_projected = new Vec3();
  9596. const sphereTrimesh_normal = new Vec3();
  9597. const sphereTrimesh_relpos = new Vec3();
  9598. new Vec3();
  9599. const sphereTrimesh_v = new Vec3();
  9600. const sphereTrimesh_v2 = new Vec3();
  9601. const sphereTrimesh_edgeVertexA = new Vec3();
  9602. const sphereTrimesh_edgeVertexB = new Vec3();
  9603. const sphereTrimesh_edgeVector = new Vec3();
  9604. const sphereTrimesh_edgeVectorUnit = new Vec3();
  9605. const sphereTrimesh_localSpherePos = new Vec3();
  9606. const sphereTrimesh_tmp = new Vec3();
  9607. const sphereTrimesh_va = new Vec3();
  9608. const sphereTrimesh_vb = new Vec3();
  9609. const sphereTrimesh_vc = new Vec3();
  9610. const sphereTrimesh_localSphereAABB = new AABB();
  9611. const sphereTrimesh_triangles = [];
  9612. const point_on_plane_to_sphere = new Vec3();
  9613. const plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  9614. const pointInPolygon_edge = new Vec3();
  9615. const pointInPolygon_edge_x_normal = new Vec3();
  9616. const pointInPolygon_vtp = new Vec3();
  9617. function pointInPolygon(verts, normal, p) {
  9618. let positiveResult = null;
  9619. const N = verts.length;
  9620. for (let i = 0; i !== N; i++) {
  9621. const v = verts[i]; // Get edge to the next vertex
  9622. const edge = pointInPolygon_edge;
  9623. verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge
  9624. const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3();
  9625. edge.cross(normal, edge_x_normal); // Get vector between point and current vertex
  9626. const vertex_to_p = pointInPolygon_vtp;
  9627. p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is
  9628. const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon.
  9629. if (positiveResult === null || r > 0 && positiveResult === true || r <= 0 && positiveResult === false) {
  9630. if (positiveResult === null) {
  9631. positiveResult = r > 0;
  9632. }
  9633. continue;
  9634. } else {
  9635. return false; // Encountered some other sign. Exit.
  9636. }
  9637. } // If we got here, all dot products were of the same sign.
  9638. return true;
  9639. }
  9640. const box_to_sphere = new Vec3();
  9641. const sphereBox_ns = new Vec3();
  9642. const sphereBox_ns1 = new Vec3();
  9643. const sphereBox_ns2 = new Vec3();
  9644. const sphereBox_sides = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  9645. const sphereBox_sphere_to_corner = new Vec3();
  9646. const sphereBox_side_ns = new Vec3();
  9647. const sphereBox_side_ns1 = new Vec3();
  9648. const sphereBox_side_ns2 = new Vec3();
  9649. const convex_to_sphere = new Vec3();
  9650. const sphereConvex_edge = new Vec3();
  9651. const sphereConvex_edgeUnit = new Vec3();
  9652. const sphereConvex_sphereToCorner = new Vec3();
  9653. const sphereConvex_worldCorner = new Vec3();
  9654. const sphereConvex_worldNormal = new Vec3();
  9655. const sphereConvex_worldPoint = new Vec3();
  9656. const sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  9657. const sphereConvex_penetrationVec = new Vec3();
  9658. const sphereConvex_sphereToWorldPoint = new Vec3();
  9659. new Vec3();
  9660. new Vec3();
  9661. const planeConvex_v = new Vec3();
  9662. const planeConvex_normal = new Vec3();
  9663. const planeConvex_relpos = new Vec3();
  9664. const planeConvex_projected = new Vec3();
  9665. const convexConvex_sepAxis = new Vec3();
  9666. const convexConvex_q = new Vec3();
  9667. const particlePlane_normal = new Vec3();
  9668. const particlePlane_relpos = new Vec3();
  9669. const particlePlane_projected = new Vec3();
  9670. const particleSphere_normal = new Vec3(); // WIP
  9671. const cqj = new Quaternion();
  9672. const convexParticle_local = new Vec3();
  9673. new Vec3();
  9674. const convexParticle_penetratedFaceNormal = new Vec3();
  9675. const convexParticle_vertexToParticle = new Vec3();
  9676. const convexParticle_worldPenetrationVec = new Vec3();
  9677. const convexHeightfield_tmp1 = new Vec3();
  9678. const convexHeightfield_tmp2 = new Vec3();
  9679. const convexHeightfield_faceList = [0];
  9680. const sphereHeightfield_tmp1 = new Vec3();
  9681. const sphereHeightfield_tmp2 = new Vec3();
  9682. class OverlapKeeper {
  9683. /**
  9684. * @todo Remove useless constructor
  9685. */
  9686. constructor() {
  9687. this.current = [];
  9688. this.previous = [];
  9689. }
  9690. /**
  9691. * getKey
  9692. */
  9693. getKey(i, j) {
  9694. if (j < i) {
  9695. const temp = j;
  9696. j = i;
  9697. i = temp;
  9698. }
  9699. return i << 16 | j;
  9700. }
  9701. /**
  9702. * set
  9703. */
  9704. set(i, j) {
  9705. // Insertion sort. This way the diff will have linear complexity.
  9706. const key = this.getKey(i, j);
  9707. const current = this.current;
  9708. let index = 0;
  9709. while (key > current[index]) {
  9710. index++;
  9711. }
  9712. if (key === current[index]) {
  9713. return; // Pair was already added
  9714. }
  9715. for (let j = current.length - 1; j >= index; j--) {
  9716. current[j + 1] = current[j];
  9717. }
  9718. current[index] = key;
  9719. }
  9720. /**
  9721. * tick
  9722. */
  9723. tick() {
  9724. const tmp = this.current;
  9725. this.current = this.previous;
  9726. this.previous = tmp;
  9727. this.current.length = 0;
  9728. }
  9729. /**
  9730. * getDiff
  9731. */
  9732. getDiff(additions, removals) {
  9733. const a = this.current;
  9734. const b = this.previous;
  9735. const al = a.length;
  9736. const bl = b.length;
  9737. let j = 0;
  9738. for (let i = 0; i < al; i++) {
  9739. let found = false;
  9740. const keyA = a[i];
  9741. while (keyA > b[j]) {
  9742. j++;
  9743. }
  9744. found = keyA === b[j];
  9745. if (!found) {
  9746. unpackAndPush(additions, keyA);
  9747. }
  9748. }
  9749. j = 0;
  9750. for (let i = 0; i < bl; i++) {
  9751. let found = false;
  9752. const keyB = b[i];
  9753. while (keyB > a[j]) {
  9754. j++;
  9755. }
  9756. found = a[j] === keyB;
  9757. if (!found) {
  9758. unpackAndPush(removals, keyB);
  9759. }
  9760. }
  9761. }
  9762. }
  9763. function unpackAndPush(array, key) {
  9764. array.push((key & 0xffff0000) >> 16, key & 0x0000ffff);
  9765. }
  9766. const getKey = (i, j) => i < j ? `${i}-${j}` : `${j}-${i}`;
  9767. /**
  9768. * TupleDictionary
  9769. */
  9770. class TupleDictionary {
  9771. constructor() {
  9772. this.data = {
  9773. keys: []
  9774. };
  9775. }
  9776. /** get */
  9777. get(i, j) {
  9778. const key = getKey(i, j);
  9779. return this.data[key];
  9780. }
  9781. /** set */
  9782. set(i, j, value) {
  9783. const key = getKey(i, j); // Check if key already exists
  9784. if (!this.get(i, j)) {
  9785. this.data.keys.push(key);
  9786. }
  9787. this.data[key] = value;
  9788. }
  9789. /** delete */
  9790. delete(i, j) {
  9791. const key = getKey(i, j);
  9792. const index = this.data.keys.indexOf(key);
  9793. if (index !== -1) {
  9794. this.data.keys.splice(index, 1);
  9795. }
  9796. delete this.data[key];
  9797. }
  9798. /** reset */
  9799. reset() {
  9800. const data = this.data;
  9801. const keys = data.keys;
  9802. while (keys.length > 0) {
  9803. const key = keys.pop();
  9804. delete data[key];
  9805. }
  9806. }
  9807. }
  9808. /**
  9809. * The physics world
  9810. */
  9811. class World extends EventTarget {
  9812. /**
  9813. * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
  9814. */
  9815. /**
  9816. * Makes bodies go to sleep when they've been inactive.
  9817. * @default false
  9818. */
  9819. /**
  9820. * All the current contacts (instances of ContactEquation) in the world.
  9821. */
  9822. /**
  9823. * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
  9824. * @default 0
  9825. */
  9826. /**
  9827. * Set to true to use fast quaternion normalization. It is often enough accurate to use.
  9828. * If bodies tend to explode, set to false.
  9829. * @default false
  9830. */
  9831. /**
  9832. * The wall-clock time since simulation start.
  9833. */
  9834. /**
  9835. * Number of timesteps taken since start.
  9836. */
  9837. /**
  9838. * Default and last timestep sizes.
  9839. */
  9840. /**
  9841. * The gravity of the world.
  9842. */
  9843. /**
  9844. * Gravity to use when approximating the friction max force (mu*mass*gravity).
  9845. * If undefined, global gravity will be used.
  9846. * Use to enable friction in a World with a null gravity vector (no gravity).
  9847. */
  9848. /**
  9849. * The broadphase algorithm to use.
  9850. * @default NaiveBroadphase
  9851. */
  9852. /**
  9853. * All bodies in this world
  9854. */
  9855. /**
  9856. * True if any bodies are not sleeping, false if every body is sleeping.
  9857. */
  9858. /**
  9859. * The solver algorithm to use.
  9860. * @default GSSolver
  9861. */
  9862. /**
  9863. * collisionMatrix
  9864. */
  9865. /**
  9866. * CollisionMatrix from the previous step.
  9867. */
  9868. /**
  9869. * All added contactmaterials.
  9870. */
  9871. /**
  9872. * Used to look up a ContactMaterial given two instances of Material.
  9873. */
  9874. /**
  9875. * The default material of the bodies.
  9876. */
  9877. /**
  9878. * This contact material is used if no suitable contactmaterial is found for a contact.
  9879. */
  9880. /**
  9881. * Time accumulator for interpolation.
  9882. * @see https://gafferongames.com/game-physics/fix-your-timestep/
  9883. */
  9884. /**
  9885. * Dispatched after a body has been added to the world.
  9886. */
  9887. /**
  9888. * Dispatched after a body has been removed from the world.
  9889. */
  9890. constructor(options) {
  9891. if (options === void 0) {
  9892. options = {};
  9893. }
  9894. super();
  9895. this.dt = -1;
  9896. this.allowSleep = !!options.allowSleep;
  9897. this.contacts = [];
  9898. this.frictionEquations = [];
  9899. this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;
  9900. this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;
  9901. this.time = 0.0;
  9902. this.stepnumber = 0;
  9903. this.default_dt = 1 / 60;
  9904. this.nextId = 0;
  9905. this.gravity = new Vec3();
  9906. if (options.gravity) {
  9907. this.gravity.copy(options.gravity);
  9908. }
  9909. if (options.frictionGravity) {
  9910. this.frictionGravity = new Vec3();
  9911. this.frictionGravity.copy(options.frictionGravity);
  9912. }
  9913. this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();
  9914. this.bodies = [];
  9915. this.hasActiveBodies = false;
  9916. this.solver = options.solver !== undefined ? options.solver : new GSSolver();
  9917. this.constraints = [];
  9918. this.narrowphase = new Narrowphase(this);
  9919. this.collisionMatrix = new ArrayCollisionMatrix();
  9920. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  9921. this.bodyOverlapKeeper = new OverlapKeeper();
  9922. this.shapeOverlapKeeper = new OverlapKeeper();
  9923. this.contactmaterials = [];
  9924. this.contactMaterialTable = new TupleDictionary();
  9925. this.defaultMaterial = new Material('default');
  9926. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, {
  9927. friction: 0.3,
  9928. restitution: 0.0
  9929. });
  9930. this.doProfiling = false;
  9931. this.profile = {
  9932. solve: 0,
  9933. makeContactConstraints: 0,
  9934. broadphase: 0,
  9935. integrate: 0,
  9936. narrowphase: 0
  9937. };
  9938. this.accumulator = 0;
  9939. this.subsystems = [];
  9940. this.addBodyEvent = {
  9941. type: 'addBody',
  9942. body: null
  9943. };
  9944. this.removeBodyEvent = {
  9945. type: 'removeBody',
  9946. body: null
  9947. };
  9948. this.idToBodyMap = {};
  9949. this.broadphase.setWorld(this);
  9950. }
  9951. /**
  9952. * Get the contact material between materials m1 and m2
  9953. * @return The contact material if it was found.
  9954. */
  9955. getContactMaterial(m1, m2) {
  9956. return this.contactMaterialTable.get(m1.id, m2.id);
  9957. }
  9958. /**
  9959. * Store old collision state info
  9960. */
  9961. collisionMatrixTick() {
  9962. const temp = this.collisionMatrixPrevious;
  9963. this.collisionMatrixPrevious = this.collisionMatrix;
  9964. this.collisionMatrix = temp;
  9965. this.collisionMatrix.reset();
  9966. this.bodyOverlapKeeper.tick();
  9967. this.shapeOverlapKeeper.tick();
  9968. }
  9969. /**
  9970. * Add a constraint to the simulation.
  9971. */
  9972. addConstraint(c) {
  9973. this.constraints.push(c);
  9974. }
  9975. /**
  9976. * Removes a constraint
  9977. */
  9978. removeConstraint(c) {
  9979. const idx = this.constraints.indexOf(c);
  9980. if (idx !== -1) {
  9981. this.constraints.splice(idx, 1);
  9982. }
  9983. }
  9984. /**
  9985. * Raycast test
  9986. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  9987. */
  9988. rayTest(from, to, result) {
  9989. if (result instanceof RaycastResult) {
  9990. // Do raycastClosest
  9991. this.raycastClosest(from, to, {
  9992. skipBackfaces: true
  9993. }, result);
  9994. } else {
  9995. // Do raycastAll
  9996. this.raycastAll(from, to, {
  9997. skipBackfaces: true
  9998. }, result);
  9999. }
  10000. }
  10001. /**
  10002. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  10003. * @return True if any body was hit.
  10004. */
  10005. raycastAll(from, to, options, callback) {
  10006. if (options === void 0) {
  10007. options = {};
  10008. }
  10009. options.mode = Ray.ALL;
  10010. options.from = from;
  10011. options.to = to;
  10012. options.callback = callback;
  10013. return tmpRay.intersectWorld(this, options);
  10014. }
  10015. /**
  10016. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  10017. * @return True if any body was hit.
  10018. */
  10019. raycastAny(from, to, options, result) {
  10020. if (options === void 0) {
  10021. options = {};
  10022. }
  10023. options.mode = Ray.ANY;
  10024. options.from = from;
  10025. options.to = to;
  10026. options.result = result;
  10027. return tmpRay.intersectWorld(this, options);
  10028. }
  10029. /**
  10030. * Ray cast, and return information of the closest hit.
  10031. * @return True if any body was hit.
  10032. */
  10033. raycastClosest(from, to, options, result) {
  10034. if (options === void 0) {
  10035. options = {};
  10036. }
  10037. options.mode = Ray.CLOSEST;
  10038. options.from = from;
  10039. options.to = to;
  10040. options.result = result;
  10041. return tmpRay.intersectWorld(this, options);
  10042. }
  10043. /**
  10044. * Add a rigid body to the simulation.
  10045. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  10046. * @todo Adding an array of bodies should be possible. This would save some loops too
  10047. */
  10048. addBody(body) {
  10049. if (this.bodies.includes(body)) {
  10050. return;
  10051. }
  10052. body.index = this.bodies.length;
  10053. this.bodies.push(body);
  10054. body.world = this;
  10055. body.initPosition.copy(body.position);
  10056. body.initVelocity.copy(body.velocity);
  10057. body.timeLastSleepy = this.time;
  10058. if (body instanceof Body) {
  10059. body.initAngularVelocity.copy(body.angularVelocity);
  10060. body.initQuaternion.copy(body.quaternion);
  10061. }
  10062. this.collisionMatrix.setNumObjects(this.bodies.length);
  10063. this.addBodyEvent.body = body;
  10064. this.idToBodyMap[body.id] = body;
  10065. this.dispatchEvent(this.addBodyEvent);
  10066. }
  10067. /**
  10068. * Remove a rigid body from the simulation.
  10069. */
  10070. removeBody(body) {
  10071. body.world = null;
  10072. const n = this.bodies.length - 1;
  10073. const bodies = this.bodies;
  10074. const idx = bodies.indexOf(body);
  10075. if (idx !== -1) {
  10076. bodies.splice(idx, 1); // Todo: should use a garbage free method
  10077. // Recompute index
  10078. for (let i = 0; i !== bodies.length; i++) {
  10079. bodies[i].index = i;
  10080. }
  10081. this.collisionMatrix.setNumObjects(n);
  10082. this.removeBodyEvent.body = body;
  10083. delete this.idToBodyMap[body.id];
  10084. this.dispatchEvent(this.removeBodyEvent);
  10085. }
  10086. }
  10087. getBodyById(id) {
  10088. return this.idToBodyMap[id];
  10089. }
  10090. /**
  10091. * @todo Make a faster map
  10092. */
  10093. getShapeById(id) {
  10094. const bodies = this.bodies;
  10095. for (let i = 0; i < bodies.length; i++) {
  10096. const shapes = bodies[i].shapes;
  10097. for (let j = 0; j < shapes.length; j++) {
  10098. const shape = shapes[j];
  10099. if (shape.id === id) {
  10100. return shape;
  10101. }
  10102. }
  10103. }
  10104. return null;
  10105. }
  10106. /**
  10107. * Adds a contact material to the World
  10108. */
  10109. addContactMaterial(cmat) {
  10110. // Add contact material
  10111. this.contactmaterials.push(cmat); // Add current contact material to the material table
  10112. this.contactMaterialTable.set(cmat.materials[0].id, cmat.materials[1].id, cmat);
  10113. }
  10114. /**
  10115. * Removes a contact material from the World.
  10116. */
  10117. removeContactMaterial(cmat) {
  10118. const idx = this.contactmaterials.indexOf(cmat);
  10119. if (idx === -1) {
  10120. return;
  10121. }
  10122. this.contactmaterials.splice(idx, 1);
  10123. this.contactMaterialTable.delete(cmat.materials[0].id, cmat.materials[1].id);
  10124. }
  10125. /**
  10126. * Step the simulation forward keeping track of last called time
  10127. * to be able to step the world at a fixed rate, independently of framerate.
  10128. *
  10129. * @param dt The fixed time step size to use (default: 1 / 60).
  10130. * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).
  10131. * @see https://gafferongames.com/post/fix_your_timestep/
  10132. * @example
  10133. * // Run the simulation independently of framerate every 1 / 60 ms
  10134. * world.fixedStep()
  10135. */
  10136. fixedStep(dt, maxSubSteps) {
  10137. if (dt === void 0) {
  10138. dt = 1 / 60;
  10139. }
  10140. if (maxSubSteps === void 0) {
  10141. maxSubSteps = 10;
  10142. }
  10143. const time = performance.now() / 1000; // seconds
  10144. if (!this.lastCallTime) {
  10145. this.step(dt, undefined, maxSubSteps);
  10146. } else {
  10147. const timeSinceLastCalled = time - this.lastCallTime;
  10148. this.step(dt, timeSinceLastCalled, maxSubSteps);
  10149. }
  10150. this.lastCallTime = time;
  10151. }
  10152. /**
  10153. * Step the physics world forward in time.
  10154. *
  10155. * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
  10156. *
  10157. * @param dt The fixed time step size to use.
  10158. * @param timeSinceLastCalled The time elapsed since the function was last called.
  10159. * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).
  10160. * @see https://web.archive.org/web/20180426154531/http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World#What_do_the_parameters_to_btDynamicsWorld::stepSimulation_mean.3F
  10161. * @example
  10162. * // fixed timestepping without interpolation
  10163. * world.step(1 / 60)
  10164. */
  10165. step(dt, timeSinceLastCalled, maxSubSteps) {
  10166. if (maxSubSteps === void 0) {
  10167. maxSubSteps = 10;
  10168. }
  10169. if (timeSinceLastCalled === undefined) {
  10170. // Fixed, simple stepping
  10171. this.internalStep(dt); // Increment time
  10172. this.time += dt;
  10173. } else {
  10174. this.accumulator += timeSinceLastCalled;
  10175. const t0 = performance.now();
  10176. let substeps = 0;
  10177. while (this.accumulator >= dt && substeps < maxSubSteps) {
  10178. // Do fixed steps to catch up
  10179. this.internalStep(dt);
  10180. this.accumulator -= dt;
  10181. substeps++;
  10182. if (performance.now() - t0 > dt * 1000) {
  10183. // The framerate is not interactive anymore.
  10184. // We are below the target framerate.
  10185. // Better bail out.
  10186. break;
  10187. }
  10188. } // Remove the excess accumulator, since we may not
  10189. // have had enough substeps available to catch up
  10190. this.accumulator = this.accumulator % dt;
  10191. const t = this.accumulator / dt;
  10192. for (let j = 0; j !== this.bodies.length; j++) {
  10193. const b = this.bodies[j];
  10194. b.previousPosition.lerp(b.position, t, b.interpolatedPosition);
  10195. b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);
  10196. b.previousQuaternion.normalize();
  10197. }
  10198. this.time += timeSinceLastCalled;
  10199. }
  10200. }
  10201. internalStep(dt) {
  10202. this.dt = dt;
  10203. const contacts = this.contacts;
  10204. const p1 = World_step_p1;
  10205. const p2 = World_step_p2;
  10206. const N = this.bodies.length;
  10207. const bodies = this.bodies;
  10208. const solver = this.solver;
  10209. const gravity = this.gravity;
  10210. const doProfiling = this.doProfiling;
  10211. const profile = this.profile;
  10212. const DYNAMIC = Body.DYNAMIC;
  10213. let profilingStart = -Infinity;
  10214. const constraints = this.constraints;
  10215. const frictionEquationPool = World_step_frictionEquationPool;
  10216. gravity.length();
  10217. const gx = gravity.x;
  10218. const gy = gravity.y;
  10219. const gz = gravity.z;
  10220. let i = 0;
  10221. if (doProfiling) {
  10222. profilingStart = performance.now();
  10223. } // Add gravity to all objects
  10224. for (i = 0; i !== N; i++) {
  10225. const bi = bodies[i];
  10226. if (bi.type === DYNAMIC) {
  10227. // Only for dynamic bodies
  10228. const f = bi.force;
  10229. const m = bi.mass;
  10230. f.x += m * gx;
  10231. f.y += m * gy;
  10232. f.z += m * gz;
  10233. }
  10234. } // Update subsystems
  10235. for (let i = 0, Nsubsystems = this.subsystems.length; i !== Nsubsystems; i++) {
  10236. this.subsystems[i].update();
  10237. } // Collision detection
  10238. if (doProfiling) {
  10239. profilingStart = performance.now();
  10240. }
  10241. p1.length = 0; // Clean up pair arrays from last step
  10242. p2.length = 0;
  10243. this.broadphase.collisionPairs(this, p1, p2);
  10244. if (doProfiling) {
  10245. profile.broadphase = performance.now() - profilingStart;
  10246. } // Remove constrained pairs with collideConnected == false
  10247. let Nconstraints = constraints.length;
  10248. for (i = 0; i !== Nconstraints; i++) {
  10249. const c = constraints[i];
  10250. if (!c.collideConnected) {
  10251. for (let j = p1.length - 1; j >= 0; j -= 1) {
  10252. if (c.bodyA === p1[j] && c.bodyB === p2[j] || c.bodyB === p1[j] && c.bodyA === p2[j]) {
  10253. p1.splice(j, 1);
  10254. p2.splice(j, 1);
  10255. }
  10256. }
  10257. }
  10258. }
  10259. this.collisionMatrixTick(); // Generate contacts
  10260. if (doProfiling) {
  10261. profilingStart = performance.now();
  10262. }
  10263. const oldcontacts = World_step_oldContacts;
  10264. const NoldContacts = contacts.length;
  10265. for (i = 0; i !== NoldContacts; i++) {
  10266. oldcontacts.push(contacts[i]);
  10267. }
  10268. contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse
  10269. const NoldFrictionEquations = this.frictionEquations.length;
  10270. for (i = 0; i !== NoldFrictionEquations; i++) {
  10271. frictionEquationPool.push(this.frictionEquations[i]);
  10272. }
  10273. this.frictionEquations.length = 0;
  10274. this.narrowphase.getContacts(p1, p2, this, contacts, oldcontacts, // To be reused
  10275. this.frictionEquations, frictionEquationPool);
  10276. if (doProfiling) {
  10277. profile.narrowphase = performance.now() - profilingStart;
  10278. } // Loop over all collisions
  10279. if (doProfiling) {
  10280. profilingStart = performance.now();
  10281. } // Add all friction eqs
  10282. for (i = 0; i < this.frictionEquations.length; i++) {
  10283. solver.addEquation(this.frictionEquations[i]);
  10284. }
  10285. const ncontacts = contacts.length;
  10286. for (let k = 0; k !== ncontacts; k++) {
  10287. // Current contact
  10288. const c = contacts[k]; // Get current collision indeces
  10289. const bi = c.bi;
  10290. const bj = c.bj;
  10291. const si = c.si;
  10292. const sj = c.sj; // Get collision properties
  10293. let cm;
  10294. if (bi.material && bj.material) {
  10295. cm = this.getContactMaterial(bi.material, bj.material) || this.defaultContactMaterial;
  10296. } else {
  10297. cm = this.defaultContactMaterial;
  10298. } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  10299. cm.friction; // c.restitution = cm.restitution;
  10300. // If friction or restitution were specified in the material, use them
  10301. if (bi.material && bj.material) {
  10302. if (bi.material.friction >= 0 && bj.material.friction >= 0) {
  10303. bi.material.friction * bj.material.friction;
  10304. }
  10305. if (bi.material.restitution >= 0 && bj.material.restitution >= 0) {
  10306. c.restitution = bi.material.restitution * bj.material.restitution;
  10307. }
  10308. } // c.setSpookParams(
  10309. // cm.contactEquationStiffness,
  10310. // cm.contactEquationRelaxation,
  10311. // dt
  10312. // );
  10313. solver.addEquation(c); // // Add friction constraint equation
  10314. // if(mu > 0){
  10315. // // Create 2 tangent equations
  10316. // const mug = mu * gnorm;
  10317. // const reducedMass = (bi.invMass + bj.invMass);
  10318. // if(reducedMass > 0){
  10319. // reducedMass = 1/reducedMass;
  10320. // }
  10321. // const pool = frictionEquationPool;
  10322. // const c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  10323. // const c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  10324. // this.frictionEquations.push(c1, c2);
  10325. // c1.bi = c2.bi = bi;
  10326. // c1.bj = c2.bj = bj;
  10327. // c1.minForce = c2.minForce = -mug*reducedMass;
  10328. // c1.maxForce = c2.maxForce = mug*reducedMass;
  10329. // // Copy over the relative vectors
  10330. // c1.ri.copy(c.ri);
  10331. // c1.rj.copy(c.rj);
  10332. // c2.ri.copy(c.ri);
  10333. // c2.rj.copy(c.rj);
  10334. // // Construct tangents
  10335. // c.ni.tangents(c1.t, c2.t);
  10336. // // Set spook params
  10337. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  10338. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  10339. // c1.enabled = c2.enabled = c.enabled;
  10340. // // Add equations to solver
  10341. // solver.addEquation(c1);
  10342. // solver.addEquation(c2);
  10343. // }
  10344. if (bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC) {
  10345. const speedSquaredB = bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared();
  10346. const speedLimitSquaredB = bj.sleepSpeedLimit ** 2;
  10347. if (speedSquaredB >= speedLimitSquaredB * 2) {
  10348. bi.wakeUpAfterNarrowphase = true;
  10349. }
  10350. }
  10351. if (bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC) {
  10352. const speedSquaredA = bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared();
  10353. const speedLimitSquaredA = bi.sleepSpeedLimit ** 2;
  10354. if (speedSquaredA >= speedLimitSquaredA * 2) {
  10355. bj.wakeUpAfterNarrowphase = true;
  10356. }
  10357. } // Now we know that i and j are in contact. Set collision matrix state
  10358. this.collisionMatrix.set(bi, bj, true);
  10359. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  10360. // First contact!
  10361. // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
  10362. World_step_collideEvent.body = bj;
  10363. World_step_collideEvent.contact = c;
  10364. bi.dispatchEvent(World_step_collideEvent);
  10365. World_step_collideEvent.body = bi;
  10366. bj.dispatchEvent(World_step_collideEvent);
  10367. }
  10368. this.bodyOverlapKeeper.set(bi.id, bj.id);
  10369. this.shapeOverlapKeeper.set(si.id, sj.id);
  10370. }
  10371. this.emitContactEvents();
  10372. if (doProfiling) {
  10373. profile.makeContactConstraints = performance.now() - profilingStart;
  10374. profilingStart = performance.now();
  10375. } // Wake up bodies
  10376. for (i = 0; i !== N; i++) {
  10377. const bi = bodies[i];
  10378. if (bi.wakeUpAfterNarrowphase) {
  10379. bi.wakeUp();
  10380. bi.wakeUpAfterNarrowphase = false;
  10381. }
  10382. } // Add user-added constraints
  10383. Nconstraints = constraints.length;
  10384. for (i = 0; i !== Nconstraints; i++) {
  10385. const c = constraints[i];
  10386. c.update();
  10387. for (let j = 0, Neq = c.equations.length; j !== Neq; j++) {
  10388. const eq = c.equations[j];
  10389. solver.addEquation(eq);
  10390. }
  10391. } // Solve the constrained system
  10392. solver.solve(dt, this);
  10393. if (doProfiling) {
  10394. profile.solve = performance.now() - profilingStart;
  10395. } // Remove all contacts from solver
  10396. solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  10397. const pow = Math.pow;
  10398. for (i = 0; i !== N; i++) {
  10399. const bi = bodies[i];
  10400. if (bi.type & DYNAMIC) {
  10401. // Only for dynamic bodies
  10402. const ld = pow(1.0 - bi.linearDamping, dt);
  10403. const v = bi.velocity;
  10404. v.scale(ld, v);
  10405. const av = bi.angularVelocity;
  10406. if (av) {
  10407. const ad = pow(1.0 - bi.angularDamping, dt);
  10408. av.scale(ad, av);
  10409. }
  10410. }
  10411. }
  10412. this.dispatchEvent(World_step_preStepEvent); // Leap frog
  10413. // vnew = v + h*f/m
  10414. // xnew = x + h*vnew
  10415. if (doProfiling) {
  10416. profilingStart = performance.now();
  10417. }
  10418. const stepnumber = this.stepnumber;
  10419. const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;
  10420. const quatNormalizeFast = this.quatNormalizeFast;
  10421. for (i = 0; i !== N; i++) {
  10422. bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);
  10423. }
  10424. this.clearForces();
  10425. this.broadphase.dirty = true;
  10426. if (doProfiling) {
  10427. profile.integrate = performance.now() - profilingStart;
  10428. } // Update step number
  10429. this.stepnumber += 1;
  10430. this.dispatchEvent(World_step_postStepEvent); // Sleeping update
  10431. let hasActiveBodies = true;
  10432. if (this.allowSleep) {
  10433. hasActiveBodies = false;
  10434. for (i = 0; i !== N; i++) {
  10435. const bi = bodies[i];
  10436. bi.sleepTick(this.time);
  10437. if (bi.sleepState !== Body.SLEEPING) {
  10438. hasActiveBodies = true;
  10439. }
  10440. }
  10441. }
  10442. this.hasActiveBodies = hasActiveBodies;
  10443. }
  10444. emitContactEvents() {
  10445. const hasBeginContact = this.hasAnyEventListener('beginContact');
  10446. const hasEndContact = this.hasAnyEventListener('endContact');
  10447. if (hasBeginContact || hasEndContact) {
  10448. this.bodyOverlapKeeper.getDiff(additions, removals);
  10449. }
  10450. if (hasBeginContact) {
  10451. for (let i = 0, l = additions.length; i < l; i += 2) {
  10452. beginContactEvent.bodyA = this.getBodyById(additions[i]);
  10453. beginContactEvent.bodyB = this.getBodyById(additions[i + 1]);
  10454. this.dispatchEvent(beginContactEvent);
  10455. }
  10456. beginContactEvent.bodyA = beginContactEvent.bodyB = null;
  10457. }
  10458. if (hasEndContact) {
  10459. for (let i = 0, l = removals.length; i < l; i += 2) {
  10460. endContactEvent.bodyA = this.getBodyById(removals[i]);
  10461. endContactEvent.bodyB = this.getBodyById(removals[i + 1]);
  10462. this.dispatchEvent(endContactEvent);
  10463. }
  10464. endContactEvent.bodyA = endContactEvent.bodyB = null;
  10465. }
  10466. additions.length = removals.length = 0;
  10467. const hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');
  10468. const hasEndShapeContact = this.hasAnyEventListener('endShapeContact');
  10469. if (hasBeginShapeContact || hasEndShapeContact) {
  10470. this.shapeOverlapKeeper.getDiff(additions, removals);
  10471. }
  10472. if (hasBeginShapeContact) {
  10473. for (let i = 0, l = additions.length; i < l; i += 2) {
  10474. const shapeA = this.getShapeById(additions[i]);
  10475. const shapeB = this.getShapeById(additions[i + 1]);
  10476. beginShapeContactEvent.shapeA = shapeA;
  10477. beginShapeContactEvent.shapeB = shapeB;
  10478. if (shapeA) beginShapeContactEvent.bodyA = shapeA.body;
  10479. if (shapeB) beginShapeContactEvent.bodyB = shapeB.body;
  10480. this.dispatchEvent(beginShapeContactEvent);
  10481. }
  10482. beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;
  10483. }
  10484. if (hasEndShapeContact) {
  10485. for (let i = 0, l = removals.length; i < l; i += 2) {
  10486. const shapeA = this.getShapeById(removals[i]);
  10487. const shapeB = this.getShapeById(removals[i + 1]);
  10488. endShapeContactEvent.shapeA = shapeA;
  10489. endShapeContactEvent.shapeB = shapeB;
  10490. if (shapeA) endShapeContactEvent.bodyA = shapeA.body;
  10491. if (shapeB) endShapeContactEvent.bodyB = shapeB.body;
  10492. this.dispatchEvent(endShapeContactEvent);
  10493. }
  10494. endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;
  10495. }
  10496. }
  10497. /**
  10498. * Sets all body forces in the world to zero.
  10499. */
  10500. clearForces() {
  10501. const bodies = this.bodies;
  10502. const N = bodies.length;
  10503. for (let i = 0; i !== N; i++) {
  10504. const b = bodies[i];
  10505. b.force;
  10506. b.torque;
  10507. b.force.set(0, 0, 0);
  10508. b.torque.set(0, 0, 0);
  10509. }
  10510. }
  10511. } // Temp stuff
  10512. new AABB();
  10513. const tmpRay = new Ray(); // performance.now() fallback on Date.now()
  10514. const performance = globalThis.performance || {};
  10515. if (!performance.now) {
  10516. let nowOffset = Date.now();
  10517. if (performance.timing && performance.timing.navigationStart) {
  10518. nowOffset = performance.timing.navigationStart;
  10519. }
  10520. performance.now = () => Date.now() - nowOffset;
  10521. }
  10522. new Vec3(); // Dispatched after the world has stepped forward in time.
  10523. // Reusable event objects to save memory.
  10524. const World_step_postStepEvent = {
  10525. type: 'postStep'
  10526. }; // Dispatched before the world steps forward in time.
  10527. const World_step_preStepEvent = {
  10528. type: 'preStep'
  10529. };
  10530. const World_step_collideEvent = {
  10531. type: Body.COLLIDE_EVENT_NAME,
  10532. body: null,
  10533. contact: null
  10534. }; // Pools for unused objects
  10535. const World_step_oldContacts = [];
  10536. const World_step_frictionEquationPool = []; // Reusable arrays for collision pairs
  10537. const World_step_p1 = [];
  10538. const World_step_p2 = []; // Stuff for emitContactEvents
  10539. const additions = [];
  10540. const removals = [];
  10541. const beginContactEvent = {
  10542. type: 'beginContact',
  10543. bodyA: null,
  10544. bodyB: null
  10545. };
  10546. const endContactEvent = {
  10547. type: 'endContact',
  10548. bodyA: null,
  10549. bodyB: null
  10550. };
  10551. const beginShapeContactEvent = {
  10552. type: 'beginShapeContact',
  10553. bodyA: null,
  10554. bodyB: null,
  10555. shapeA: null,
  10556. shapeB: null
  10557. };
  10558. const endShapeContactEvent = {
  10559. type: 'endShapeContact',
  10560. bodyA: null,
  10561. bodyB: null,
  10562. shapeA: null,
  10563. shapeB: null
  10564. };
  10565. export { AABB, ArrayCollisionMatrix, BODY_SLEEP_STATES, BODY_TYPES, Body, Box, Broadphase, COLLISION_TYPES, ConeTwistConstraint, Constraint, ContactEquation, ContactMaterial, ConvexPolyhedron, Cylinder, DistanceConstraint, Equation, EventTarget, FrictionEquation, GSSolver, GridBroadphase, Heightfield, HingeConstraint, JacobianElement, LockConstraint, Mat3, Material, NaiveBroadphase, Narrowphase, ObjectCollisionMatrix, Particle, Plane, PointToPointConstraint, Pool, Quaternion, RAY_MODES, Ray, RaycastResult, RaycastVehicle, RigidVehicle, RotationalEquation, RotationalMotorEquation, SAPBroadphase, SHAPE_TYPES, SPHSystem, Shape, Solver, Sphere, SplitSolver, Spring, Transform, Trimesh, Vec3, Vec3Pool, WheelInfo, World };