cannon-es.cjs.js 339 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. /**
  4. * Records what objects are colliding with each other
  5. */
  6. class ObjectCollisionMatrix {
  7. /**
  8. * The matrix storage.
  9. */
  10. /**
  11. * @todo Remove useless constructor
  12. */
  13. constructor() {
  14. this.matrix = {};
  15. }
  16. /**
  17. * get
  18. */
  19. get(bi, bj) {
  20. let {
  21. id: i
  22. } = bi;
  23. let {
  24. id: j
  25. } = bj;
  26. if (j > i) {
  27. const temp = j;
  28. j = i;
  29. i = temp;
  30. }
  31. return `${i}-${j}` in this.matrix;
  32. }
  33. /**
  34. * set
  35. */
  36. set(bi, bj, value) {
  37. let {
  38. id: i
  39. } = bi;
  40. let {
  41. id: j
  42. } = bj;
  43. if (j > i) {
  44. const temp = j;
  45. j = i;
  46. i = temp;
  47. }
  48. if (value) {
  49. this.matrix[`${i}-${j}`] = true;
  50. } else {
  51. delete this.matrix[`${i}-${j}`];
  52. }
  53. }
  54. /**
  55. * Empty the matrix
  56. */
  57. reset() {
  58. this.matrix = {};
  59. }
  60. /**
  61. * Set max number of objects
  62. */
  63. setNumObjects(n) {}
  64. }
  65. /**
  66. * A 3x3 matrix.
  67. * Authored by {@link http://github.com/schteppe/ schteppe}
  68. */
  69. class Mat3 {
  70. /**
  71. * A vector of length 9, containing all matrix elements.
  72. */
  73. /**
  74. * @param elements A vector of length 9, containing all matrix elements.
  75. */
  76. constructor(elements) {
  77. if (elements === void 0) {
  78. elements = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  79. }
  80. this.elements = elements;
  81. }
  82. /**
  83. * Sets the matrix to identity
  84. * @todo Should perhaps be renamed to `setIdentity()` to be more clear.
  85. * @todo Create another function that immediately creates an identity matrix eg. `eye()`
  86. */
  87. identity() {
  88. const e = this.elements;
  89. e[0] = 1;
  90. e[1] = 0;
  91. e[2] = 0;
  92. e[3] = 0;
  93. e[4] = 1;
  94. e[5] = 0;
  95. e[6] = 0;
  96. e[7] = 0;
  97. e[8] = 1;
  98. }
  99. /**
  100. * Set all elements to zero
  101. */
  102. setZero() {
  103. const e = this.elements;
  104. e[0] = 0;
  105. e[1] = 0;
  106. e[2] = 0;
  107. e[3] = 0;
  108. e[4] = 0;
  109. e[5] = 0;
  110. e[6] = 0;
  111. e[7] = 0;
  112. e[8] = 0;
  113. }
  114. /**
  115. * Sets the matrix diagonal elements from a Vec3
  116. */
  117. setTrace(vector) {
  118. const e = this.elements;
  119. e[0] = vector.x;
  120. e[4] = vector.y;
  121. e[8] = vector.z;
  122. }
  123. /**
  124. * Gets the matrix diagonal elements
  125. */
  126. getTrace(target) {
  127. if (target === void 0) {
  128. target = new Vec3();
  129. }
  130. const e = this.elements;
  131. target.x = e[0];
  132. target.y = e[4];
  133. target.z = e[8];
  134. return target;
  135. }
  136. /**
  137. * Matrix-Vector multiplication
  138. * @param v The vector to multiply with
  139. * @param target Optional, target to save the result in.
  140. */
  141. vmult(v, target) {
  142. if (target === void 0) {
  143. target = new Vec3();
  144. }
  145. const e = this.elements;
  146. const x = v.x;
  147. const y = v.y;
  148. const z = v.z;
  149. target.x = e[0] * x + e[1] * y + e[2] * z;
  150. target.y = e[3] * x + e[4] * y + e[5] * z;
  151. target.z = e[6] * x + e[7] * y + e[8] * z;
  152. return target;
  153. }
  154. /**
  155. * Matrix-scalar multiplication
  156. */
  157. smult(s) {
  158. for (let i = 0; i < this.elements.length; i++) {
  159. this.elements[i] *= s;
  160. }
  161. }
  162. /**
  163. * Matrix multiplication
  164. * @param matrix Matrix to multiply with from left side.
  165. */
  166. mmult(matrix, target) {
  167. if (target === void 0) {
  168. target = new Mat3();
  169. }
  170. const A = this.elements;
  171. const B = matrix.elements;
  172. const T = target.elements;
  173. const a11 = A[0],
  174. a12 = A[1],
  175. a13 = A[2],
  176. a21 = A[3],
  177. a22 = A[4],
  178. a23 = A[5],
  179. a31 = A[6],
  180. a32 = A[7],
  181. a33 = A[8];
  182. const b11 = B[0],
  183. b12 = B[1],
  184. b13 = B[2],
  185. b21 = B[3],
  186. b22 = B[4],
  187. b23 = B[5],
  188. b31 = B[6],
  189. b32 = B[7],
  190. b33 = B[8];
  191. T[0] = a11 * b11 + a12 * b21 + a13 * b31;
  192. T[1] = a11 * b12 + a12 * b22 + a13 * b32;
  193. T[2] = a11 * b13 + a12 * b23 + a13 * b33;
  194. T[3] = a21 * b11 + a22 * b21 + a23 * b31;
  195. T[4] = a21 * b12 + a22 * b22 + a23 * b32;
  196. T[5] = a21 * b13 + a22 * b23 + a23 * b33;
  197. T[6] = a31 * b11 + a32 * b21 + a33 * b31;
  198. T[7] = a31 * b12 + a32 * b22 + a33 * b32;
  199. T[8] = a31 * b13 + a32 * b23 + a33 * b33;
  200. return target;
  201. }
  202. /**
  203. * Scale each column of the matrix
  204. */
  205. scale(vector, target) {
  206. if (target === void 0) {
  207. target = new Mat3();
  208. }
  209. const e = this.elements;
  210. const t = target.elements;
  211. for (let i = 0; i !== 3; i++) {
  212. t[3 * i + 0] = vector.x * e[3 * i + 0];
  213. t[3 * i + 1] = vector.y * e[3 * i + 1];
  214. t[3 * i + 2] = vector.z * e[3 * i + 2];
  215. }
  216. return target;
  217. }
  218. /**
  219. * Solve Ax=b
  220. * @param b The right hand side
  221. * @param target Optional. Target vector to save in.
  222. * @return The solution x
  223. * @todo should reuse arrays
  224. */
  225. solve(b, target) {
  226. if (target === void 0) {
  227. target = new Vec3();
  228. }
  229. // Construct equations
  230. const nr = 3; // num rows
  231. const nc = 4; // num cols
  232. const eqns = [];
  233. let i;
  234. let j;
  235. for (i = 0; i < nr * nc; i++) {
  236. eqns.push(0);
  237. }
  238. for (i = 0; i < 3; i++) {
  239. for (j = 0; j < 3; j++) {
  240. eqns[i + nc * j] = this.elements[i + 3 * j];
  241. }
  242. }
  243. eqns[3 + 4 * 0] = b.x;
  244. eqns[3 + 4 * 1] = b.y;
  245. eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination
  246. let n = 3;
  247. const k = n;
  248. let np;
  249. const kp = 4; // num rows
  250. let p;
  251. do {
  252. i = k - n;
  253. if (eqns[i + nc * i] === 0) {
  254. // the pivot is null, swap lines
  255. for (j = i + 1; j < k; j++) {
  256. if (eqns[i + nc * j] !== 0) {
  257. np = kp;
  258. do {
  259. // do ligne( i ) = ligne( i ) + ligne( k )
  260. p = kp - np;
  261. eqns[p + nc * i] += eqns[p + nc * j];
  262. } while (--np);
  263. break;
  264. }
  265. }
  266. }
  267. if (eqns[i + nc * i] !== 0) {
  268. for (j = i + 1; j < k; j++) {
  269. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  270. np = kp;
  271. do {
  272. // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  273. p = kp - np;
  274. eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  275. } while (--np);
  276. }
  277. }
  278. } while (--n); // Get the solution
  279. target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2];
  280. target.y = (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1];
  281. target.x = (eqns[0 * nc + 3] - eqns[0 * nc + 2] * target.z - eqns[0 * nc + 1] * target.y) / eqns[0 * nc + 0];
  282. if (isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x === Infinity || target.y === Infinity || target.z === Infinity) {
  283. throw `Could not solve equation! Got x=[${target.toString()}], b=[${b.toString()}], A=[${this.toString()}]`;
  284. }
  285. return target;
  286. }
  287. /**
  288. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  289. * @param value If provided, the matrix element will be set to this value.
  290. */
  291. e(row, column, value) {
  292. if (value === undefined) {
  293. return this.elements[column + 3 * row];
  294. } else {
  295. // Set value
  296. this.elements[column + 3 * row] = value;
  297. }
  298. }
  299. /**
  300. * Copy another matrix into this matrix object.
  301. */
  302. copy(matrix) {
  303. for (let i = 0; i < matrix.elements.length; i++) {
  304. this.elements[i] = matrix.elements[i];
  305. }
  306. return this;
  307. }
  308. /**
  309. * Returns a string representation of the matrix.
  310. */
  311. toString() {
  312. let r = '';
  313. const sep = ',';
  314. for (let i = 0; i < 9; i++) {
  315. r += this.elements[i] + sep;
  316. }
  317. return r;
  318. }
  319. /**
  320. * reverse the matrix
  321. * @param target Target matrix to save in.
  322. * @return The solution x
  323. */
  324. reverse(target) {
  325. if (target === void 0) {
  326. target = new Mat3();
  327. }
  328. // Construct equations
  329. const nr = 3; // num rows
  330. const nc = 6; // num cols
  331. const eqns = reverse_eqns;
  332. let i;
  333. let j;
  334. for (i = 0; i < 3; i++) {
  335. for (j = 0; j < 3; j++) {
  336. eqns[i + nc * j] = this.elements[i + 3 * j];
  337. }
  338. }
  339. eqns[3 + 6 * 0] = 1;
  340. eqns[3 + 6 * 1] = 0;
  341. eqns[3 + 6 * 2] = 0;
  342. eqns[4 + 6 * 0] = 0;
  343. eqns[4 + 6 * 1] = 1;
  344. eqns[4 + 6 * 2] = 0;
  345. eqns[5 + 6 * 0] = 0;
  346. eqns[5 + 6 * 1] = 0;
  347. eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination
  348. let n = 3;
  349. const k = n;
  350. let np;
  351. const kp = nc; // num rows
  352. let p;
  353. do {
  354. i = k - n;
  355. if (eqns[i + nc * i] === 0) {
  356. // the pivot is null, swap lines
  357. for (j = i + 1; j < k; j++) {
  358. if (eqns[i + nc * j] !== 0) {
  359. np = kp;
  360. do {
  361. // do line( i ) = line( i ) + line( k )
  362. p = kp - np;
  363. eqns[p + nc * i] += eqns[p + nc * j];
  364. } while (--np);
  365. break;
  366. }
  367. }
  368. }
  369. if (eqns[i + nc * i] !== 0) {
  370. for (j = i + 1; j < k; j++) {
  371. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  372. np = kp;
  373. do {
  374. // do line( k ) = line( k ) - multiplier * line( i )
  375. p = kp - np;
  376. eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  377. } while (--np);
  378. }
  379. }
  380. } while (--n); // eliminate the upper left triangle of the matrix
  381. i = 2;
  382. do {
  383. j = i - 1;
  384. do {
  385. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  386. np = nc;
  387. do {
  388. p = nc - np;
  389. eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  390. } while (--np);
  391. } while (j--);
  392. } while (--i); // operations on the diagonal
  393. i = 2;
  394. do {
  395. const multiplier = 1 / eqns[i + nc * i];
  396. np = nc;
  397. do {
  398. p = nc - np;
  399. eqns[p + nc * i] = eqns[p + nc * i] * multiplier;
  400. } while (--np);
  401. } while (i--);
  402. i = 2;
  403. do {
  404. j = 2;
  405. do {
  406. p = eqns[nr + j + nc * i];
  407. if (isNaN(p) || p === Infinity) {
  408. throw `Could not reverse! A=[${this.toString()}]`;
  409. }
  410. target.e(i, j, p);
  411. } while (j--);
  412. } while (i--);
  413. return target;
  414. }
  415. /**
  416. * Set the matrix from a quaterion
  417. */
  418. setRotationFromQuaternion(q) {
  419. const x = q.x;
  420. const y = q.y;
  421. const z = q.z;
  422. const w = q.w;
  423. const x2 = x + x;
  424. const y2 = y + y;
  425. const z2 = z + z;
  426. const xx = x * x2;
  427. const xy = x * y2;
  428. const xz = x * z2;
  429. const yy = y * y2;
  430. const yz = y * z2;
  431. const zz = z * z2;
  432. const wx = w * x2;
  433. const wy = w * y2;
  434. const wz = w * z2;
  435. const e = this.elements;
  436. e[3 * 0 + 0] = 1 - (yy + zz);
  437. e[3 * 0 + 1] = xy - wz;
  438. e[3 * 0 + 2] = xz + wy;
  439. e[3 * 1 + 0] = xy + wz;
  440. e[3 * 1 + 1] = 1 - (xx + zz);
  441. e[3 * 1 + 2] = yz - wx;
  442. e[3 * 2 + 0] = xz - wy;
  443. e[3 * 2 + 1] = yz + wx;
  444. e[3 * 2 + 2] = 1 - (xx + yy);
  445. return this;
  446. }
  447. /**
  448. * Transpose the matrix
  449. * @param target Optional. Where to store the result.
  450. * @return The target Mat3, or a new Mat3 if target was omitted.
  451. */
  452. transpose(target) {
  453. if (target === void 0) {
  454. target = new Mat3();
  455. }
  456. const M = this.elements;
  457. const T = target.elements;
  458. let tmp; //Set diagonals
  459. T[0] = M[0];
  460. T[4] = M[4];
  461. T[8] = M[8];
  462. tmp = M[1];
  463. T[1] = M[3];
  464. T[3] = tmp;
  465. tmp = M[2];
  466. T[2] = M[6];
  467. T[6] = tmp;
  468. tmp = M[5];
  469. T[5] = M[7];
  470. T[7] = tmp;
  471. return target;
  472. }
  473. }
  474. const reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  475. /**
  476. * 3-dimensional vector
  477. * @example
  478. * const v = new Vec3(1, 2, 3)
  479. * console.log('x=' + v.x) // x=1
  480. */
  481. class Vec3 {
  482. constructor(x, y, z) {
  483. if (x === void 0) {
  484. x = 0.0;
  485. }
  486. if (y === void 0) {
  487. y = 0.0;
  488. }
  489. if (z === void 0) {
  490. z = 0.0;
  491. }
  492. this.x = x;
  493. this.y = y;
  494. this.z = z;
  495. }
  496. /**
  497. * Vector cross product
  498. * @param target Optional target to save in.
  499. */
  500. cross(vector, target) {
  501. if (target === void 0) {
  502. target = new Vec3();
  503. }
  504. const vx = vector.x;
  505. const vy = vector.y;
  506. const vz = vector.z;
  507. const x = this.x;
  508. const y = this.y;
  509. const z = this.z;
  510. target.x = y * vz - z * vy;
  511. target.y = z * vx - x * vz;
  512. target.z = x * vy - y * vx;
  513. return target;
  514. }
  515. /**
  516. * Set the vectors' 3 elements
  517. */
  518. set(x, y, z) {
  519. this.x = x;
  520. this.y = y;
  521. this.z = z;
  522. return this;
  523. }
  524. /**
  525. * Set all components of the vector to zero.
  526. */
  527. setZero() {
  528. this.x = this.y = this.z = 0;
  529. }
  530. /**
  531. * Vector addition
  532. */
  533. vadd(vector, target) {
  534. if (target) {
  535. target.x = vector.x + this.x;
  536. target.y = vector.y + this.y;
  537. target.z = vector.z + this.z;
  538. } else {
  539. return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z);
  540. }
  541. }
  542. /**
  543. * Vector subtraction
  544. * @param target Optional target to save in.
  545. */
  546. vsub(vector, target) {
  547. if (target) {
  548. target.x = this.x - vector.x;
  549. target.y = this.y - vector.y;
  550. target.z = this.z - vector.z;
  551. } else {
  552. return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z);
  553. }
  554. }
  555. /**
  556. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  557. *
  558. * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture}
  559. */
  560. crossmat() {
  561. return new Mat3([0, -this.z, this.y, this.z, 0, -this.x, -this.y, this.x, 0]);
  562. }
  563. /**
  564. * Normalize the vector. Note that this changes the values in the vector.
  565. * @return Returns the norm of the vector
  566. */
  567. normalize() {
  568. const x = this.x;
  569. const y = this.y;
  570. const z = this.z;
  571. const n = Math.sqrt(x * x + y * y + z * z);
  572. if (n > 0.0) {
  573. const invN = 1 / n;
  574. this.x *= invN;
  575. this.y *= invN;
  576. this.z *= invN;
  577. } else {
  578. // Make something up
  579. this.x = 0;
  580. this.y = 0;
  581. this.z = 0;
  582. }
  583. return n;
  584. }
  585. /**
  586. * Get the version of this vector that is of length 1.
  587. * @param target Optional target to save in
  588. * @return Returns the unit vector
  589. */
  590. unit(target) {
  591. if (target === void 0) {
  592. target = new Vec3();
  593. }
  594. const x = this.x;
  595. const y = this.y;
  596. const z = this.z;
  597. let ninv = Math.sqrt(x * x + y * y + z * z);
  598. if (ninv > 0.0) {
  599. ninv = 1.0 / ninv;
  600. target.x = x * ninv;
  601. target.y = y * ninv;
  602. target.z = z * ninv;
  603. } else {
  604. target.x = 1;
  605. target.y = 0;
  606. target.z = 0;
  607. }
  608. return target;
  609. }
  610. /**
  611. * Get the length of the vector
  612. */
  613. length() {
  614. const x = this.x;
  615. const y = this.y;
  616. const z = this.z;
  617. return Math.sqrt(x * x + y * y + z * z);
  618. }
  619. /**
  620. * Get the squared length of the vector.
  621. */
  622. lengthSquared() {
  623. return this.dot(this);
  624. }
  625. /**
  626. * Get distance from this point to another point
  627. */
  628. distanceTo(p) {
  629. const x = this.x;
  630. const y = this.y;
  631. const z = this.z;
  632. const px = p.x;
  633. const py = p.y;
  634. const pz = p.z;
  635. return Math.sqrt((px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z));
  636. }
  637. /**
  638. * Get squared distance from this point to another point
  639. */
  640. distanceSquared(p) {
  641. const x = this.x;
  642. const y = this.y;
  643. const z = this.z;
  644. const px = p.x;
  645. const py = p.y;
  646. const pz = p.z;
  647. return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z);
  648. }
  649. /**
  650. * Multiply all the components of the vector with a scalar.
  651. * @param target The vector to save the result in.
  652. */
  653. scale(scalar, target) {
  654. if (target === void 0) {
  655. target = new Vec3();
  656. }
  657. const x = this.x;
  658. const y = this.y;
  659. const z = this.z;
  660. target.x = scalar * x;
  661. target.y = scalar * y;
  662. target.z = scalar * z;
  663. return target;
  664. }
  665. /**
  666. * Multiply the vector with an other vector, component-wise.
  667. * @param target The vector to save the result in.
  668. */
  669. vmul(vector, target) {
  670. if (target === void 0) {
  671. target = new Vec3();
  672. }
  673. target.x = vector.x * this.x;
  674. target.y = vector.y * this.y;
  675. target.z = vector.z * this.z;
  676. return target;
  677. }
  678. /**
  679. * Scale a vector and add it to this vector. Save the result in "target". (target = this + vector * scalar)
  680. * @param target The vector to save the result in.
  681. */
  682. addScaledVector(scalar, vector, target) {
  683. if (target === void 0) {
  684. target = new Vec3();
  685. }
  686. target.x = this.x + scalar * vector.x;
  687. target.y = this.y + scalar * vector.y;
  688. target.z = this.z + scalar * vector.z;
  689. return target;
  690. }
  691. /**
  692. * Calculate dot product
  693. * @param vector
  694. */
  695. dot(vector) {
  696. return this.x * vector.x + this.y * vector.y + this.z * vector.z;
  697. }
  698. isZero() {
  699. return this.x === 0 && this.y === 0 && this.z === 0;
  700. }
  701. /**
  702. * Make the vector point in the opposite direction.
  703. * @param target Optional target to save in
  704. */
  705. negate(target) {
  706. if (target === void 0) {
  707. target = new Vec3();
  708. }
  709. target.x = -this.x;
  710. target.y = -this.y;
  711. target.z = -this.z;
  712. return target;
  713. }
  714. /**
  715. * Compute two artificial tangents to the vector
  716. * @param t1 Vector object to save the first tangent in
  717. * @param t2 Vector object to save the second tangent in
  718. */
  719. tangents(t1, t2) {
  720. const norm = this.length();
  721. if (norm > 0.0) {
  722. const n = Vec3_tangents_n;
  723. const inorm = 1 / norm;
  724. n.set(this.x * inorm, this.y * inorm, this.z * inorm);
  725. const randVec = Vec3_tangents_randVec;
  726. if (Math.abs(n.x) < 0.9) {
  727. randVec.set(1, 0, 0);
  728. n.cross(randVec, t1);
  729. } else {
  730. randVec.set(0, 1, 0);
  731. n.cross(randVec, t1);
  732. }
  733. n.cross(t1, t2);
  734. } else {
  735. // The normal length is zero, make something up
  736. t1.set(1, 0, 0);
  737. t2.set(0, 1, 0);
  738. }
  739. }
  740. /**
  741. * Converts to a more readable format
  742. */
  743. toString() {
  744. return `${this.x},${this.y},${this.z}`;
  745. }
  746. /**
  747. * Converts to an array
  748. */
  749. toArray() {
  750. return [this.x, this.y, this.z];
  751. }
  752. /**
  753. * Copies value of source to this vector.
  754. */
  755. copy(vector) {
  756. this.x = vector.x;
  757. this.y = vector.y;
  758. this.z = vector.z;
  759. return this;
  760. }
  761. /**
  762. * Do a linear interpolation between two vectors
  763. * @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.
  764. */
  765. lerp(vector, t, target) {
  766. const x = this.x;
  767. const y = this.y;
  768. const z = this.z;
  769. target.x = x + (vector.x - x) * t;
  770. target.y = y + (vector.y - y) * t;
  771. target.z = z + (vector.z - z) * t;
  772. }
  773. /**
  774. * Check if a vector equals is almost equal to another one.
  775. */
  776. almostEquals(vector, precision) {
  777. if (precision === void 0) {
  778. precision = 1e-6;
  779. }
  780. if (Math.abs(this.x - vector.x) > precision || Math.abs(this.y - vector.y) > precision || Math.abs(this.z - vector.z) > precision) {
  781. return false;
  782. }
  783. return true;
  784. }
  785. /**
  786. * Check if a vector is almost zero
  787. */
  788. almostZero(precision) {
  789. if (precision === void 0) {
  790. precision = 1e-6;
  791. }
  792. if (Math.abs(this.x) > precision || Math.abs(this.y) > precision || Math.abs(this.z) > precision) {
  793. return false;
  794. }
  795. return true;
  796. }
  797. /**
  798. * Check if the vector is anti-parallel to another vector.
  799. * @param precision Set to zero for exact comparisons
  800. */
  801. isAntiparallelTo(vector, precision) {
  802. this.negate(antip_neg);
  803. return antip_neg.almostEquals(vector, precision);
  804. }
  805. /**
  806. * Clone the vector
  807. */
  808. clone() {
  809. return new Vec3(this.x, this.y, this.z);
  810. }
  811. }
  812. Vec3.ZERO = new Vec3(0, 0, 0);
  813. Vec3.UNIT_X = new Vec3(1, 0, 0);
  814. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  815. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  816. const Vec3_tangents_n = new Vec3();
  817. const Vec3_tangents_randVec = new Vec3();
  818. const antip_neg = new Vec3();
  819. /**
  820. * Axis aligned bounding box class.
  821. */
  822. class AABB {
  823. /**
  824. * The lower bound of the bounding box
  825. */
  826. /**
  827. * The upper bound of the bounding box
  828. */
  829. constructor(options) {
  830. if (options === void 0) {
  831. options = {};
  832. }
  833. this.lowerBound = new Vec3();
  834. this.upperBound = new Vec3();
  835. if (options.lowerBound) {
  836. this.lowerBound.copy(options.lowerBound);
  837. }
  838. if (options.upperBound) {
  839. this.upperBound.copy(options.upperBound);
  840. }
  841. }
  842. /**
  843. * Set the AABB bounds from a set of points.
  844. * @param points An array of Vec3's.
  845. * @return The self object
  846. */
  847. setFromPoints(points, position, quaternion, skinSize) {
  848. const l = this.lowerBound;
  849. const u = this.upperBound;
  850. const q = quaternion; // Set to the first point
  851. l.copy(points[0]);
  852. if (q) {
  853. q.vmult(l, l);
  854. }
  855. u.copy(l);
  856. for (let i = 1; i < points.length; i++) {
  857. let p = points[i];
  858. if (q) {
  859. q.vmult(p, tmp$1);
  860. p = tmp$1;
  861. }
  862. if (p.x > u.x) {
  863. u.x = p.x;
  864. }
  865. if (p.x < l.x) {
  866. l.x = p.x;
  867. }
  868. if (p.y > u.y) {
  869. u.y = p.y;
  870. }
  871. if (p.y < l.y) {
  872. l.y = p.y;
  873. }
  874. if (p.z > u.z) {
  875. u.z = p.z;
  876. }
  877. if (p.z < l.z) {
  878. l.z = p.z;
  879. }
  880. } // Add offset
  881. if (position) {
  882. position.vadd(l, l);
  883. position.vadd(u, u);
  884. }
  885. if (skinSize) {
  886. l.x -= skinSize;
  887. l.y -= skinSize;
  888. l.z -= skinSize;
  889. u.x += skinSize;
  890. u.y += skinSize;
  891. u.z += skinSize;
  892. }
  893. return this;
  894. }
  895. /**
  896. * Copy bounds from an AABB to this AABB
  897. * @param aabb Source to copy from
  898. * @return The this object, for chainability
  899. */
  900. copy(aabb) {
  901. this.lowerBound.copy(aabb.lowerBound);
  902. this.upperBound.copy(aabb.upperBound);
  903. return this;
  904. }
  905. /**
  906. * Clone an AABB
  907. */
  908. clone() {
  909. return new AABB().copy(this);
  910. }
  911. /**
  912. * Extend this AABB so that it covers the given AABB too.
  913. */
  914. extend(aabb) {
  915. this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);
  916. this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);
  917. this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);
  918. this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);
  919. this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);
  920. this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);
  921. }
  922. /**
  923. * Returns true if the given AABB overlaps this AABB.
  924. */
  925. overlaps(aabb) {
  926. const l1 = this.lowerBound;
  927. const u1 = this.upperBound;
  928. const l2 = aabb.lowerBound;
  929. const u2 = aabb.upperBound; // l2 u2
  930. // |---------|
  931. // |--------|
  932. // l1 u1
  933. const overlapsX = l2.x <= u1.x && u1.x <= u2.x || l1.x <= u2.x && u2.x <= u1.x;
  934. const overlapsY = l2.y <= u1.y && u1.y <= u2.y || l1.y <= u2.y && u2.y <= u1.y;
  935. const overlapsZ = l2.z <= u1.z && u1.z <= u2.z || l1.z <= u2.z && u2.z <= u1.z;
  936. return overlapsX && overlapsY && overlapsZ;
  937. } // Mostly for debugging
  938. volume() {
  939. const l = this.lowerBound;
  940. const u = this.upperBound;
  941. return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);
  942. }
  943. /**
  944. * Returns true if the given AABB is fully contained in this AABB.
  945. */
  946. contains(aabb) {
  947. const l1 = this.lowerBound;
  948. const u1 = this.upperBound;
  949. const l2 = aabb.lowerBound;
  950. const u2 = aabb.upperBound; // l2 u2
  951. // |---------|
  952. // |---------------|
  953. // l1 u1
  954. 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;
  955. }
  956. getCorners(a, b, c, d, e, f, g, h) {
  957. const l = this.lowerBound;
  958. const u = this.upperBound;
  959. a.copy(l);
  960. b.set(u.x, l.y, l.z);
  961. c.set(u.x, u.y, l.z);
  962. d.set(l.x, u.y, u.z);
  963. e.set(u.x, l.y, u.z);
  964. f.set(l.x, u.y, l.z);
  965. g.set(l.x, l.y, u.z);
  966. h.copy(u);
  967. }
  968. /**
  969. * Get the representation of an AABB in another frame.
  970. * @return The "target" AABB object.
  971. */
  972. toLocalFrame(frame, target) {
  973. const corners = transformIntoFrame_corners;
  974. const a = corners[0];
  975. const b = corners[1];
  976. const c = corners[2];
  977. const d = corners[3];
  978. const e = corners[4];
  979. const f = corners[5];
  980. const g = corners[6];
  981. const h = corners[7]; // Get corners in current frame
  982. this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame
  983. for (let i = 0; i !== 8; i++) {
  984. const corner = corners[i];
  985. frame.pointToLocal(corner, corner);
  986. }
  987. return target.setFromPoints(corners);
  988. }
  989. /**
  990. * Get the representation of an AABB in the global frame.
  991. * @return The "target" AABB object.
  992. */
  993. toWorldFrame(frame, target) {
  994. const corners = transformIntoFrame_corners;
  995. const a = corners[0];
  996. const b = corners[1];
  997. const c = corners[2];
  998. const d = corners[3];
  999. const e = corners[4];
  1000. const f = corners[5];
  1001. const g = corners[6];
  1002. const h = corners[7]; // Get corners in current frame
  1003. this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame
  1004. for (let i = 0; i !== 8; i++) {
  1005. const corner = corners[i];
  1006. frame.pointToWorld(corner, corner);
  1007. }
  1008. return target.setFromPoints(corners);
  1009. }
  1010. /**
  1011. * Check if the AABB is hit by a ray.
  1012. */
  1013. overlapsRay(ray) {
  1014. const {
  1015. direction,
  1016. from
  1017. } = ray; // const t = 0
  1018. // ray.direction is unit direction vector of ray
  1019. const dirFracX = 1 / direction.x;
  1020. const dirFracY = 1 / direction.y;
  1021. const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
  1022. const t1 = (this.lowerBound.x - from.x) * dirFracX;
  1023. const t2 = (this.upperBound.x - from.x) * dirFracX;
  1024. const t3 = (this.lowerBound.y - from.y) * dirFracY;
  1025. const t4 = (this.upperBound.y - from.y) * dirFracY;
  1026. const t5 = (this.lowerBound.z - from.z) * dirFracZ;
  1027. const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
  1028. // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
  1029. const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
  1030. 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
  1031. if (tmax < 0) {
  1032. //t = tmax;
  1033. return false;
  1034. } // if tmin > tmax, ray doesn't intersect AABB
  1035. if (tmin > tmax) {
  1036. //t = tmax;
  1037. return false;
  1038. }
  1039. return true;
  1040. }
  1041. }
  1042. const tmp$1 = new Vec3();
  1043. const transformIntoFrame_corners = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  1044. /**
  1045. * Collision "matrix".
  1046. * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  1047. */
  1048. class ArrayCollisionMatrix {
  1049. /**
  1050. * The matrix storage.
  1051. */
  1052. constructor() {
  1053. this.matrix = [];
  1054. }
  1055. /**
  1056. * Get an element
  1057. */
  1058. get(bi, bj) {
  1059. let {
  1060. index: i
  1061. } = bi;
  1062. let {
  1063. index: j
  1064. } = bj;
  1065. if (j > i) {
  1066. const temp = j;
  1067. j = i;
  1068. i = temp;
  1069. }
  1070. return this.matrix[(i * (i + 1) >> 1) + j - 1];
  1071. }
  1072. /**
  1073. * Set an element
  1074. */
  1075. set(bi, bj, value) {
  1076. let {
  1077. index: i
  1078. } = bi;
  1079. let {
  1080. index: j
  1081. } = bj;
  1082. if (j > i) {
  1083. const temp = j;
  1084. j = i;
  1085. i = temp;
  1086. }
  1087. this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;
  1088. }
  1089. /**
  1090. * Sets all elements to zero
  1091. */
  1092. reset() {
  1093. for (let i = 0, l = this.matrix.length; i !== l; i++) {
  1094. this.matrix[i] = 0;
  1095. }
  1096. }
  1097. /**
  1098. * Sets the max number of objects
  1099. */
  1100. setNumObjects(n) {
  1101. this.matrix.length = n * (n - 1) >> 1;
  1102. }
  1103. }
  1104. /**
  1105. * Base class for objects that dispatches events.
  1106. */
  1107. class EventTarget {
  1108. /**
  1109. * Add an event listener
  1110. * @return The self object, for chainability.
  1111. */
  1112. addEventListener(type, listener) {
  1113. if (this._listeners === undefined) {
  1114. this._listeners = {};
  1115. }
  1116. const listeners = this._listeners;
  1117. if (listeners[type] === undefined) {
  1118. listeners[type] = [];
  1119. }
  1120. if (!listeners[type].includes(listener)) {
  1121. listeners[type].push(listener);
  1122. }
  1123. return this;
  1124. }
  1125. /**
  1126. * Check if an event listener is added
  1127. */
  1128. hasEventListener(type, listener) {
  1129. if (this._listeners === undefined) {
  1130. return false;
  1131. }
  1132. const listeners = this._listeners;
  1133. if (listeners[type] !== undefined && listeners[type].includes(listener)) {
  1134. return true;
  1135. }
  1136. return false;
  1137. }
  1138. /**
  1139. * Check if any event listener of the given type is added
  1140. */
  1141. hasAnyEventListener(type) {
  1142. if (this._listeners === undefined) {
  1143. return false;
  1144. }
  1145. const listeners = this._listeners;
  1146. return listeners[type] !== undefined;
  1147. }
  1148. /**
  1149. * Remove an event listener
  1150. * @return The self object, for chainability.
  1151. */
  1152. removeEventListener(type, listener) {
  1153. if (this._listeners === undefined) {
  1154. return this;
  1155. }
  1156. const listeners = this._listeners;
  1157. if (listeners[type] === undefined) {
  1158. return this;
  1159. }
  1160. const index = listeners[type].indexOf(listener);
  1161. if (index !== -1) {
  1162. listeners[type].splice(index, 1);
  1163. }
  1164. return this;
  1165. }
  1166. /**
  1167. * Emit an event.
  1168. * @return The self object, for chainability.
  1169. */
  1170. dispatchEvent(event) {
  1171. if (this._listeners === undefined) {
  1172. return this;
  1173. }
  1174. const listeners = this._listeners;
  1175. const listenerArray = listeners[event.type];
  1176. if (listenerArray !== undefined) {
  1177. event.target = this;
  1178. for (let i = 0, l = listenerArray.length; i < l; i++) {
  1179. listenerArray[i].call(this, event);
  1180. }
  1181. }
  1182. return this;
  1183. }
  1184. }
  1185. /**
  1186. * 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.
  1187. * @param x Multiplier of the imaginary basis vector i.
  1188. * @param y Multiplier of the imaginary basis vector j.
  1189. * @param z Multiplier of the imaginary basis vector k.
  1190. * @param w Multiplier of the real part.
  1191. * @see http://en.wikipedia.org/wiki/Quaternion
  1192. */
  1193. class Quaternion {
  1194. constructor(x, y, z, w) {
  1195. if (x === void 0) {
  1196. x = 0;
  1197. }
  1198. if (y === void 0) {
  1199. y = 0;
  1200. }
  1201. if (z === void 0) {
  1202. z = 0;
  1203. }
  1204. if (w === void 0) {
  1205. w = 1;
  1206. }
  1207. this.x = x;
  1208. this.y = y;
  1209. this.z = z;
  1210. this.w = w;
  1211. }
  1212. /**
  1213. * Set the value of the quaternion.
  1214. */
  1215. set(x, y, z, w) {
  1216. this.x = x;
  1217. this.y = y;
  1218. this.z = z;
  1219. this.w = w;
  1220. return this;
  1221. }
  1222. /**
  1223. * Convert to a readable format
  1224. * @return "x,y,z,w"
  1225. */
  1226. toString() {
  1227. return `${this.x},${this.y},${this.z},${this.w}`;
  1228. }
  1229. /**
  1230. * Convert to an Array
  1231. * @return [x, y, z, w]
  1232. */
  1233. toArray() {
  1234. return [this.x, this.y, this.z, this.w];
  1235. }
  1236. /**
  1237. * Set the quaternion components given an axis and an angle in radians.
  1238. */
  1239. setFromAxisAngle(vector, angle) {
  1240. const s = Math.sin(angle * 0.5);
  1241. this.x = vector.x * s;
  1242. this.y = vector.y * s;
  1243. this.z = vector.z * s;
  1244. this.w = Math.cos(angle * 0.5);
  1245. return this;
  1246. }
  1247. /**
  1248. * Converts the quaternion to [ axis, angle ] representation.
  1249. * @param targetAxis A vector object to reuse for storing the axis.
  1250. * @return An array, first element is the axis and the second is the angle in radians.
  1251. */
  1252. toAxisAngle(targetAxis) {
  1253. if (targetAxis === void 0) {
  1254. targetAxis = new Vec3();
  1255. }
  1256. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  1257. const angle = 2 * Math.acos(this.w);
  1258. const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  1259. if (s < 0.001) {
  1260. // test to avoid divide by zero, s is always positive due to sqrt
  1261. // if s close to zero then direction of axis not important
  1262. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  1263. targetAxis.y = this.y;
  1264. targetAxis.z = this.z;
  1265. } else {
  1266. targetAxis.x = this.x / s; // normalise axis
  1267. targetAxis.y = this.y / s;
  1268. targetAxis.z = this.z / s;
  1269. }
  1270. return [targetAxis, angle];
  1271. }
  1272. /**
  1273. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  1274. */
  1275. setFromVectors(u, v) {
  1276. if (u.isAntiparallelTo(v)) {
  1277. const t1 = sfv_t1;
  1278. const t2 = sfv_t2;
  1279. u.tangents(t1, t2);
  1280. this.setFromAxisAngle(t1, Math.PI);
  1281. } else {
  1282. const a = u.cross(v);
  1283. this.x = a.x;
  1284. this.y = a.y;
  1285. this.z = a.z;
  1286. this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v);
  1287. this.normalize();
  1288. }
  1289. return this;
  1290. }
  1291. /**
  1292. * Multiply the quaternion with an other quaternion.
  1293. */
  1294. mult(quat, target) {
  1295. if (target === void 0) {
  1296. target = new Quaternion();
  1297. }
  1298. const ax = this.x;
  1299. const ay = this.y;
  1300. const az = this.z;
  1301. const aw = this.w;
  1302. const bx = quat.x;
  1303. const by = quat.y;
  1304. const bz = quat.z;
  1305. const bw = quat.w;
  1306. target.x = ax * bw + aw * bx + ay * bz - az * by;
  1307. target.y = ay * bw + aw * by + az * bx - ax * bz;
  1308. target.z = az * bw + aw * bz + ax * by - ay * bx;
  1309. target.w = aw * bw - ax * bx - ay * by - az * bz;
  1310. return target;
  1311. }
  1312. /**
  1313. * Get the inverse quaternion rotation.
  1314. */
  1315. inverse(target) {
  1316. if (target === void 0) {
  1317. target = new Quaternion();
  1318. }
  1319. const x = this.x;
  1320. const y = this.y;
  1321. const z = this.z;
  1322. const w = this.w;
  1323. this.conjugate(target);
  1324. const inorm2 = 1 / (x * x + y * y + z * z + w * w);
  1325. target.x *= inorm2;
  1326. target.y *= inorm2;
  1327. target.z *= inorm2;
  1328. target.w *= inorm2;
  1329. return target;
  1330. }
  1331. /**
  1332. * Get the quaternion conjugate
  1333. */
  1334. conjugate(target) {
  1335. if (target === void 0) {
  1336. target = new Quaternion();
  1337. }
  1338. target.x = -this.x;
  1339. target.y = -this.y;
  1340. target.z = -this.z;
  1341. target.w = this.w;
  1342. return target;
  1343. }
  1344. /**
  1345. * Normalize the quaternion. Note that this changes the values of the quaternion.
  1346. */
  1347. normalize() {
  1348. let l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1349. if (l === 0) {
  1350. this.x = 0;
  1351. this.y = 0;
  1352. this.z = 0;
  1353. this.w = 0;
  1354. } else {
  1355. l = 1 / l;
  1356. this.x *= l;
  1357. this.y *= l;
  1358. this.z *= l;
  1359. this.w *= l;
  1360. }
  1361. return this;
  1362. }
  1363. /**
  1364. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  1365. * @author unphased, https://github.com/unphased
  1366. */
  1367. normalizeFast() {
  1368. const f = (3.0 - (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)) / 2.0;
  1369. if (f === 0) {
  1370. this.x = 0;
  1371. this.y = 0;
  1372. this.z = 0;
  1373. this.w = 0;
  1374. } else {
  1375. this.x *= f;
  1376. this.y *= f;
  1377. this.z *= f;
  1378. this.w *= f;
  1379. }
  1380. return this;
  1381. }
  1382. /**
  1383. * Multiply the quaternion by a vector
  1384. */
  1385. vmult(v, target) {
  1386. if (target === void 0) {
  1387. target = new Vec3();
  1388. }
  1389. const x = v.x;
  1390. const y = v.y;
  1391. const z = v.z;
  1392. const qx = this.x;
  1393. const qy = this.y;
  1394. const qz = this.z;
  1395. const qw = this.w; // q*v
  1396. const ix = qw * x + qy * z - qz * y;
  1397. const iy = qw * y + qz * x - qx * z;
  1398. const iz = qw * z + qx * y - qy * x;
  1399. const iw = -qx * x - qy * y - qz * z;
  1400. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1401. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1402. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1403. return target;
  1404. }
  1405. /**
  1406. * Copies value of source to this quaternion.
  1407. * @return this
  1408. */
  1409. copy(quat) {
  1410. this.x = quat.x;
  1411. this.y = quat.y;
  1412. this.z = quat.z;
  1413. this.w = quat.w;
  1414. return this;
  1415. }
  1416. /**
  1417. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm
  1418. * @param order Three-character string, defaults to "YZX"
  1419. */
  1420. toEuler(target, order) {
  1421. if (order === void 0) {
  1422. order = 'YZX';
  1423. }
  1424. let heading;
  1425. let attitude;
  1426. let bank;
  1427. const x = this.x;
  1428. const y = this.y;
  1429. const z = this.z;
  1430. const w = this.w;
  1431. switch (order) {
  1432. case 'YZX':
  1433. const test = x * y + z * w;
  1434. if (test > 0.499) {
  1435. // singularity at north pole
  1436. heading = 2 * Math.atan2(x, w);
  1437. attitude = Math.PI / 2;
  1438. bank = 0;
  1439. }
  1440. if (test < -0.499) {
  1441. // singularity at south pole
  1442. heading = -2 * Math.atan2(x, w);
  1443. attitude = -Math.PI / 2;
  1444. bank = 0;
  1445. }
  1446. if (heading === undefined) {
  1447. const sqx = x * x;
  1448. const sqy = y * y;
  1449. const sqz = z * z;
  1450. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1451. attitude = Math.asin(2 * test); // attitude
  1452. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1453. }
  1454. break;
  1455. default:
  1456. throw new Error(`Euler order ${order} not supported yet.`);
  1457. }
  1458. target.y = heading;
  1459. target.z = attitude;
  1460. target.x = bank;
  1461. }
  1462. /**
  1463. * Set the quaternion components given Euler angle representation.
  1464. *
  1465. * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination.
  1466. *
  1467. * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference
  1468. */
  1469. setFromEuler(x, y, z, order) {
  1470. if (order === void 0) {
  1471. order = 'XYZ';
  1472. }
  1473. const c1 = Math.cos(x / 2);
  1474. const c2 = Math.cos(y / 2);
  1475. const c3 = Math.cos(z / 2);
  1476. const s1 = Math.sin(x / 2);
  1477. const s2 = Math.sin(y / 2);
  1478. const s3 = Math.sin(z / 2);
  1479. if (order === 'XYZ') {
  1480. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1481. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1482. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1483. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1484. } else if (order === 'YXZ') {
  1485. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1486. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1487. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1488. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1489. } else if (order === 'ZXY') {
  1490. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1491. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1492. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1493. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1494. } else if (order === 'ZYX') {
  1495. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1496. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1497. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1498. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1499. } else if (order === 'YZX') {
  1500. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1501. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1502. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1503. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1504. } else if (order === 'XZY') {
  1505. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1506. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1507. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1508. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1509. }
  1510. return this;
  1511. }
  1512. clone() {
  1513. return new Quaternion(this.x, this.y, this.z, this.w);
  1514. }
  1515. /**
  1516. * Performs a spherical linear interpolation between two quat
  1517. *
  1518. * @param toQuat second operand
  1519. * @param t interpolation amount between the self quaternion and toQuat
  1520. * @param target A quaternion to store the result in. If not provided, a new one will be created.
  1521. * @returns {Quaternion} The "target" object
  1522. */
  1523. slerp(toQuat, t, target) {
  1524. if (target === void 0) {
  1525. target = new Quaternion();
  1526. }
  1527. const ax = this.x;
  1528. const ay = this.y;
  1529. const az = this.z;
  1530. const aw = this.w;
  1531. let bx = toQuat.x;
  1532. let by = toQuat.y;
  1533. let bz = toQuat.z;
  1534. let bw = toQuat.w;
  1535. let omega;
  1536. let cosom;
  1537. let sinom;
  1538. let scale0;
  1539. let scale1; // calc cosine
  1540. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  1541. if (cosom < 0.0) {
  1542. cosom = -cosom;
  1543. bx = -bx;
  1544. by = -by;
  1545. bz = -bz;
  1546. bw = -bw;
  1547. } // calculate coefficients
  1548. if (1.0 - cosom > 0.000001) {
  1549. // standard case (slerp)
  1550. omega = Math.acos(cosom);
  1551. sinom = Math.sin(omega);
  1552. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  1553. scale1 = Math.sin(t * omega) / sinom;
  1554. } else {
  1555. // "from" and "to" quaternions are very close
  1556. // ... so we can do a linear interpolation
  1557. scale0 = 1.0 - t;
  1558. scale1 = t;
  1559. } // calculate final values
  1560. target.x = scale0 * ax + scale1 * bx;
  1561. target.y = scale0 * ay + scale1 * by;
  1562. target.z = scale0 * az + scale1 * bz;
  1563. target.w = scale0 * aw + scale1 * bw;
  1564. return target;
  1565. }
  1566. /**
  1567. * Rotate an absolute orientation quaternion given an angular velocity and a time step.
  1568. */
  1569. integrate(angularVelocity, dt, angularFactor, target) {
  1570. if (target === void 0) {
  1571. target = new Quaternion();
  1572. }
  1573. const ax = angularVelocity.x * angularFactor.x,
  1574. ay = angularVelocity.y * angularFactor.y,
  1575. az = angularVelocity.z * angularFactor.z,
  1576. bx = this.x,
  1577. by = this.y,
  1578. bz = this.z,
  1579. bw = this.w;
  1580. const half_dt = dt * 0.5;
  1581. target.x += half_dt * (ax * bw + ay * bz - az * by);
  1582. target.y += half_dt * (ay * bw + az * bx - ax * bz);
  1583. target.z += half_dt * (az * bw + ax * by - ay * bx);
  1584. target.w += half_dt * (-ax * bx - ay * by - az * bz);
  1585. return target;
  1586. }
  1587. }
  1588. const sfv_t1 = new Vec3();
  1589. const sfv_t2 = new Vec3();
  1590. /**
  1591. * The available shape types.
  1592. */
  1593. const SHAPE_TYPES = {
  1594. /** SPHERE */
  1595. SPHERE: 1,
  1596. /** PLANE */
  1597. PLANE: 2,
  1598. /** BOX */
  1599. BOX: 4,
  1600. /** COMPOUND */
  1601. COMPOUND: 8,
  1602. /** CONVEXPOLYHEDRON */
  1603. CONVEXPOLYHEDRON: 16,
  1604. /** HEIGHTFIELD */
  1605. HEIGHTFIELD: 32,
  1606. /** PARTICLE */
  1607. PARTICLE: 64,
  1608. /** CYLINDER */
  1609. CYLINDER: 128,
  1610. /** TRIMESH */
  1611. TRIMESH: 256
  1612. };
  1613. /**
  1614. * ShapeType
  1615. */
  1616. /**
  1617. * Base class for shapes
  1618. */
  1619. class Shape {
  1620. /**
  1621. * Identifier of the Shape.
  1622. */
  1623. /**
  1624. * The type of this shape. Must be set to an int > 0 by subclasses.
  1625. */
  1626. /**
  1627. * The local bounding sphere radius of this shape.
  1628. */
  1629. /**
  1630. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  1631. * @default true
  1632. */
  1633. /**
  1634. * @default 1
  1635. */
  1636. /**
  1637. * @default -1
  1638. */
  1639. /**
  1640. * Optional material of the shape that regulates contact properties.
  1641. */
  1642. /**
  1643. * The body to which the shape is added to.
  1644. */
  1645. /**
  1646. * All the Shape types.
  1647. */
  1648. constructor(options) {
  1649. if (options === void 0) {
  1650. options = {};
  1651. }
  1652. this.id = Shape.idCounter++;
  1653. this.type = options.type || 0;
  1654. this.boundingSphereRadius = 0;
  1655. this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;
  1656. this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;
  1657. this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;
  1658. this.material = options.material ? options.material : null;
  1659. this.body = null;
  1660. }
  1661. /**
  1662. * Computes the bounding sphere radius.
  1663. * The result is stored in the property `.boundingSphereRadius`
  1664. */
  1665. updateBoundingSphereRadius() {
  1666. throw `computeBoundingSphereRadius() not implemented for shape type ${this.type}`;
  1667. }
  1668. /**
  1669. * Get the volume of this shape
  1670. */
  1671. volume() {
  1672. throw `volume() not implemented for shape type ${this.type}`;
  1673. }
  1674. /**
  1675. * Calculates the inertia in the local frame for this shape.
  1676. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  1677. */
  1678. calculateLocalInertia(mass, target) {
  1679. throw `calculateLocalInertia() not implemented for shape type ${this.type}`;
  1680. }
  1681. /**
  1682. * @todo use abstract for these kind of methods
  1683. */
  1684. calculateWorldAABB(pos, quat, min, max) {
  1685. throw `calculateWorldAABB() not implemented for shape type ${this.type}`;
  1686. }
  1687. }
  1688. Shape.idCounter = 0;
  1689. Shape.types = SHAPE_TYPES;
  1690. /**
  1691. * Transformation utilities.
  1692. */
  1693. class Transform {
  1694. /**
  1695. * position
  1696. */
  1697. /**
  1698. * quaternion
  1699. */
  1700. constructor(options) {
  1701. if (options === void 0) {
  1702. options = {};
  1703. }
  1704. this.position = new Vec3();
  1705. this.quaternion = new Quaternion();
  1706. if (options.position) {
  1707. this.position.copy(options.position);
  1708. }
  1709. if (options.quaternion) {
  1710. this.quaternion.copy(options.quaternion);
  1711. }
  1712. }
  1713. /**
  1714. * Get a global point in local transform coordinates.
  1715. */
  1716. pointToLocal(worldPoint, result) {
  1717. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  1718. }
  1719. /**
  1720. * Get a local point in global transform coordinates.
  1721. */
  1722. pointToWorld(localPoint, result) {
  1723. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  1724. }
  1725. /**
  1726. * vectorToWorldFrame
  1727. */
  1728. vectorToWorldFrame(localVector, result) {
  1729. if (result === void 0) {
  1730. result = new Vec3();
  1731. }
  1732. this.quaternion.vmult(localVector, result);
  1733. return result;
  1734. }
  1735. /**
  1736. * pointToLocalFrame
  1737. */
  1738. static pointToLocalFrame(position, quaternion, worldPoint, result) {
  1739. if (result === void 0) {
  1740. result = new Vec3();
  1741. }
  1742. worldPoint.vsub(position, result);
  1743. quaternion.conjugate(tmpQuat$1);
  1744. tmpQuat$1.vmult(result, result);
  1745. return result;
  1746. }
  1747. /**
  1748. * pointToWorldFrame
  1749. */
  1750. static pointToWorldFrame(position, quaternion, localPoint, result) {
  1751. if (result === void 0) {
  1752. result = new Vec3();
  1753. }
  1754. quaternion.vmult(localPoint, result);
  1755. result.vadd(position, result);
  1756. return result;
  1757. }
  1758. /**
  1759. * vectorToWorldFrame
  1760. */
  1761. static vectorToWorldFrame(quaternion, localVector, result) {
  1762. if (result === void 0) {
  1763. result = new Vec3();
  1764. }
  1765. quaternion.vmult(localVector, result);
  1766. return result;
  1767. }
  1768. /**
  1769. * vectorToLocalFrame
  1770. */
  1771. static vectorToLocalFrame(position, quaternion, worldVector, result) {
  1772. if (result === void 0) {
  1773. result = new Vec3();
  1774. }
  1775. quaternion.w *= -1;
  1776. quaternion.vmult(worldVector, result);
  1777. quaternion.w *= -1;
  1778. return result;
  1779. }
  1780. }
  1781. const tmpQuat$1 = new Quaternion();
  1782. /**
  1783. * A set of polygons describing a convex shape.
  1784. *
  1785. * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  1786. * in the same 3D plane), instead these should be merged into one polygon.
  1787. *
  1788. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  1789. * @author schteppe / https://github.com/schteppe
  1790. * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  1791. *
  1792. * @todo Move the clipping functions to ContactGenerator?
  1793. * @todo Automatically merge coplanar polygons in constructor.
  1794. * @example
  1795. * const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces })
  1796. * const convexBody = new CANNON.Body({ mass: 1, shape: convexShape })
  1797. * world.addBody(convexBody)
  1798. */
  1799. class ConvexPolyhedron extends Shape {
  1800. /** vertices */
  1801. /**
  1802. * Array of integer arrays, indicating which vertices each face consists of
  1803. */
  1804. /** faceNormals */
  1805. /** worldVertices */
  1806. /** worldVerticesNeedsUpdate */
  1807. /** worldFaceNormals */
  1808. /** worldFaceNormalsNeedsUpdate */
  1809. /**
  1810. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  1811. */
  1812. /** uniqueEdges */
  1813. /**
  1814. * @param vertices An array of Vec3's
  1815. * @param faces Array of integer arrays, describing which vertices that is included in each face.
  1816. */
  1817. constructor(props) {
  1818. if (props === void 0) {
  1819. props = {};
  1820. }
  1821. const {
  1822. vertices = [],
  1823. faces = [],
  1824. normals = [],
  1825. axes,
  1826. boundingSphereRadius
  1827. } = props;
  1828. super({
  1829. type: Shape.types.CONVEXPOLYHEDRON
  1830. });
  1831. this.vertices = vertices;
  1832. this.faces = faces;
  1833. this.faceNormals = normals;
  1834. if (this.faceNormals.length === 0) {
  1835. this.computeNormals();
  1836. }
  1837. if (!boundingSphereRadius) {
  1838. this.updateBoundingSphereRadius();
  1839. } else {
  1840. this.boundingSphereRadius = boundingSphereRadius;
  1841. }
  1842. this.worldVertices = []; // World transformed version of .vertices
  1843. this.worldVerticesNeedsUpdate = true;
  1844. this.worldFaceNormals = []; // World transformed version of .faceNormals
  1845. this.worldFaceNormalsNeedsUpdate = true;
  1846. this.uniqueAxes = axes ? axes.slice() : null;
  1847. this.uniqueEdges = [];
  1848. this.computeEdges();
  1849. }
  1850. /**
  1851. * Computes uniqueEdges
  1852. */
  1853. computeEdges() {
  1854. const faces = this.faces;
  1855. const vertices = this.vertices;
  1856. const edges = this.uniqueEdges;
  1857. edges.length = 0;
  1858. const edge = new Vec3();
  1859. for (let i = 0; i !== faces.length; i++) {
  1860. const face = faces[i];
  1861. const numVertices = face.length;
  1862. for (let j = 0; j !== numVertices; j++) {
  1863. const k = (j + 1) % numVertices;
  1864. vertices[face[j]].vsub(vertices[face[k]], edge);
  1865. edge.normalize();
  1866. let found = false;
  1867. for (let p = 0; p !== edges.length; p++) {
  1868. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) {
  1869. found = true;
  1870. break;
  1871. }
  1872. }
  1873. if (!found) {
  1874. edges.push(edge.clone());
  1875. }
  1876. }
  1877. }
  1878. }
  1879. /**
  1880. * Compute the normals of the faces.
  1881. * Will reuse existing Vec3 objects in the `faceNormals` array if they exist.
  1882. */
  1883. computeNormals() {
  1884. this.faceNormals.length = this.faces.length; // Generate normals
  1885. for (let i = 0; i < this.faces.length; i++) {
  1886. // Check so all vertices exists for this face
  1887. for (let j = 0; j < this.faces[i].length; j++) {
  1888. if (!this.vertices[this.faces[i][j]]) {
  1889. throw new Error(`Vertex ${this.faces[i][j]} not found!`);
  1890. }
  1891. }
  1892. const n = this.faceNormals[i] || new Vec3();
  1893. this.getFaceNormal(i, n);
  1894. n.negate(n);
  1895. this.faceNormals[i] = n;
  1896. const vertex = this.vertices[this.faces[i][0]];
  1897. if (n.dot(vertex) < 0) {
  1898. 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.`);
  1899. for (let j = 0; j < this.faces[i].length; j++) {
  1900. console.warn(`.vertices[${this.faces[i][j]}] = Vec3(${this.vertices[this.faces[i][j]].toString()})`);
  1901. }
  1902. }
  1903. }
  1904. }
  1905. /**
  1906. * Compute the normal of a face from its vertices
  1907. */
  1908. getFaceNormal(i, target) {
  1909. const f = this.faces[i];
  1910. const va = this.vertices[f[0]];
  1911. const vb = this.vertices[f[1]];
  1912. const vc = this.vertices[f[2]];
  1913. ConvexPolyhedron.computeNormal(va, vb, vc, target);
  1914. }
  1915. /**
  1916. * Get face normal given 3 vertices
  1917. */
  1918. static computeNormal(va, vb, vc, target) {
  1919. const cb = new Vec3();
  1920. const ab = new Vec3();
  1921. vb.vsub(va, ab);
  1922. vc.vsub(vb, cb);
  1923. cb.cross(ab, target);
  1924. if (!target.isZero()) {
  1925. target.normalize();
  1926. }
  1927. }
  1928. /**
  1929. * @param minDist Clamp distance
  1930. * @param result The an array of contact point objects, see clipFaceAgainstHull
  1931. */
  1932. clipAgainstHull(posA, quatA, hullB, posB, quatB, separatingNormal, minDist, maxDist, result) {
  1933. const WorldNormal = new Vec3();
  1934. let closestFaceB = -1;
  1935. let dmax = -Number.MAX_VALUE;
  1936. for (let face = 0; face < hullB.faces.length; face++) {
  1937. WorldNormal.copy(hullB.faceNormals[face]);
  1938. quatB.vmult(WorldNormal, WorldNormal);
  1939. const d = WorldNormal.dot(separatingNormal);
  1940. if (d > dmax) {
  1941. dmax = d;
  1942. closestFaceB = face;
  1943. }
  1944. }
  1945. const worldVertsB1 = [];
  1946. for (let i = 0; i < hullB.faces[closestFaceB].length; i++) {
  1947. const b = hullB.vertices[hullB.faces[closestFaceB][i]];
  1948. const worldb = new Vec3();
  1949. worldb.copy(b);
  1950. quatB.vmult(worldb, worldb);
  1951. posB.vadd(worldb, worldb);
  1952. worldVertsB1.push(worldb);
  1953. }
  1954. if (closestFaceB >= 0) {
  1955. this.clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result);
  1956. }
  1957. }
  1958. /**
  1959. * Find the separating axis between this hull and another
  1960. * @param target The target vector to save the axis in
  1961. * @return Returns false if a separation is found, else true
  1962. */
  1963. findSeparatingAxis(hullB, posA, quatA, posB, quatB, target, faceListA, faceListB) {
  1964. const faceANormalWS3 = new Vec3();
  1965. const Worldnormal1 = new Vec3();
  1966. const deltaC = new Vec3();
  1967. const worldEdge0 = new Vec3();
  1968. const worldEdge1 = new Vec3();
  1969. const Cross = new Vec3();
  1970. let dmin = Number.MAX_VALUE;
  1971. const hullA = this;
  1972. if (!hullA.uniqueAxes) {
  1973. const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA
  1974. for (let i = 0; i < numFacesA; i++) {
  1975. const fi = faceListA ? faceListA[i] : i; // Get world face normal
  1976. faceANormalWS3.copy(hullA.faceNormals[fi]);
  1977. quatA.vmult(faceANormalWS3, faceANormalWS3);
  1978. const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  1979. if (d === false) {
  1980. return false;
  1981. }
  1982. if (d < dmin) {
  1983. dmin = d;
  1984. target.copy(faceANormalWS3);
  1985. }
  1986. }
  1987. } else {
  1988. // Test unique axes
  1989. for (let i = 0; i !== hullA.uniqueAxes.length; i++) {
  1990. // Get world axis
  1991. quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3);
  1992. const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  1993. if (d === false) {
  1994. return false;
  1995. }
  1996. if (d < dmin) {
  1997. dmin = d;
  1998. target.copy(faceANormalWS3);
  1999. }
  2000. }
  2001. }
  2002. if (!hullB.uniqueAxes) {
  2003. // Test face normals from hullB
  2004. const numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  2005. for (let i = 0; i < numFacesB; i++) {
  2006. const fi = faceListB ? faceListB[i] : i;
  2007. Worldnormal1.copy(hullB.faceNormals[fi]);
  2008. quatB.vmult(Worldnormal1, Worldnormal1);
  2009. const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);
  2010. if (d === false) {
  2011. return false;
  2012. }
  2013. if (d < dmin) {
  2014. dmin = d;
  2015. target.copy(Worldnormal1);
  2016. }
  2017. }
  2018. } else {
  2019. // Test unique axes in B
  2020. for (let i = 0; i !== hullB.uniqueAxes.length; i++) {
  2021. quatB.vmult(hullB.uniqueAxes[i], Worldnormal1);
  2022. const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);
  2023. if (d === false) {
  2024. return false;
  2025. }
  2026. if (d < dmin) {
  2027. dmin = d;
  2028. target.copy(Worldnormal1);
  2029. }
  2030. }
  2031. } // Test edges
  2032. for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) {
  2033. // Get world edge
  2034. quatA.vmult(hullA.uniqueEdges[e0], worldEdge0);
  2035. for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) {
  2036. // Get world edge 2
  2037. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  2038. worldEdge0.cross(worldEdge1, Cross);
  2039. if (!Cross.almostZero()) {
  2040. Cross.normalize();
  2041. const dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  2042. if (dist === false) {
  2043. return false;
  2044. }
  2045. if (dist < dmin) {
  2046. dmin = dist;
  2047. target.copy(Cross);
  2048. }
  2049. }
  2050. }
  2051. }
  2052. posB.vsub(posA, deltaC);
  2053. if (deltaC.dot(target) > 0.0) {
  2054. target.negate(target);
  2055. }
  2056. return true;
  2057. }
  2058. /**
  2059. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  2060. * @return The overlap depth, or FALSE if no penetration.
  2061. */
  2062. testSepAxis(axis, hullB, posA, quatA, posB, quatB) {
  2063. const hullA = this;
  2064. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  2065. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  2066. const maxA = maxminA[0];
  2067. const minA = maxminA[1];
  2068. const maxB = maxminB[0];
  2069. const minB = maxminB[1];
  2070. if (maxA < minB || maxB < minA) {
  2071. return false; // Separated
  2072. }
  2073. const d0 = maxA - minB;
  2074. const d1 = maxB - minA;
  2075. const depth = d0 < d1 ? d0 : d1;
  2076. return depth;
  2077. }
  2078. /**
  2079. * calculateLocalInertia
  2080. */
  2081. calculateLocalInertia(mass, target) {
  2082. // Approximate with box inertia
  2083. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  2084. const aabbmax = new Vec3();
  2085. const aabbmin = new Vec3();
  2086. this.computeLocalAABB(aabbmin, aabbmax);
  2087. const x = aabbmax.x - aabbmin.x;
  2088. const y = aabbmax.y - aabbmin.y;
  2089. const z = aabbmax.z - aabbmin.z;
  2090. target.x = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z);
  2091. target.y = 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z);
  2092. target.z = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x);
  2093. }
  2094. /**
  2095. * @param face_i Index of the face
  2096. */
  2097. getPlaneConstantOfFace(face_i) {
  2098. const f = this.faces[face_i];
  2099. const n = this.faceNormals[face_i];
  2100. const v = this.vertices[f[0]];
  2101. const c = -n.dot(v);
  2102. return c;
  2103. }
  2104. /**
  2105. * Clip a face against a hull.
  2106. * @param worldVertsB1 An array of Vec3 with vertices in the world frame.
  2107. * @param minDist Distance clamping
  2108. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  2109. */
  2110. clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result) {
  2111. const faceANormalWS = new Vec3();
  2112. const edge0 = new Vec3();
  2113. const WorldEdge0 = new Vec3();
  2114. const worldPlaneAnormal1 = new Vec3();
  2115. const planeNormalWS1 = new Vec3();
  2116. const worldA1 = new Vec3();
  2117. const localPlaneNormal = new Vec3();
  2118. const planeNormalWS = new Vec3();
  2119. const hullA = this;
  2120. const worldVertsB2 = [];
  2121. const pVtxIn = worldVertsB1;
  2122. const pVtxOut = worldVertsB2;
  2123. let closestFaceA = -1;
  2124. let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis
  2125. for (let face = 0; face < hullA.faces.length; face++) {
  2126. faceANormalWS.copy(hullA.faceNormals[face]);
  2127. quatA.vmult(faceANormalWS, faceANormalWS);
  2128. const d = faceANormalWS.dot(separatingNormal);
  2129. if (d < dmin) {
  2130. dmin = d;
  2131. closestFaceA = face;
  2132. }
  2133. }
  2134. if (closestFaceA < 0) {
  2135. return;
  2136. } // Get the face and construct connected faces
  2137. const polyA = hullA.faces[closestFaceA];
  2138. polyA.connectedFaces = [];
  2139. for (let i = 0; i < hullA.faces.length; i++) {
  2140. for (let j = 0; j < hullA.faces[i].length; j++) {
  2141. if (
  2142. /* Sharing a vertex*/
  2143. polyA.indexOf(hullA.faces[i][j]) !== -1 &&
  2144. /* Not the one we are looking for connections from */
  2145. i !== closestFaceA &&
  2146. /* Not already added */
  2147. polyA.connectedFaces.indexOf(i) === -1) {
  2148. polyA.connectedFaces.push(i);
  2149. }
  2150. }
  2151. } // Clip the polygon to the back of the planes of all faces of hull A,
  2152. // that are adjacent to the witness face
  2153. const numVerticesA = polyA.length;
  2154. for (let i = 0; i < numVerticesA; i++) {
  2155. const a = hullA.vertices[polyA[i]];
  2156. const b = hullA.vertices[polyA[(i + 1) % numVerticesA]];
  2157. a.vsub(b, edge0);
  2158. WorldEdge0.copy(edge0);
  2159. quatA.vmult(WorldEdge0, WorldEdge0);
  2160. posA.vadd(WorldEdge0, WorldEdge0);
  2161. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);
  2162. quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1);
  2163. posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1);
  2164. WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1);
  2165. planeNormalWS1.negate(planeNormalWS1);
  2166. worldA1.copy(a);
  2167. quatA.vmult(worldA1, worldA1);
  2168. posA.vadd(worldA1, worldA1);
  2169. const otherFace = polyA.connectedFaces[i];
  2170. localPlaneNormal.copy(this.faceNormals[otherFace]);
  2171. const localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  2172. planeNormalWS.copy(localPlaneNormal);
  2173. quatA.vmult(planeNormalWS, planeNormalWS);
  2174. const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane
  2175. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip
  2176. while (pVtxIn.length) {
  2177. pVtxIn.shift();
  2178. }
  2179. while (pVtxOut.length) {
  2180. pVtxIn.push(pVtxOut.shift());
  2181. }
  2182. } // only keep contact points that are behind the witness face
  2183. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  2184. const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  2185. planeNormalWS.copy(localPlaneNormal);
  2186. quatA.vmult(planeNormalWS, planeNormalWS);
  2187. const planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  2188. for (let i = 0; i < pVtxIn.length; i++) {
  2189. let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ???
  2190. if (depth <= minDist) {
  2191. console.log(`clamped: depth=${depth} to minDist=${minDist}`);
  2192. depth = minDist;
  2193. }
  2194. if (depth <= maxDist) {
  2195. const point = pVtxIn[i];
  2196. if (depth <= 1e-6) {
  2197. const p = {
  2198. point,
  2199. normal: planeNormalWS,
  2200. depth
  2201. };
  2202. result.push(p);
  2203. }
  2204. }
  2205. }
  2206. }
  2207. /**
  2208. * Clip a face in a hull against the back of a plane.
  2209. * @param planeConstant The constant in the mathematical plane equation
  2210. */
  2211. clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) {
  2212. let n_dot_first;
  2213. let n_dot_last;
  2214. const numVerts = inVertices.length;
  2215. if (numVerts < 2) {
  2216. return outVertices;
  2217. }
  2218. let firstVertex = inVertices[inVertices.length - 1];
  2219. let lastVertex = inVertices[0];
  2220. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  2221. for (let vi = 0; vi < numVerts; vi++) {
  2222. lastVertex = inVertices[vi];
  2223. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  2224. if (n_dot_first < 0) {
  2225. if (n_dot_last < 0) {
  2226. // Start < 0, end < 0, so output lastVertex
  2227. const newv = new Vec3();
  2228. newv.copy(lastVertex);
  2229. outVertices.push(newv);
  2230. } else {
  2231. // Start < 0, end >= 0, so output intersection
  2232. const newv = new Vec3();
  2233. firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
  2234. outVertices.push(newv);
  2235. }
  2236. } else {
  2237. if (n_dot_last < 0) {
  2238. // Start >= 0, end < 0 so output intersection and end
  2239. const newv = new Vec3();
  2240. firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
  2241. outVertices.push(newv);
  2242. outVertices.push(lastVertex);
  2243. }
  2244. }
  2245. firstVertex = lastVertex;
  2246. n_dot_first = n_dot_last;
  2247. }
  2248. return outVertices;
  2249. }
  2250. /**
  2251. * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false.
  2252. */
  2253. computeWorldVertices(position, quat) {
  2254. while (this.worldVertices.length < this.vertices.length) {
  2255. this.worldVertices.push(new Vec3());
  2256. }
  2257. const verts = this.vertices;
  2258. const worldVerts = this.worldVertices;
  2259. for (let i = 0; i !== this.vertices.length; i++) {
  2260. quat.vmult(verts[i], worldVerts[i]);
  2261. position.vadd(worldVerts[i], worldVerts[i]);
  2262. }
  2263. this.worldVerticesNeedsUpdate = false;
  2264. }
  2265. computeLocalAABB(aabbmin, aabbmax) {
  2266. const vertices = this.vertices;
  2267. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2268. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2269. for (let i = 0; i < this.vertices.length; i++) {
  2270. const v = vertices[i];
  2271. if (v.x < aabbmin.x) {
  2272. aabbmin.x = v.x;
  2273. } else if (v.x > aabbmax.x) {
  2274. aabbmax.x = v.x;
  2275. }
  2276. if (v.y < aabbmin.y) {
  2277. aabbmin.y = v.y;
  2278. } else if (v.y > aabbmax.y) {
  2279. aabbmax.y = v.y;
  2280. }
  2281. if (v.z < aabbmin.z) {
  2282. aabbmin.z = v.z;
  2283. } else if (v.z > aabbmax.z) {
  2284. aabbmax.z = v.z;
  2285. }
  2286. }
  2287. }
  2288. /**
  2289. * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false.
  2290. */
  2291. computeWorldFaceNormals(quat) {
  2292. const N = this.faceNormals.length;
  2293. while (this.worldFaceNormals.length < N) {
  2294. this.worldFaceNormals.push(new Vec3());
  2295. }
  2296. const normals = this.faceNormals;
  2297. const worldNormals = this.worldFaceNormals;
  2298. for (let i = 0; i !== N; i++) {
  2299. quat.vmult(normals[i], worldNormals[i]);
  2300. }
  2301. this.worldFaceNormalsNeedsUpdate = false;
  2302. }
  2303. /**
  2304. * updateBoundingSphereRadius
  2305. */
  2306. updateBoundingSphereRadius() {
  2307. // Assume points are distributed with local (0,0,0) as center
  2308. let max2 = 0;
  2309. const verts = this.vertices;
  2310. for (let i = 0; i !== verts.length; i++) {
  2311. const norm2 = verts[i].lengthSquared();
  2312. if (norm2 > max2) {
  2313. max2 = norm2;
  2314. }
  2315. }
  2316. this.boundingSphereRadius = Math.sqrt(max2);
  2317. }
  2318. /**
  2319. * calculateWorldAABB
  2320. */
  2321. calculateWorldAABB(pos, quat, min, max) {
  2322. const verts = this.vertices;
  2323. let minx;
  2324. let miny;
  2325. let minz;
  2326. let maxx;
  2327. let maxy;
  2328. let maxz;
  2329. let tempWorldVertex = new Vec3();
  2330. for (let i = 0; i < verts.length; i++) {
  2331. tempWorldVertex.copy(verts[i]);
  2332. quat.vmult(tempWorldVertex, tempWorldVertex);
  2333. pos.vadd(tempWorldVertex, tempWorldVertex);
  2334. const v = tempWorldVertex;
  2335. if (minx === undefined || v.x < minx) {
  2336. minx = v.x;
  2337. }
  2338. if (maxx === undefined || v.x > maxx) {
  2339. maxx = v.x;
  2340. }
  2341. if (miny === undefined || v.y < miny) {
  2342. miny = v.y;
  2343. }
  2344. if (maxy === undefined || v.y > maxy) {
  2345. maxy = v.y;
  2346. }
  2347. if (minz === undefined || v.z < minz) {
  2348. minz = v.z;
  2349. }
  2350. if (maxz === undefined || v.z > maxz) {
  2351. maxz = v.z;
  2352. }
  2353. }
  2354. min.set(minx, miny, minz);
  2355. max.set(maxx, maxy, maxz);
  2356. }
  2357. /**
  2358. * Get approximate convex volume
  2359. */
  2360. volume() {
  2361. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  2362. }
  2363. /**
  2364. * Get an average of all the vertices positions
  2365. */
  2366. getAveragePointLocal(target) {
  2367. if (target === void 0) {
  2368. target = new Vec3();
  2369. }
  2370. const verts = this.vertices;
  2371. for (let i = 0; i < verts.length; i++) {
  2372. target.vadd(verts[i], target);
  2373. }
  2374. target.scale(1 / verts.length, target);
  2375. return target;
  2376. }
  2377. /**
  2378. * Transform all local points. Will change the .vertices
  2379. */
  2380. transformAllPoints(offset, quat) {
  2381. const n = this.vertices.length;
  2382. const verts = this.vertices; // Apply rotation
  2383. if (quat) {
  2384. // Rotate vertices
  2385. for (let i = 0; i < n; i++) {
  2386. const v = verts[i];
  2387. quat.vmult(v, v);
  2388. } // Rotate face normals
  2389. for (let i = 0; i < this.faceNormals.length; i++) {
  2390. const v = this.faceNormals[i];
  2391. quat.vmult(v, v);
  2392. }
  2393. /*
  2394. // Rotate edges
  2395. for(let i=0; i<this.uniqueEdges.length; i++){
  2396. const v = this.uniqueEdges[i];
  2397. quat.vmult(v,v);
  2398. }*/
  2399. } // Apply offset
  2400. if (offset) {
  2401. for (let i = 0; i < n; i++) {
  2402. const v = verts[i];
  2403. v.vadd(offset, v);
  2404. }
  2405. }
  2406. }
  2407. /**
  2408. * Checks whether p is inside the polyhedra. Must be in local coords.
  2409. * The point lies outside of the convex hull of the other points if and only if the direction
  2410. * of all the vectors from it to those other points are on less than one half of a sphere around it.
  2411. * @param p A point given in local coordinates
  2412. */
  2413. pointIsInside(p) {
  2414. const verts = this.vertices;
  2415. const faces = this.faces;
  2416. const normals = this.faceNormals;
  2417. const positiveResult = null;
  2418. const pointInside = new Vec3();
  2419. this.getAveragePointLocal(pointInside);
  2420. for (let i = 0; i < this.faces.length; i++) {
  2421. let n = normals[i];
  2422. const v = verts[faces[i][0]]; // We only need one point in the face
  2423. // This dot product determines which side of the edge the point is
  2424. const vToP = new Vec3();
  2425. p.vsub(v, vToP);
  2426. const r1 = n.dot(vToP);
  2427. const vToPointInside = new Vec3();
  2428. pointInside.vsub(v, vToPointInside);
  2429. const r2 = n.dot(vToPointInside);
  2430. if (r1 < 0 && r2 > 0 || r1 > 0 && r2 < 0) {
  2431. return false; // Encountered some other sign. Exit.
  2432. }
  2433. } // If we got here, all dot products were of the same sign.
  2434. return positiveResult ? 1 : -1;
  2435. }
  2436. /**
  2437. * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis.
  2438. * Results are saved in the array maxmin.
  2439. * @param result result[0] and result[1] will be set to maximum and minimum, respectively.
  2440. */
  2441. static project(shape, axis, pos, quat, result) {
  2442. const n = shape.vertices.length;
  2443. project_worldVertex;
  2444. const localAxis = project_localAxis;
  2445. let max = 0;
  2446. let min = 0;
  2447. const localOrigin = project_localOrigin;
  2448. const vs = shape.vertices;
  2449. localOrigin.setZero(); // Transform the axis to local
  2450. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  2451. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  2452. const add = localOrigin.dot(localAxis);
  2453. min = max = vs[0].dot(localAxis);
  2454. for (let i = 1; i < n; i++) {
  2455. const val = vs[i].dot(localAxis);
  2456. if (val > max) {
  2457. max = val;
  2458. }
  2459. if (val < min) {
  2460. min = val;
  2461. }
  2462. }
  2463. min -= add;
  2464. max -= add;
  2465. if (min > max) {
  2466. // Inconsistent - swap
  2467. const temp = min;
  2468. min = max;
  2469. max = temp;
  2470. } // Output
  2471. result[0] = max;
  2472. result[1] = min;
  2473. }
  2474. }
  2475. const maxminA = [];
  2476. const maxminB = [];
  2477. const project_worldVertex = new Vec3();
  2478. const project_localAxis = new Vec3();
  2479. const project_localOrigin = new Vec3();
  2480. /**
  2481. * A 3d box shape.
  2482. * @example
  2483. * const size = 1
  2484. * const halfExtents = new CANNON.Vec3(size, size, size)
  2485. * const boxShape = new CANNON.Box(halfExtents)
  2486. * const boxBody = new CANNON.Body({ mass: 1, shape: boxShape })
  2487. * world.addBody(boxBody)
  2488. */
  2489. class Box extends Shape {
  2490. /**
  2491. * The half extents of the box.
  2492. */
  2493. /**
  2494. * Used by the contact generator to make contacts with other convex polyhedra for example.
  2495. */
  2496. constructor(halfExtents) {
  2497. super({
  2498. type: Shape.types.BOX
  2499. });
  2500. this.halfExtents = halfExtents;
  2501. this.convexPolyhedronRepresentation = null;
  2502. this.updateConvexPolyhedronRepresentation();
  2503. this.updateBoundingSphereRadius();
  2504. }
  2505. /**
  2506. * Updates the local convex polyhedron representation used for some collisions.
  2507. */
  2508. updateConvexPolyhedronRepresentation() {
  2509. const sx = this.halfExtents.x;
  2510. const sy = this.halfExtents.y;
  2511. const sz = this.halfExtents.z;
  2512. const V = Vec3;
  2513. 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)];
  2514. const faces = [[3, 2, 1, 0], // -z
  2515. [4, 5, 6, 7], // +z
  2516. [5, 4, 0, 1], // -y
  2517. [2, 3, 7, 6], // +y
  2518. [0, 4, 7, 3], // -x
  2519. [1, 2, 6, 5] // +x
  2520. ];
  2521. const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)];
  2522. const h = new ConvexPolyhedron({
  2523. vertices,
  2524. faces,
  2525. axes
  2526. });
  2527. this.convexPolyhedronRepresentation = h;
  2528. h.material = this.material;
  2529. }
  2530. /**
  2531. * Calculate the inertia of the box.
  2532. */
  2533. calculateLocalInertia(mass, target) {
  2534. if (target === void 0) {
  2535. target = new Vec3();
  2536. }
  2537. Box.calculateInertia(this.halfExtents, mass, target);
  2538. return target;
  2539. }
  2540. static calculateInertia(halfExtents, mass, target) {
  2541. const e = halfExtents;
  2542. target.x = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z);
  2543. target.y = 1.0 / 12.0 * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z);
  2544. target.z = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x);
  2545. }
  2546. /**
  2547. * Get the box 6 side normals
  2548. * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  2549. * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  2550. */
  2551. getSideNormals(sixTargetVectors, quat) {
  2552. const sides = sixTargetVectors;
  2553. const ex = this.halfExtents;
  2554. sides[0].set(ex.x, 0, 0);
  2555. sides[1].set(0, ex.y, 0);
  2556. sides[2].set(0, 0, ex.z);
  2557. sides[3].set(-ex.x, 0, 0);
  2558. sides[4].set(0, -ex.y, 0);
  2559. sides[5].set(0, 0, -ex.z);
  2560. if (quat !== undefined) {
  2561. for (let i = 0; i !== sides.length; i++) {
  2562. quat.vmult(sides[i], sides[i]);
  2563. }
  2564. }
  2565. return sides;
  2566. }
  2567. /**
  2568. * Returns the volume of the box.
  2569. */
  2570. volume() {
  2571. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  2572. }
  2573. /**
  2574. * updateBoundingSphereRadius
  2575. */
  2576. updateBoundingSphereRadius() {
  2577. this.boundingSphereRadius = this.halfExtents.length();
  2578. }
  2579. /**
  2580. * forEachWorldCorner
  2581. */
  2582. forEachWorldCorner(pos, quat, callback) {
  2583. const e = this.halfExtents;
  2584. 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]];
  2585. for (let i = 0; i < corners.length; i++) {
  2586. worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]);
  2587. quat.vmult(worldCornerTempPos, worldCornerTempPos);
  2588. pos.vadd(worldCornerTempPos, worldCornerTempPos);
  2589. callback(worldCornerTempPos.x, worldCornerTempPos.y, worldCornerTempPos.z);
  2590. }
  2591. }
  2592. /**
  2593. * calculateWorldAABB
  2594. */
  2595. calculateWorldAABB(pos, quat, min, max) {
  2596. const e = this.halfExtents;
  2597. worldCornersTemp[0].set(e.x, e.y, e.z);
  2598. worldCornersTemp[1].set(-e.x, e.y, e.z);
  2599. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  2600. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  2601. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  2602. worldCornersTemp[5].set(e.x, e.y, -e.z);
  2603. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  2604. worldCornersTemp[7].set(e.x, -e.y, e.z);
  2605. const wc = worldCornersTemp[0];
  2606. quat.vmult(wc, wc);
  2607. pos.vadd(wc, wc);
  2608. max.copy(wc);
  2609. min.copy(wc);
  2610. for (let i = 1; i < 8; i++) {
  2611. const wc = worldCornersTemp[i];
  2612. quat.vmult(wc, wc);
  2613. pos.vadd(wc, wc);
  2614. const x = wc.x;
  2615. const y = wc.y;
  2616. const z = wc.z;
  2617. if (x > max.x) {
  2618. max.x = x;
  2619. }
  2620. if (y > max.y) {
  2621. max.y = y;
  2622. }
  2623. if (z > max.z) {
  2624. max.z = z;
  2625. }
  2626. if (x < min.x) {
  2627. min.x = x;
  2628. }
  2629. if (y < min.y) {
  2630. min.y = y;
  2631. }
  2632. if (z < min.z) {
  2633. min.z = z;
  2634. }
  2635. } // Get each axis max
  2636. // min.set(Infinity,Infinity,Infinity);
  2637. // max.set(-Infinity,-Infinity,-Infinity);
  2638. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  2639. // if(x > max.x){
  2640. // max.x = x;
  2641. // }
  2642. // if(y > max.y){
  2643. // max.y = y;
  2644. // }
  2645. // if(z > max.z){
  2646. // max.z = z;
  2647. // }
  2648. // if(x < min.x){
  2649. // min.x = x;
  2650. // }
  2651. // if(y < min.y){
  2652. // min.y = y;
  2653. // }
  2654. // if(z < min.z){
  2655. // min.z = z;
  2656. // }
  2657. // });
  2658. }
  2659. }
  2660. const worldCornerTempPos = new Vec3();
  2661. const worldCornersTemp = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  2662. /**
  2663. * BODY_TYPES
  2664. */
  2665. const BODY_TYPES = {
  2666. /** DYNAMIC */
  2667. DYNAMIC: 1,
  2668. /** STATIC */
  2669. STATIC: 2,
  2670. /** KINEMATIC */
  2671. KINEMATIC: 4
  2672. };
  2673. /**
  2674. * BodyType
  2675. */
  2676. /**
  2677. * BODY_SLEEP_STATES
  2678. */
  2679. const BODY_SLEEP_STATES = {
  2680. /** AWAKE */
  2681. AWAKE: 0,
  2682. /** SLEEPY */
  2683. SLEEPY: 1,
  2684. /** SLEEPING */
  2685. SLEEPING: 2
  2686. };
  2687. /**
  2688. * BodySleepState
  2689. */
  2690. /**
  2691. * Base class for all body types.
  2692. * @example
  2693. * const shape = new CANNON.Sphere(1)
  2694. * const body = new CANNON.Body({
  2695. * mass: 1,
  2696. * shape,
  2697. * })
  2698. * world.addBody(body)
  2699. */
  2700. class Body extends EventTarget {
  2701. /**
  2702. * Dispatched after two bodies collide. This event is dispatched on each
  2703. * of the two bodies involved in the collision.
  2704. * @event collide
  2705. * @param body The body that was involved in the collision.
  2706. * @param contact The details of the collision.
  2707. */
  2708. /**
  2709. * 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.
  2710. */
  2711. /**
  2712. * 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.
  2713. */
  2714. /**
  2715. * 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.
  2716. */
  2717. /**
  2718. * AWAKE
  2719. */
  2720. /**
  2721. * SLEEPY
  2722. */
  2723. /**
  2724. * SLEEPING
  2725. */
  2726. /**
  2727. * Dispatched after a sleeping body has woken up.
  2728. * @event wakeup
  2729. */
  2730. /**
  2731. * Dispatched after a body has gone in to the sleepy state.
  2732. * @event sleepy
  2733. */
  2734. /**
  2735. * Dispatched after a body has fallen asleep.
  2736. * @event sleep
  2737. */
  2738. constructor(options) {
  2739. if (options === void 0) {
  2740. options = {};
  2741. }
  2742. super();
  2743. this.id = Body.idCounter++;
  2744. this.index = -1;
  2745. this.world = null;
  2746. this.vlambda = new Vec3();
  2747. this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1;
  2748. this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1;
  2749. this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true;
  2750. this.position = new Vec3();
  2751. this.previousPosition = new Vec3();
  2752. this.interpolatedPosition = new Vec3();
  2753. this.initPosition = new Vec3();
  2754. if (options.position) {
  2755. this.position.copy(options.position);
  2756. this.previousPosition.copy(options.position);
  2757. this.interpolatedPosition.copy(options.position);
  2758. this.initPosition.copy(options.position);
  2759. }
  2760. this.velocity = new Vec3();
  2761. if (options.velocity) {
  2762. this.velocity.copy(options.velocity);
  2763. }
  2764. this.initVelocity = new Vec3();
  2765. this.force = new Vec3();
  2766. const mass = typeof options.mass === 'number' ? options.mass : 0;
  2767. this.mass = mass;
  2768. this.invMass = mass > 0 ? 1.0 / mass : 0;
  2769. this.material = options.material || null;
  2770. this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01;
  2771. this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC;
  2772. if (typeof options.type === typeof Body.STATIC) {
  2773. this.type = options.type;
  2774. }
  2775. this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true;
  2776. this.sleepState = Body.AWAKE;
  2777. this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  2778. this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1;
  2779. this.timeLastSleepy = 0;
  2780. this.wakeUpAfterNarrowphase = false;
  2781. this.torque = new Vec3();
  2782. this.quaternion = new Quaternion();
  2783. this.initQuaternion = new Quaternion();
  2784. this.previousQuaternion = new Quaternion();
  2785. this.interpolatedQuaternion = new Quaternion();
  2786. if (options.quaternion) {
  2787. this.quaternion.copy(options.quaternion);
  2788. this.initQuaternion.copy(options.quaternion);
  2789. this.previousQuaternion.copy(options.quaternion);
  2790. this.interpolatedQuaternion.copy(options.quaternion);
  2791. }
  2792. this.angularVelocity = new Vec3();
  2793. if (options.angularVelocity) {
  2794. this.angularVelocity.copy(options.angularVelocity);
  2795. }
  2796. this.initAngularVelocity = new Vec3();
  2797. this.shapes = [];
  2798. this.shapeOffsets = [];
  2799. this.shapeOrientations = [];
  2800. this.inertia = new Vec3();
  2801. this.invInertia = new Vec3();
  2802. this.invInertiaWorld = new Mat3();
  2803. this.invMassSolve = 0;
  2804. this.invInertiaSolve = new Vec3();
  2805. this.invInertiaWorldSolve = new Mat3();
  2806. this.fixedRotation = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false;
  2807. this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01;
  2808. this.linearFactor = new Vec3(1, 1, 1);
  2809. if (options.linearFactor) {
  2810. this.linearFactor.copy(options.linearFactor);
  2811. }
  2812. this.angularFactor = new Vec3(1, 1, 1);
  2813. if (options.angularFactor) {
  2814. this.angularFactor.copy(options.angularFactor);
  2815. }
  2816. this.aabb = new AABB();
  2817. this.aabbNeedsUpdate = true;
  2818. this.boundingRadius = 0;
  2819. this.wlambda = new Vec3();
  2820. this.isTrigger = Boolean(options.isTrigger);
  2821. if (options.shape) {
  2822. this.addShape(options.shape);
  2823. }
  2824. this.updateMassProperties();
  2825. }
  2826. /**
  2827. * Wake the body up.
  2828. */
  2829. wakeUp() {
  2830. const prevState = this.sleepState;
  2831. this.sleepState = Body.AWAKE;
  2832. this.wakeUpAfterNarrowphase = false;
  2833. if (prevState === Body.SLEEPING) {
  2834. this.dispatchEvent(Body.wakeupEvent);
  2835. }
  2836. }
  2837. /**
  2838. * Force body sleep
  2839. */
  2840. sleep() {
  2841. this.sleepState = Body.SLEEPING;
  2842. this.velocity.set(0, 0, 0);
  2843. this.angularVelocity.set(0, 0, 0);
  2844. this.wakeUpAfterNarrowphase = false;
  2845. }
  2846. /**
  2847. * Called every timestep to update internal sleep timer and change sleep state if needed.
  2848. * @param time The world time in seconds
  2849. */
  2850. sleepTick(time) {
  2851. if (this.allowSleep) {
  2852. const sleepState = this.sleepState;
  2853. const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared();
  2854. const speedLimitSquared = this.sleepSpeedLimit ** 2;
  2855. if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {
  2856. this.sleepState = Body.SLEEPY; // Sleepy
  2857. this.timeLastSleepy = time;
  2858. this.dispatchEvent(Body.sleepyEvent);
  2859. } else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {
  2860. this.wakeUp(); // Wake up
  2861. } else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {
  2862. this.sleep(); // Sleeping
  2863. this.dispatchEvent(Body.sleepEvent);
  2864. }
  2865. }
  2866. }
  2867. /**
  2868. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  2869. */
  2870. updateSolveMassProperties() {
  2871. if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {
  2872. this.invMassSolve = 0;
  2873. this.invInertiaSolve.setZero();
  2874. this.invInertiaWorldSolve.setZero();
  2875. } else {
  2876. this.invMassSolve = this.invMass;
  2877. this.invInertiaSolve.copy(this.invInertia);
  2878. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  2879. }
  2880. }
  2881. /**
  2882. * Convert a world point to local body frame.
  2883. */
  2884. pointToLocalFrame(worldPoint, result) {
  2885. if (result === void 0) {
  2886. result = new Vec3();
  2887. }
  2888. worldPoint.vsub(this.position, result);
  2889. this.quaternion.conjugate().vmult(result, result);
  2890. return result;
  2891. }
  2892. /**
  2893. * Convert a world vector to local body frame.
  2894. */
  2895. vectorToLocalFrame(worldVector, result) {
  2896. if (result === void 0) {
  2897. result = new Vec3();
  2898. }
  2899. this.quaternion.conjugate().vmult(worldVector, result);
  2900. return result;
  2901. }
  2902. /**
  2903. * Convert a local body point to world frame.
  2904. */
  2905. pointToWorldFrame(localPoint, result) {
  2906. if (result === void 0) {
  2907. result = new Vec3();
  2908. }
  2909. this.quaternion.vmult(localPoint, result);
  2910. result.vadd(this.position, result);
  2911. return result;
  2912. }
  2913. /**
  2914. * Convert a local body point to world frame.
  2915. */
  2916. vectorToWorldFrame(localVector, result) {
  2917. if (result === void 0) {
  2918. result = new Vec3();
  2919. }
  2920. this.quaternion.vmult(localVector, result);
  2921. return result;
  2922. }
  2923. /**
  2924. * Add a shape to the body with a local offset and orientation.
  2925. * @return The body object, for chainability.
  2926. */
  2927. addShape(shape, _offset, _orientation) {
  2928. const offset = new Vec3();
  2929. const orientation = new Quaternion();
  2930. if (_offset) {
  2931. offset.copy(_offset);
  2932. }
  2933. if (_orientation) {
  2934. orientation.copy(_orientation);
  2935. }
  2936. this.shapes.push(shape);
  2937. this.shapeOffsets.push(offset);
  2938. this.shapeOrientations.push(orientation);
  2939. this.updateMassProperties();
  2940. this.updateBoundingRadius();
  2941. this.aabbNeedsUpdate = true;
  2942. shape.body = this;
  2943. return this;
  2944. }
  2945. /**
  2946. * Remove a shape from the body.
  2947. * @return The body object, for chainability.
  2948. */
  2949. removeShape(shape) {
  2950. const index = this.shapes.indexOf(shape);
  2951. if (index === -1) {
  2952. console.warn('Shape does not belong to the body');
  2953. return this;
  2954. }
  2955. this.shapes.splice(index, 1);
  2956. this.shapeOffsets.splice(index, 1);
  2957. this.shapeOrientations.splice(index, 1);
  2958. this.updateMassProperties();
  2959. this.updateBoundingRadius();
  2960. this.aabbNeedsUpdate = true;
  2961. shape.body = null;
  2962. return this;
  2963. }
  2964. /**
  2965. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  2966. */
  2967. updateBoundingRadius() {
  2968. const shapes = this.shapes;
  2969. const shapeOffsets = this.shapeOffsets;
  2970. const N = shapes.length;
  2971. let radius = 0;
  2972. for (let i = 0; i !== N; i++) {
  2973. const shape = shapes[i];
  2974. shape.updateBoundingSphereRadius();
  2975. const offset = shapeOffsets[i].length();
  2976. const r = shape.boundingSphereRadius;
  2977. if (offset + r > radius) {
  2978. radius = offset + r;
  2979. }
  2980. }
  2981. this.boundingRadius = radius;
  2982. }
  2983. /**
  2984. * Updates the .aabb
  2985. */
  2986. updateAABB() {
  2987. const shapes = this.shapes;
  2988. const shapeOffsets = this.shapeOffsets;
  2989. const shapeOrientations = this.shapeOrientations;
  2990. const N = shapes.length;
  2991. const offset = tmpVec;
  2992. const orientation = tmpQuat;
  2993. const bodyQuat = this.quaternion;
  2994. const aabb = this.aabb;
  2995. const shapeAABB = updateAABB_shapeAABB;
  2996. for (let i = 0; i !== N; i++) {
  2997. const shape = shapes[i]; // Get shape world position
  2998. bodyQuat.vmult(shapeOffsets[i], offset);
  2999. offset.vadd(this.position, offset); // Get shape world quaternion
  3000. bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB
  3001. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  3002. if (i === 0) {
  3003. aabb.copy(shapeAABB);
  3004. } else {
  3005. aabb.extend(shapeAABB);
  3006. }
  3007. }
  3008. this.aabbNeedsUpdate = false;
  3009. }
  3010. /**
  3011. * Update `.inertiaWorld` and `.invInertiaWorld`
  3012. */
  3013. updateInertiaWorld(force) {
  3014. const I = this.invInertia;
  3015. if (I.x === I.y && I.y === I.z && !force) ; else {
  3016. const m1 = uiw_m1;
  3017. const m2 = uiw_m2;
  3018. uiw_m3;
  3019. m1.setRotationFromQuaternion(this.quaternion);
  3020. m1.transpose(m2);
  3021. m1.scale(I, m1);
  3022. m1.mmult(m2, this.invInertiaWorld);
  3023. }
  3024. }
  3025. /**
  3026. * Apply force to a point of the body. This could for example be a point on the Body surface.
  3027. * Applying force this way will add to Body.force and Body.torque.
  3028. * @param force The amount of force to add.
  3029. * @param relativePoint A point relative to the center of mass to apply the force on.
  3030. */
  3031. applyForce(force, relativePoint) {
  3032. if (relativePoint === void 0) {
  3033. relativePoint = new Vec3();
  3034. }
  3035. // Needed?
  3036. if (this.type !== Body.DYNAMIC) {
  3037. return;
  3038. }
  3039. if (this.sleepState === Body.SLEEPING) {
  3040. this.wakeUp();
  3041. } // Compute produced rotational force
  3042. const rotForce = Body_applyForce_rotForce;
  3043. relativePoint.cross(force, rotForce); // Add linear force
  3044. this.force.vadd(force, this.force); // Add rotational force
  3045. this.torque.vadd(rotForce, this.torque);
  3046. }
  3047. /**
  3048. * Apply force to a local point in the body.
  3049. * @param force The force vector to apply, defined locally in the body frame.
  3050. * @param localPoint A local point in the body to apply the force on.
  3051. */
  3052. applyLocalForce(localForce, localPoint) {
  3053. if (localPoint === void 0) {
  3054. localPoint = new Vec3();
  3055. }
  3056. if (this.type !== Body.DYNAMIC) {
  3057. return;
  3058. }
  3059. const worldForce = Body_applyLocalForce_worldForce;
  3060. const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space
  3061. this.vectorToWorldFrame(localForce, worldForce);
  3062. this.vectorToWorldFrame(localPoint, relativePointWorld);
  3063. this.applyForce(worldForce, relativePointWorld);
  3064. }
  3065. /**
  3066. * Apply torque to the body.
  3067. * @param torque The amount of torque to add.
  3068. */
  3069. applyTorque(torque) {
  3070. if (this.type !== Body.DYNAMIC) {
  3071. return;
  3072. }
  3073. if (this.sleepState === Body.SLEEPING) {
  3074. this.wakeUp();
  3075. } // Add rotational force
  3076. this.torque.vadd(torque, this.torque);
  3077. }
  3078. /**
  3079. * Apply impulse to a point of the body. This could for example be a point on the Body surface.
  3080. * An impulse is a force added to a body during a short period of time (impulse = force * time).
  3081. * Impulses will be added to Body.velocity and Body.angularVelocity.
  3082. * @param impulse The amount of impulse to add.
  3083. * @param relativePoint A point relative to the center of mass to apply the force on.
  3084. */
  3085. applyImpulse(impulse, relativePoint) {
  3086. if (relativePoint === void 0) {
  3087. relativePoint = new Vec3();
  3088. }
  3089. if (this.type !== Body.DYNAMIC) {
  3090. return;
  3091. }
  3092. if (this.sleepState === Body.SLEEPING) {
  3093. this.wakeUp();
  3094. } // Compute point position relative to the body center
  3095. const r = relativePoint; // Compute produced central impulse velocity
  3096. const velo = Body_applyImpulse_velo;
  3097. velo.copy(impulse);
  3098. velo.scale(this.invMass, velo); // Add linear impulse
  3099. this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity
  3100. const rotVelo = Body_applyImpulse_rotVelo;
  3101. r.cross(impulse, rotVelo);
  3102. /*
  3103. rotVelo.x *= this.invInertia.x;
  3104. rotVelo.y *= this.invInertia.y;
  3105. rotVelo.z *= this.invInertia.z;
  3106. */
  3107. this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse
  3108. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  3109. }
  3110. /**
  3111. * Apply locally-defined impulse to a local point in the body.
  3112. * @param force The force vector to apply, defined locally in the body frame.
  3113. * @param localPoint A local point in the body to apply the force on.
  3114. */
  3115. applyLocalImpulse(localImpulse, localPoint) {
  3116. if (localPoint === void 0) {
  3117. localPoint = new Vec3();
  3118. }
  3119. if (this.type !== Body.DYNAMIC) {
  3120. return;
  3121. }
  3122. const worldImpulse = Body_applyLocalImpulse_worldImpulse;
  3123. const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space
  3124. this.vectorToWorldFrame(localImpulse, worldImpulse);
  3125. this.vectorToWorldFrame(localPoint, relativePointWorld);
  3126. this.applyImpulse(worldImpulse, relativePointWorld);
  3127. }
  3128. /**
  3129. * Should be called whenever you change the body shape or mass.
  3130. */
  3131. updateMassProperties() {
  3132. const halfExtents = Body_updateMassProperties_halfExtents;
  3133. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  3134. const I = this.inertia;
  3135. const fixed = this.fixedRotation; // Approximate with AABB box
  3136. this.updateAABB();
  3137. 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);
  3138. Box.calculateInertia(halfExtents, this.mass, I);
  3139. 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);
  3140. this.updateInertiaWorld(true);
  3141. }
  3142. /**
  3143. * Get world velocity of a point in the body.
  3144. * @param worldPoint
  3145. * @param result
  3146. * @return The result vector.
  3147. */
  3148. getVelocityAtWorldPoint(worldPoint, result) {
  3149. const r = new Vec3();
  3150. worldPoint.vsub(this.position, r);
  3151. this.angularVelocity.cross(r, result);
  3152. this.velocity.vadd(result, result);
  3153. return result;
  3154. }
  3155. /**
  3156. * Move the body forward in time.
  3157. * @param dt Time step
  3158. * @param quatNormalize Set to true to normalize the body quaternion
  3159. * @param quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
  3160. */
  3161. integrate(dt, quatNormalize, quatNormalizeFast) {
  3162. // Save previous position
  3163. this.previousPosition.copy(this.position);
  3164. this.previousQuaternion.copy(this.quaternion);
  3165. if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {
  3166. // Only for dynamic
  3167. return;
  3168. }
  3169. const velo = this.velocity;
  3170. const angularVelo = this.angularVelocity;
  3171. const pos = this.position;
  3172. const force = this.force;
  3173. const torque = this.torque;
  3174. const quat = this.quaternion;
  3175. const invMass = this.invMass;
  3176. const invInertia = this.invInertiaWorld;
  3177. const linearFactor = this.linearFactor;
  3178. const iMdt = invMass * dt;
  3179. velo.x += force.x * iMdt * linearFactor.x;
  3180. velo.y += force.y * iMdt * linearFactor.y;
  3181. velo.z += force.z * iMdt * linearFactor.z;
  3182. const e = invInertia.elements;
  3183. const angularFactor = this.angularFactor;
  3184. const tx = torque.x * angularFactor.x;
  3185. const ty = torque.y * angularFactor.y;
  3186. const tz = torque.z * angularFactor.z;
  3187. angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);
  3188. angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);
  3189. angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz); // Use new velocity - leap frog
  3190. pos.x += velo.x * dt;
  3191. pos.y += velo.y * dt;
  3192. pos.z += velo.z * dt;
  3193. quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);
  3194. if (quatNormalize) {
  3195. if (quatNormalizeFast) {
  3196. quat.normalizeFast();
  3197. } else {
  3198. quat.normalize();
  3199. }
  3200. }
  3201. this.aabbNeedsUpdate = true; // Update world inertia
  3202. this.updateInertiaWorld();
  3203. }
  3204. }
  3205. Body.idCounter = 0;
  3206. Body.COLLIDE_EVENT_NAME = 'collide';
  3207. Body.DYNAMIC = BODY_TYPES.DYNAMIC;
  3208. Body.STATIC = BODY_TYPES.STATIC;
  3209. Body.KINEMATIC = BODY_TYPES.KINEMATIC;
  3210. Body.AWAKE = BODY_SLEEP_STATES.AWAKE;
  3211. Body.SLEEPY = BODY_SLEEP_STATES.SLEEPY;
  3212. Body.SLEEPING = BODY_SLEEP_STATES.SLEEPING;
  3213. Body.wakeupEvent = {
  3214. type: 'wakeup'
  3215. };
  3216. Body.sleepyEvent = {
  3217. type: 'sleepy'
  3218. };
  3219. Body.sleepEvent = {
  3220. type: 'sleep'
  3221. };
  3222. const tmpVec = new Vec3();
  3223. const tmpQuat = new Quaternion();
  3224. const updateAABB_shapeAABB = new AABB();
  3225. const uiw_m1 = new Mat3();
  3226. const uiw_m2 = new Mat3();
  3227. const uiw_m3 = new Mat3();
  3228. const Body_applyForce_rotForce = new Vec3();
  3229. const Body_applyLocalForce_worldForce = new Vec3();
  3230. const Body_applyLocalForce_relativePointWorld = new Vec3();
  3231. const Body_applyImpulse_velo = new Vec3();
  3232. const Body_applyImpulse_rotVelo = new Vec3();
  3233. const Body_applyLocalImpulse_worldImpulse = new Vec3();
  3234. const Body_applyLocalImpulse_relativePoint = new Vec3();
  3235. const Body_updateMassProperties_halfExtents = new Vec3();
  3236. /**
  3237. * Base class for broadphase implementations
  3238. * @author schteppe
  3239. */
  3240. class Broadphase {
  3241. /**
  3242. * The world to search for collisions in.
  3243. */
  3244. /**
  3245. * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres.
  3246. */
  3247. /**
  3248. * Set to true if the objects in the world moved.
  3249. */
  3250. constructor() {
  3251. this.world = null;
  3252. this.useBoundingBoxes = false;
  3253. this.dirty = true;
  3254. }
  3255. /**
  3256. * Get the collision pairs from the world
  3257. * @param world The world to search in
  3258. * @param p1 Empty array to be filled with body objects
  3259. * @param p2 Empty array to be filled with body objects
  3260. */
  3261. collisionPairs(world, p1, p2) {
  3262. throw new Error('collisionPairs not implemented for this BroadPhase class!');
  3263. }
  3264. /**
  3265. * Check if a body pair needs to be intersection tested at all.
  3266. */
  3267. needBroadphaseCollision(bodyA, bodyB) {
  3268. // Check collision filter masks
  3269. if ((bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0) {
  3270. return false;
  3271. } // Check types
  3272. if (((bodyA.type & Body.STATIC) !== 0 || bodyA.sleepState === Body.SLEEPING) && ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING)) {
  3273. // Both bodies are static or sleeping. Skip.
  3274. return false;
  3275. }
  3276. return true;
  3277. }
  3278. /**
  3279. * Check if the bounding volumes of two bodies intersect.
  3280. */
  3281. intersectionTest(bodyA, bodyB, pairs1, pairs2) {
  3282. if (this.useBoundingBoxes) {
  3283. this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2);
  3284. } else {
  3285. this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2);
  3286. }
  3287. }
  3288. /**
  3289. * Check if the bounding spheres of two bodies are intersecting.
  3290. * @param pairs1 bodyA is appended to this array if intersection
  3291. * @param pairs2 bodyB is appended to this array if intersection
  3292. */
  3293. doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) {
  3294. const r = Broadphase_collisionPairs_r;
  3295. bodyB.position.vsub(bodyA.position, r);
  3296. const boundingRadiusSum2 = (bodyA.boundingRadius + bodyB.boundingRadius) ** 2;
  3297. const norm2 = r.lengthSquared();
  3298. if (norm2 < boundingRadiusSum2) {
  3299. pairs1.push(bodyA);
  3300. pairs2.push(bodyB);
  3301. }
  3302. }
  3303. /**
  3304. * Check if the bounding boxes of two bodies are intersecting.
  3305. */
  3306. doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) {
  3307. if (bodyA.aabbNeedsUpdate) {
  3308. bodyA.updateAABB();
  3309. }
  3310. if (bodyB.aabbNeedsUpdate) {
  3311. bodyB.updateAABB();
  3312. } // Check AABB / AABB
  3313. if (bodyA.aabb.overlaps(bodyB.aabb)) {
  3314. pairs1.push(bodyA);
  3315. pairs2.push(bodyB);
  3316. }
  3317. }
  3318. /**
  3319. * Removes duplicate pairs from the pair arrays.
  3320. */
  3321. makePairsUnique(pairs1, pairs2) {
  3322. const t = Broadphase_makePairsUnique_temp;
  3323. const p1 = Broadphase_makePairsUnique_p1;
  3324. const p2 = Broadphase_makePairsUnique_p2;
  3325. const N = pairs1.length;
  3326. for (let i = 0; i !== N; i++) {
  3327. p1[i] = pairs1[i];
  3328. p2[i] = pairs2[i];
  3329. }
  3330. pairs1.length = 0;
  3331. pairs2.length = 0;
  3332. for (let i = 0; i !== N; i++) {
  3333. const id1 = p1[i].id;
  3334. const id2 = p2[i].id;
  3335. const key = id1 < id2 ? `${id1},${id2}` : `${id2},${id1}`;
  3336. t[key] = i;
  3337. t.keys.push(key);
  3338. }
  3339. for (let i = 0; i !== t.keys.length; i++) {
  3340. const key = t.keys.pop();
  3341. const pairIndex = t[key];
  3342. pairs1.push(p1[pairIndex]);
  3343. pairs2.push(p2[pairIndex]);
  3344. delete t[key];
  3345. }
  3346. }
  3347. /**
  3348. * To be implemented by subcasses
  3349. */
  3350. setWorld(world) {}
  3351. /**
  3352. * Check if the bounding spheres of two bodies overlap.
  3353. */
  3354. static boundingSphereCheck(bodyA, bodyB) {
  3355. const dist = new Vec3(); // bsc_dist;
  3356. bodyA.position.vsub(bodyB.position, dist);
  3357. const sa = bodyA.shapes[0];
  3358. const sb = bodyB.shapes[0];
  3359. return Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > dist.lengthSquared();
  3360. }
  3361. /**
  3362. * Returns all the bodies within the AABB.
  3363. */
  3364. aabbQuery(world, aabb, result) {
  3365. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  3366. return [];
  3367. }
  3368. } // Temp objects
  3369. const Broadphase_collisionPairs_r = new Vec3();
  3370. new Vec3();
  3371. new Quaternion();
  3372. new Vec3();
  3373. const Broadphase_makePairsUnique_temp = {
  3374. keys: []
  3375. };
  3376. const Broadphase_makePairsUnique_p1 = [];
  3377. const Broadphase_makePairsUnique_p2 = [];
  3378. new Vec3();
  3379. /**
  3380. * Axis aligned uniform grid broadphase.
  3381. * @todo Needs support for more than just planes and spheres.
  3382. */
  3383. class GridBroadphase extends Broadphase {
  3384. /**
  3385. * Number of boxes along x
  3386. */
  3387. /**
  3388. * Number of boxes along y
  3389. */
  3390. /**
  3391. * Number of boxes along z
  3392. */
  3393. /**
  3394. * aabbMin
  3395. */
  3396. /**
  3397. * aabbMax
  3398. */
  3399. /**
  3400. * bins
  3401. */
  3402. /**
  3403. * binLengths
  3404. */
  3405. /**
  3406. * @param nx Number of boxes along x.
  3407. * @param ny Number of boxes along y.
  3408. * @param nz Number of boxes along z.
  3409. */
  3410. constructor(aabbMin, aabbMax, nx, ny, nz) {
  3411. if (aabbMin === void 0) {
  3412. aabbMin = new Vec3(100, 100, 100);
  3413. }
  3414. if (aabbMax === void 0) {
  3415. aabbMax = new Vec3(-100, -100, -100);
  3416. }
  3417. if (nx === void 0) {
  3418. nx = 10;
  3419. }
  3420. if (ny === void 0) {
  3421. ny = 10;
  3422. }
  3423. if (nz === void 0) {
  3424. nz = 10;
  3425. }
  3426. super();
  3427. this.nx = nx;
  3428. this.ny = ny;
  3429. this.nz = nz;
  3430. this.aabbMin = aabbMin;
  3431. this.aabbMax = aabbMax;
  3432. const nbins = this.nx * this.ny * this.nz;
  3433. if (nbins <= 0) {
  3434. throw "GridBroadphase: Each dimension's n must be >0";
  3435. }
  3436. this.bins = [];
  3437. this.binLengths = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  3438. this.bins.length = nbins;
  3439. this.binLengths.length = nbins;
  3440. for (let i = 0; i < nbins; i++) {
  3441. this.bins[i] = [];
  3442. this.binLengths[i] = 0;
  3443. }
  3444. }
  3445. /**
  3446. * Get all the collision pairs in the physics world
  3447. */
  3448. collisionPairs(world, pairs1, pairs2) {
  3449. const N = world.bodies.length;
  3450. const bodies = world.bodies;
  3451. const max = this.aabbMax;
  3452. const min = this.aabbMin;
  3453. const nx = this.nx;
  3454. const ny = this.ny;
  3455. const nz = this.nz;
  3456. const xstep = ny * nz;
  3457. const ystep = nz;
  3458. const zstep = 1;
  3459. const xmax = max.x;
  3460. const ymax = max.y;
  3461. const zmax = max.z;
  3462. const xmin = min.x;
  3463. const ymin = min.y;
  3464. const zmin = min.z;
  3465. const xmult = nx / (xmax - xmin);
  3466. const ymult = ny / (ymax - ymin);
  3467. const zmult = nz / (zmax - zmin);
  3468. const binsizeX = (xmax - xmin) / nx;
  3469. const binsizeY = (ymax - ymin) / ny;
  3470. const binsizeZ = (zmax - zmin) / nz;
  3471. const binRadius = Math.sqrt(binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ) * 0.5;
  3472. const types = Shape.types;
  3473. const SPHERE = types.SPHERE;
  3474. const PLANE = types.PLANE;
  3475. types.BOX;
  3476. types.COMPOUND;
  3477. types.CONVEXPOLYHEDRON;
  3478. const bins = this.bins;
  3479. const binLengths = this.binLengths;
  3480. const Nbins = this.bins.length; // Reset bins
  3481. for (let i = 0; i !== Nbins; i++) {
  3482. binLengths[i] = 0;
  3483. }
  3484. const ceil = Math.ceil;
  3485. function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) {
  3486. let xoff0 = (x0 - xmin) * xmult | 0;
  3487. let yoff0 = (y0 - ymin) * ymult | 0;
  3488. let zoff0 = (z0 - zmin) * zmult | 0;
  3489. let xoff1 = ceil((x1 - xmin) * xmult);
  3490. let yoff1 = ceil((y1 - ymin) * ymult);
  3491. let zoff1 = ceil((z1 - zmin) * zmult);
  3492. if (xoff0 < 0) {
  3493. xoff0 = 0;
  3494. } else if (xoff0 >= nx) {
  3495. xoff0 = nx - 1;
  3496. }
  3497. if (yoff0 < 0) {
  3498. yoff0 = 0;
  3499. } else if (yoff0 >= ny) {
  3500. yoff0 = ny - 1;
  3501. }
  3502. if (zoff0 < 0) {
  3503. zoff0 = 0;
  3504. } else if (zoff0 >= nz) {
  3505. zoff0 = nz - 1;
  3506. }
  3507. if (xoff1 < 0) {
  3508. xoff1 = 0;
  3509. } else if (xoff1 >= nx) {
  3510. xoff1 = nx - 1;
  3511. }
  3512. if (yoff1 < 0) {
  3513. yoff1 = 0;
  3514. } else if (yoff1 >= ny) {
  3515. yoff1 = ny - 1;
  3516. }
  3517. if (zoff1 < 0) {
  3518. zoff1 = 0;
  3519. } else if (zoff1 >= nz) {
  3520. zoff1 = nz - 1;
  3521. }
  3522. xoff0 *= xstep;
  3523. yoff0 *= ystep;
  3524. zoff0 *= zstep;
  3525. xoff1 *= xstep;
  3526. yoff1 *= ystep;
  3527. zoff1 *= zstep;
  3528. for (let xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  3529. for (let yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  3530. for (let zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  3531. const idx = xoff + yoff + zoff;
  3532. bins[idx][binLengths[idx]++] = bi;
  3533. }
  3534. }
  3535. }
  3536. } // Put all bodies into the bins
  3537. for (let i = 0; i !== N; i++) {
  3538. const bi = bodies[i];
  3539. const si = bi.shapes[0];
  3540. switch (si.type) {
  3541. case SPHERE:
  3542. {
  3543. const shape = si; // Put in bin
  3544. // check if overlap with other bins
  3545. const x = bi.position.x;
  3546. const y = bi.position.y;
  3547. const z = bi.position.z;
  3548. const r = shape.radius;
  3549. addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi);
  3550. break;
  3551. }
  3552. case PLANE:
  3553. {
  3554. const shape = si;
  3555. if (shape.worldNormalNeedsUpdate) {
  3556. shape.computeWorldNormal(bi.quaternion);
  3557. }
  3558. const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin
  3559. //Incremented as we iterate through the bins
  3560. const xreset = xmin + binsizeX * 0.5 - bi.position.x;
  3561. const yreset = ymin + binsizeY * 0.5 - bi.position.y;
  3562. const zreset = zmin + binsizeZ * 0.5 - bi.position.z;
  3563. const d = GridBroadphase_collisionPairs_d;
  3564. d.set(xreset, yreset, zreset);
  3565. for (let xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  3566. for (let yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  3567. for (let zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  3568. if (d.dot(planeNormal) < binRadius) {
  3569. const idx = xoff + yoff + zoff;
  3570. bins[idx][binLengths[idx]++] = bi;
  3571. }
  3572. }
  3573. }
  3574. }
  3575. break;
  3576. }
  3577. default:
  3578. {
  3579. if (bi.aabbNeedsUpdate) {
  3580. bi.updateAABB();
  3581. }
  3582. 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);
  3583. break;
  3584. }
  3585. }
  3586. } // Check each bin
  3587. for (let i = 0; i !== Nbins; i++) {
  3588. const binLength = binLengths[i]; //Skip bins with no potential collisions
  3589. if (binLength > 1) {
  3590. const bin = bins[i]; // Do N^2 broadphase inside
  3591. for (let xi = 0; xi !== binLength; xi++) {
  3592. const bi = bin[xi];
  3593. for (let yi = 0; yi !== xi; yi++) {
  3594. const bj = bin[yi];
  3595. if (this.needBroadphaseCollision(bi, bj)) {
  3596. this.intersectionTest(bi, bj, pairs1, pairs2);
  3597. }
  3598. }
  3599. }
  3600. }
  3601. } // for (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  3602. // console.log("layer "+zi);
  3603. // for (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  3604. // const row = '';
  3605. // for (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  3606. // const idx = xoff + yoff + zoff;
  3607. // row += ' ' + binLengths[idx];
  3608. // }
  3609. // console.log(row);
  3610. // }
  3611. // }
  3612. this.makePairsUnique(pairs1, pairs2);
  3613. }
  3614. }
  3615. const GridBroadphase_collisionPairs_d = new Vec3();
  3616. new Vec3();
  3617. /**
  3618. * Naive broadphase implementation, used in lack of better ones.
  3619. *
  3620. * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_
  3621. */
  3622. class NaiveBroadphase extends Broadphase {
  3623. /**
  3624. * @todo Remove useless constructor
  3625. */
  3626. constructor() {
  3627. super();
  3628. }
  3629. /**
  3630. * Get all the collision pairs in the physics world
  3631. */
  3632. collisionPairs(world, pairs1, pairs2) {
  3633. const bodies = world.bodies;
  3634. const n = bodies.length;
  3635. let bi;
  3636. let bj; // Naive N^2 ftw!
  3637. for (let i = 0; i !== n; i++) {
  3638. for (let j = 0; j !== i; j++) {
  3639. bi = bodies[i];
  3640. bj = bodies[j];
  3641. if (!this.needBroadphaseCollision(bi, bj)) {
  3642. continue;
  3643. }
  3644. this.intersectionTest(bi, bj, pairs1, pairs2);
  3645. }
  3646. }
  3647. }
  3648. /**
  3649. * Returns all the bodies within an AABB.
  3650. * @param result An array to store resulting bodies in.
  3651. */
  3652. aabbQuery(world, aabb, result) {
  3653. if (result === void 0) {
  3654. result = [];
  3655. }
  3656. for (let i = 0; i < world.bodies.length; i++) {
  3657. const b = world.bodies[i];
  3658. if (b.aabbNeedsUpdate) {
  3659. b.updateAABB();
  3660. } // Ugly hack until Body gets aabb
  3661. if (b.aabb.overlaps(aabb)) {
  3662. result.push(b);
  3663. }
  3664. }
  3665. return result;
  3666. }
  3667. }
  3668. /**
  3669. * Storage for Ray casting data
  3670. */
  3671. class RaycastResult {
  3672. /**
  3673. * rayFromWorld
  3674. */
  3675. /**
  3676. * rayToWorld
  3677. */
  3678. /**
  3679. * hitNormalWorld
  3680. */
  3681. /**
  3682. * hitPointWorld
  3683. */
  3684. /**
  3685. * hasHit
  3686. */
  3687. /**
  3688. * shape
  3689. */
  3690. /**
  3691. * body
  3692. */
  3693. /**
  3694. * The index of the hit triangle, if the hit shape was a trimesh
  3695. */
  3696. /**
  3697. * Distance to the hit. Will be set to -1 if there was no hit
  3698. */
  3699. /**
  3700. * If the ray should stop traversing the bodies
  3701. */
  3702. constructor() {
  3703. this.rayFromWorld = new Vec3();
  3704. this.rayToWorld = new Vec3();
  3705. this.hitNormalWorld = new Vec3();
  3706. this.hitPointWorld = new Vec3();
  3707. this.hasHit = false;
  3708. this.shape = null;
  3709. this.body = null;
  3710. this.hitFaceIndex = -1;
  3711. this.distance = -1;
  3712. this.shouldStop = false;
  3713. }
  3714. /**
  3715. * Reset all result data.
  3716. */
  3717. reset() {
  3718. this.rayFromWorld.setZero();
  3719. this.rayToWorld.setZero();
  3720. this.hitNormalWorld.setZero();
  3721. this.hitPointWorld.setZero();
  3722. this.hasHit = false;
  3723. this.shape = null;
  3724. this.body = null;
  3725. this.hitFaceIndex = -1;
  3726. this.distance = -1;
  3727. this.shouldStop = false;
  3728. }
  3729. /**
  3730. * abort
  3731. */
  3732. abort() {
  3733. this.shouldStop = true;
  3734. }
  3735. /**
  3736. * Set result data.
  3737. */
  3738. set(rayFromWorld, rayToWorld, hitNormalWorld, hitPointWorld, shape, body, distance) {
  3739. this.rayFromWorld.copy(rayFromWorld);
  3740. this.rayToWorld.copy(rayToWorld);
  3741. this.hitNormalWorld.copy(hitNormalWorld);
  3742. this.hitPointWorld.copy(hitPointWorld);
  3743. this.shape = shape;
  3744. this.body = body;
  3745. this.distance = distance;
  3746. }
  3747. }
  3748. let _Shape$types$SPHERE, _Shape$types$PLANE, _Shape$types$BOX, _Shape$types$CYLINDER, _Shape$types$CONVEXPO, _Shape$types$HEIGHTFI, _Shape$types$TRIMESH;
  3749. /**
  3750. * RAY_MODES
  3751. */
  3752. const RAY_MODES = {
  3753. /** CLOSEST */
  3754. CLOSEST: 1,
  3755. /** ANY */
  3756. ANY: 2,
  3757. /** ALL */
  3758. ALL: 4
  3759. };
  3760. /**
  3761. * RayMode
  3762. */
  3763. _Shape$types$SPHERE = Shape.types.SPHERE;
  3764. _Shape$types$PLANE = Shape.types.PLANE;
  3765. _Shape$types$BOX = Shape.types.BOX;
  3766. _Shape$types$CYLINDER = Shape.types.CYLINDER;
  3767. _Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON;
  3768. _Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD;
  3769. _Shape$types$TRIMESH = Shape.types.TRIMESH;
  3770. /**
  3771. * A line in 3D space that intersects bodies and return points.
  3772. */
  3773. class Ray {
  3774. /**
  3775. * from
  3776. */
  3777. /**
  3778. * to
  3779. */
  3780. /**
  3781. * direction
  3782. */
  3783. /**
  3784. * The precision of the ray. Used when checking parallelity etc.
  3785. * @default 0.0001
  3786. */
  3787. /**
  3788. * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes.
  3789. * @default true
  3790. */
  3791. /**
  3792. * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0.
  3793. * @default false
  3794. */
  3795. /**
  3796. * collisionFilterMask
  3797. * @default -1
  3798. */
  3799. /**
  3800. * collisionFilterGroup
  3801. * @default -1
  3802. */
  3803. /**
  3804. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  3805. * @default RAY.ANY
  3806. */
  3807. /**
  3808. * Current result object.
  3809. */
  3810. /**
  3811. * Will be set to `true` during intersectWorld() if the ray hit anything.
  3812. */
  3813. /**
  3814. * User-provided result callback. Will be used if mode is Ray.ALL.
  3815. */
  3816. /**
  3817. * CLOSEST
  3818. */
  3819. /**
  3820. * ANY
  3821. */
  3822. /**
  3823. * ALL
  3824. */
  3825. get [_Shape$types$SPHERE]() {
  3826. return this._intersectSphere;
  3827. }
  3828. get [_Shape$types$PLANE]() {
  3829. return this._intersectPlane;
  3830. }
  3831. get [_Shape$types$BOX]() {
  3832. return this._intersectBox;
  3833. }
  3834. get [_Shape$types$CYLINDER]() {
  3835. return this._intersectConvex;
  3836. }
  3837. get [_Shape$types$CONVEXPO]() {
  3838. return this._intersectConvex;
  3839. }
  3840. get [_Shape$types$HEIGHTFI]() {
  3841. return this._intersectHeightfield;
  3842. }
  3843. get [_Shape$types$TRIMESH]() {
  3844. return this._intersectTrimesh;
  3845. }
  3846. constructor(from, to) {
  3847. if (from === void 0) {
  3848. from = new Vec3();
  3849. }
  3850. if (to === void 0) {
  3851. to = new Vec3();
  3852. }
  3853. this.from = from.clone();
  3854. this.to = to.clone();
  3855. this.direction = new Vec3();
  3856. this.precision = 0.0001;
  3857. this.checkCollisionResponse = true;
  3858. this.skipBackfaces = false;
  3859. this.collisionFilterMask = -1;
  3860. this.collisionFilterGroup = -1;
  3861. this.mode = Ray.ANY;
  3862. this.result = new RaycastResult();
  3863. this.hasHit = false;
  3864. this.callback = result => {};
  3865. }
  3866. /**
  3867. * Do itersection against all bodies in the given World.
  3868. * @return True if the ray hit anything, otherwise false.
  3869. */
  3870. intersectWorld(world, options) {
  3871. this.mode = options.mode || Ray.ANY;
  3872. this.result = options.result || new RaycastResult();
  3873. this.skipBackfaces = !!options.skipBackfaces;
  3874. this.collisionFilterMask = typeof options.collisionFilterMask !== 'undefined' ? options.collisionFilterMask : -1;
  3875. this.collisionFilterGroup = typeof options.collisionFilterGroup !== 'undefined' ? options.collisionFilterGroup : -1;
  3876. this.checkCollisionResponse = typeof options.checkCollisionResponse !== 'undefined' ? options.checkCollisionResponse : true;
  3877. if (options.from) {
  3878. this.from.copy(options.from);
  3879. }
  3880. if (options.to) {
  3881. this.to.copy(options.to);
  3882. }
  3883. this.callback = options.callback || (() => {});
  3884. this.hasHit = false;
  3885. this.result.reset();
  3886. this.updateDirection();
  3887. this.getAABB(tmpAABB$1);
  3888. tmpArray.length = 0;
  3889. world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray);
  3890. this.intersectBodies(tmpArray);
  3891. return this.hasHit;
  3892. }
  3893. /**
  3894. * Shoot a ray at a body, get back information about the hit.
  3895. * @deprecated @param result set the result property of the Ray instead.
  3896. */
  3897. intersectBody(body, result) {
  3898. if (result) {
  3899. this.result = result;
  3900. this.updateDirection();
  3901. }
  3902. const checkCollisionResponse = this.checkCollisionResponse;
  3903. if (checkCollisionResponse && !body.collisionResponse) {
  3904. return;
  3905. }
  3906. if ((this.collisionFilterGroup & body.collisionFilterMask) === 0 || (body.collisionFilterGroup & this.collisionFilterMask) === 0) {
  3907. return;
  3908. }
  3909. const xi = intersectBody_xi;
  3910. const qi = intersectBody_qi;
  3911. for (let i = 0, N = body.shapes.length; i < N; i++) {
  3912. const shape = body.shapes[i];
  3913. if (checkCollisionResponse && !shape.collisionResponse) {
  3914. continue; // Skip
  3915. }
  3916. body.quaternion.mult(body.shapeOrientations[i], qi);
  3917. body.quaternion.vmult(body.shapeOffsets[i], xi);
  3918. xi.vadd(body.position, xi);
  3919. this.intersectShape(shape, qi, xi, body);
  3920. if (this.result.shouldStop) {
  3921. break;
  3922. }
  3923. }
  3924. }
  3925. /**
  3926. * Shoot a ray at an array bodies, get back information about the hit.
  3927. * @param bodies An array of Body objects.
  3928. * @deprecated @param result set the result property of the Ray instead.
  3929. *
  3930. */
  3931. intersectBodies(bodies, result) {
  3932. if (result) {
  3933. this.result = result;
  3934. this.updateDirection();
  3935. }
  3936. for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) {
  3937. this.intersectBody(bodies[i]);
  3938. }
  3939. }
  3940. /**
  3941. * Updates the direction vector.
  3942. */
  3943. updateDirection() {
  3944. this.to.vsub(this.from, this.direction);
  3945. this.direction.normalize();
  3946. }
  3947. intersectShape(shape, quat, position, body) {
  3948. const from = this.from; // Checking boundingSphere
  3949. const distance = distanceFromIntersection(from, this.direction, position);
  3950. if (distance > shape.boundingSphereRadius) {
  3951. return;
  3952. }
  3953. const intersectMethod = this[shape.type];
  3954. if (intersectMethod) {
  3955. intersectMethod.call(this, shape, quat, position, body, shape);
  3956. }
  3957. }
  3958. _intersectBox(box, quat, position, body, reportedShape) {
  3959. return this._intersectConvex(box.convexPolyhedronRepresentation, quat, position, body, reportedShape);
  3960. }
  3961. _intersectPlane(shape, quat, position, body, reportedShape) {
  3962. const from = this.from;
  3963. const to = this.to;
  3964. const direction = this.direction; // Get plane normal
  3965. const worldNormal = new Vec3(0, 0, 1);
  3966. quat.vmult(worldNormal, worldNormal);
  3967. const len = new Vec3();
  3968. from.vsub(position, len);
  3969. const planeToFrom = len.dot(worldNormal);
  3970. to.vsub(position, len);
  3971. const planeToTo = len.dot(worldNormal);
  3972. if (planeToFrom * planeToTo > 0) {
  3973. // "from" and "to" are on the same side of the plane... bail out
  3974. return;
  3975. }
  3976. if (from.distanceTo(to) < planeToFrom) {
  3977. return;
  3978. }
  3979. const n_dot_dir = worldNormal.dot(direction);
  3980. if (Math.abs(n_dot_dir) < this.precision) {
  3981. // No intersection
  3982. return;
  3983. }
  3984. const planePointToFrom = new Vec3();
  3985. const dir_scaled_with_t = new Vec3();
  3986. const hitPointWorld = new Vec3();
  3987. from.vsub(position, planePointToFrom);
  3988. const t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  3989. direction.scale(t, dir_scaled_with_t);
  3990. from.vadd(dir_scaled_with_t, hitPointWorld);
  3991. this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);
  3992. }
  3993. /**
  3994. * Get the world AABB of the ray.
  3995. */
  3996. getAABB(aabb) {
  3997. const {
  3998. lowerBound,
  3999. upperBound
  4000. } = aabb;
  4001. const to = this.to;
  4002. const from = this.from;
  4003. lowerBound.x = Math.min(to.x, from.x);
  4004. lowerBound.y = Math.min(to.y, from.y);
  4005. lowerBound.z = Math.min(to.z, from.z);
  4006. upperBound.x = Math.max(to.x, from.x);
  4007. upperBound.y = Math.max(to.y, from.y);
  4008. upperBound.z = Math.max(to.z, from.z);
  4009. }
  4010. _intersectHeightfield(shape, quat, position, body, reportedShape) {
  4011. shape.data;
  4012. shape.elementSize; // Convert the ray to local heightfield coordinates
  4013. const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);
  4014. localRay.from.copy(this.from);
  4015. localRay.to.copy(this.to);
  4016. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  4017. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  4018. localRay.updateDirection(); // Get the index of the data points to test against
  4019. const index = intersectHeightfield_index;
  4020. let iMinX;
  4021. let iMinY;
  4022. let iMaxX;
  4023. let iMaxY; // Set to max
  4024. iMinX = iMinY = 0;
  4025. iMaxX = iMaxY = shape.data.length - 1;
  4026. const aabb = new AABB();
  4027. localRay.getAABB(aabb);
  4028. shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);
  4029. iMinX = Math.max(iMinX, index[0]);
  4030. iMinY = Math.max(iMinY, index[1]);
  4031. shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);
  4032. iMaxX = Math.min(iMaxX, index[0] + 1);
  4033. iMaxY = Math.min(iMaxY, index[1] + 1);
  4034. for (let i = iMinX; i < iMaxX; i++) {
  4035. for (let j = iMinY; j < iMaxY; j++) {
  4036. if (this.result.shouldStop) {
  4037. return;
  4038. }
  4039. shape.getAabbAtIndex(i, j, aabb);
  4040. if (!aabb.overlapsRay(localRay)) {
  4041. continue;
  4042. } // Lower triangle
  4043. shape.getConvexTrianglePillar(i, j, false);
  4044. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  4045. this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
  4046. if (this.result.shouldStop) {
  4047. return;
  4048. } // Upper triangle
  4049. shape.getConvexTrianglePillar(i, j, true);
  4050. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  4051. this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
  4052. }
  4053. }
  4054. }
  4055. _intersectSphere(sphere, quat, position, body, reportedShape) {
  4056. const from = this.from;
  4057. const to = this.to;
  4058. const r = sphere.radius;
  4059. const a = (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2;
  4060. 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));
  4061. const c = (from.x - position.x) ** 2 + (from.y - position.y) ** 2 + (from.z - position.z) ** 2 - r ** 2;
  4062. const delta = b ** 2 - 4 * a * c;
  4063. const intersectionPoint = Ray_intersectSphere_intersectionPoint;
  4064. const normal = Ray_intersectSphere_normal;
  4065. if (delta < 0) {
  4066. // No intersection
  4067. return;
  4068. } else if (delta === 0) {
  4069. // single intersection point
  4070. from.lerp(to, delta, intersectionPoint);
  4071. intersectionPoint.vsub(position, normal);
  4072. normal.normalize();
  4073. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4074. } else {
  4075. const d1 = (-b - Math.sqrt(delta)) / (2 * a);
  4076. const d2 = (-b + Math.sqrt(delta)) / (2 * a);
  4077. if (d1 >= 0 && d1 <= 1) {
  4078. from.lerp(to, d1, intersectionPoint);
  4079. intersectionPoint.vsub(position, normal);
  4080. normal.normalize();
  4081. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4082. }
  4083. if (this.result.shouldStop) {
  4084. return;
  4085. }
  4086. if (d2 >= 0 && d2 <= 1) {
  4087. from.lerp(to, d2, intersectionPoint);
  4088. intersectionPoint.vsub(position, normal);
  4089. normal.normalize();
  4090. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4091. }
  4092. }
  4093. }
  4094. _intersectConvex(shape, quat, position, body, reportedShape, options) {
  4095. intersectConvex_minDistNormal;
  4096. const normal = intersectConvex_normal;
  4097. const vector = intersectConvex_vector;
  4098. intersectConvex_minDistIntersect;
  4099. const faceList = options && options.faceList || null; // Checking faces
  4100. const faces = shape.faces;
  4101. const vertices = shape.vertices;
  4102. const normals = shape.faceNormals;
  4103. const direction = this.direction;
  4104. const from = this.from;
  4105. const to = this.to;
  4106. const fromToDistance = from.distanceTo(to);
  4107. const Nfaces = faceList ? faceList.length : faces.length;
  4108. const result = this.result;
  4109. for (let j = 0; !result.shouldStop && j < Nfaces; j++) {
  4110. const fi = faceList ? faceList[j] : j;
  4111. const face = faces[fi];
  4112. const faceNormal = normals[fi];
  4113. const q = quat;
  4114. const x = position; // determine if ray intersects the plane of the face
  4115. // note: this works regardless of the direction of the face normal
  4116. // Get plane point in world coordinates...
  4117. vector.copy(vertices[face[0]]);
  4118. q.vmult(vector, vector);
  4119. vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later.
  4120. vector.vsub(from, vector); // Get plane normal
  4121. q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting
  4122. const dot = direction.dot(normal); // Bail out if ray and plane are parallel
  4123. if (Math.abs(dot) < this.precision) {
  4124. continue;
  4125. } // calc distance to plane
  4126. const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray
  4127. if (scalar < 0) {
  4128. continue;
  4129. } // if (dot < 0) {
  4130. // Intersection point is from + direction * scalar
  4131. direction.scale(scalar, intersectPoint);
  4132. intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with.
  4133. a.copy(vertices[face[0]]);
  4134. q.vmult(a, a);
  4135. x.vadd(a, a);
  4136. for (let i = 1; !result.shouldStop && i < face.length - 1; i++) {
  4137. // Transform 3 vertices to world coords
  4138. b.copy(vertices[face[i]]);
  4139. c.copy(vertices[face[i + 1]]);
  4140. q.vmult(b, b);
  4141. q.vmult(c, c);
  4142. x.vadd(b, b);
  4143. x.vadd(c, c);
  4144. const distance = intersectPoint.distanceTo(from);
  4145. if (!(Ray.pointInTriangle(intersectPoint, a, b, c) || Ray.pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance) {
  4146. continue;
  4147. }
  4148. this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);
  4149. } // }
  4150. }
  4151. }
  4152. /**
  4153. * @todo Optimize by transforming the world to local space first.
  4154. * @todo Use Octree lookup
  4155. */
  4156. _intersectTrimesh(mesh, quat, position, body, reportedShape, options) {
  4157. const normal = intersectTrimesh_normal;
  4158. const triangles = intersectTrimesh_triangles;
  4159. const treeTransform = intersectTrimesh_treeTransform;
  4160. const vector = intersectConvex_vector;
  4161. const localDirection = intersectTrimesh_localDirection;
  4162. const localFrom = intersectTrimesh_localFrom;
  4163. const localTo = intersectTrimesh_localTo;
  4164. const worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  4165. const worldNormal = intersectTrimesh_worldNormal; // Checking faces
  4166. const indices = mesh.indices;
  4167. mesh.vertices; // const normals = mesh.faceNormals
  4168. const from = this.from;
  4169. const to = this.to;
  4170. const direction = this.direction;
  4171. treeTransform.position.copy(position);
  4172. treeTransform.quaternion.copy(quat); // Transform ray to local space!
  4173. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  4174. Transform.pointToLocalFrame(position, quat, from, localFrom);
  4175. Transform.pointToLocalFrame(position, quat, to, localTo);
  4176. localTo.x *= mesh.scale.x;
  4177. localTo.y *= mesh.scale.y;
  4178. localTo.z *= mesh.scale.z;
  4179. localFrom.x *= mesh.scale.x;
  4180. localFrom.y *= mesh.scale.y;
  4181. localFrom.z *= mesh.scale.z;
  4182. localTo.vsub(localFrom, localDirection);
  4183. localDirection.normalize();
  4184. const fromToDistanceSquared = localFrom.distanceSquared(localTo);
  4185. mesh.tree.rayQuery(this, treeTransform, triangles);
  4186. for (let i = 0, N = triangles.length; !this.result.shouldStop && i !== N; i++) {
  4187. const trianglesIndex = triangles[i];
  4188. mesh.getNormal(trianglesIndex, normal); // determine if ray intersects the plane of the face
  4189. // note: this works regardless of the direction of the face normal
  4190. // Get plane point in world coordinates...
  4191. mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later.
  4192. a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting
  4193. const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel
  4194. // if (Math.abs( dot ) < this.precision){
  4195. // continue;
  4196. // }
  4197. // calc distance to plane
  4198. const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray
  4199. if (scalar < 0) {
  4200. continue;
  4201. } // Intersection point is from + direction * scalar
  4202. localDirection.scale(scalar, intersectPoint);
  4203. intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices
  4204. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  4205. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  4206. const squaredDistance = intersectPoint.distanceSquared(localFrom);
  4207. if (!(Ray.pointInTriangle(intersectPoint, b, a, c) || Ray.pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared) {
  4208. continue;
  4209. } // transform intersectpoint and normal to world
  4210. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  4211. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  4212. this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);
  4213. }
  4214. triangles.length = 0;
  4215. }
  4216. /**
  4217. * @return True if the intersections should continue
  4218. */
  4219. reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) {
  4220. const from = this.from;
  4221. const to = this.to;
  4222. const distance = from.distanceTo(hitPointWorld);
  4223. const result = this.result; // Skip back faces?
  4224. if (this.skipBackfaces && normal.dot(this.direction) > 0) {
  4225. return;
  4226. }
  4227. result.hitFaceIndex = typeof hitFaceIndex !== 'undefined' ? hitFaceIndex : -1;
  4228. switch (this.mode) {
  4229. case Ray.ALL:
  4230. this.hasHit = true;
  4231. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4232. result.hasHit = true;
  4233. this.callback(result);
  4234. break;
  4235. case Ray.CLOSEST:
  4236. // Store if closer than current closest
  4237. if (distance < result.distance || !result.hasHit) {
  4238. this.hasHit = true;
  4239. result.hasHit = true;
  4240. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4241. }
  4242. break;
  4243. case Ray.ANY:
  4244. // Report and stop.
  4245. this.hasHit = true;
  4246. result.hasHit = true;
  4247. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4248. result.shouldStop = true;
  4249. break;
  4250. }
  4251. }
  4252. /**
  4253. * As per "Barycentric Technique" as named
  4254. * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division
  4255. */
  4256. static pointInTriangle(p, a, b, c) {
  4257. c.vsub(a, v0);
  4258. b.vsub(a, v1);
  4259. p.vsub(a, v2);
  4260. const dot00 = v0.dot(v0);
  4261. const dot01 = v0.dot(v1);
  4262. const dot02 = v0.dot(v2);
  4263. const dot11 = v1.dot(v1);
  4264. const dot12 = v1.dot(v2);
  4265. let u;
  4266. let v;
  4267. return (u = dot11 * dot02 - dot01 * dot12) >= 0 && (v = dot00 * dot12 - dot01 * dot02) >= 0 && u + v < dot00 * dot11 - dot01 * dot01;
  4268. }
  4269. }
  4270. Ray.CLOSEST = RAY_MODES.CLOSEST;
  4271. Ray.ANY = RAY_MODES.ANY;
  4272. Ray.ALL = RAY_MODES.ALL;
  4273. const tmpAABB$1 = new AABB();
  4274. const tmpArray = [];
  4275. const v1 = new Vec3();
  4276. const v2 = new Vec3();
  4277. const intersectBody_xi = new Vec3();
  4278. const intersectBody_qi = new Quaternion();
  4279. const intersectPoint = new Vec3();
  4280. const a = new Vec3();
  4281. const b = new Vec3();
  4282. const c = new Vec3();
  4283. new Vec3();
  4284. new RaycastResult();
  4285. const intersectConvexOptions = {
  4286. faceList: [0]
  4287. };
  4288. const worldPillarOffset = new Vec3();
  4289. const intersectHeightfield_localRay = new Ray();
  4290. const intersectHeightfield_index = [];
  4291. const Ray_intersectSphere_intersectionPoint = new Vec3();
  4292. const Ray_intersectSphere_normal = new Vec3();
  4293. const intersectConvex_normal = new Vec3();
  4294. const intersectConvex_minDistNormal = new Vec3();
  4295. const intersectConvex_minDistIntersect = new Vec3();
  4296. const intersectConvex_vector = new Vec3();
  4297. const intersectTrimesh_normal = new Vec3();
  4298. const intersectTrimesh_localDirection = new Vec3();
  4299. const intersectTrimesh_localFrom = new Vec3();
  4300. const intersectTrimesh_localTo = new Vec3();
  4301. const intersectTrimesh_worldNormal = new Vec3();
  4302. const intersectTrimesh_worldIntersectPoint = new Vec3();
  4303. new AABB();
  4304. const intersectTrimesh_triangles = [];
  4305. const intersectTrimesh_treeTransform = new Transform();
  4306. const v0 = new Vec3();
  4307. const intersect = new Vec3();
  4308. function distanceFromIntersection(from, direction, position) {
  4309. // v0 is vector from from to position
  4310. position.vsub(from, v0);
  4311. const dot = v0.dot(direction); // intersect = direction*dot + from
  4312. direction.scale(dot, intersect);
  4313. intersect.vadd(from, intersect);
  4314. const distance = position.distanceTo(intersect);
  4315. return distance;
  4316. }
  4317. /**
  4318. * Sweep and prune broadphase along one axis.
  4319. */
  4320. class SAPBroadphase extends Broadphase {
  4321. /**
  4322. * List of bodies currently in the broadphase.
  4323. */
  4324. /**
  4325. * The world to search in.
  4326. */
  4327. /**
  4328. * Axis to sort the bodies along.
  4329. * Set to 0 for x axis, and 1 for y axis.
  4330. * For best performance, pick the axis where bodies are most distributed.
  4331. */
  4332. /**
  4333. * Check if the bounds of two bodies overlap, along the given SAP axis.
  4334. */
  4335. static checkBounds(bi, bj, axisIndex) {
  4336. let biPos;
  4337. let bjPos;
  4338. if (axisIndex === 0) {
  4339. biPos = bi.position.x;
  4340. bjPos = bj.position.x;
  4341. } else if (axisIndex === 1) {
  4342. biPos = bi.position.y;
  4343. bjPos = bj.position.y;
  4344. } else if (axisIndex === 2) {
  4345. biPos = bi.position.z;
  4346. bjPos = bj.position.z;
  4347. }
  4348. const ri = bi.boundingRadius,
  4349. rj = bj.boundingRadius,
  4350. boundA2 = biPos + ri,
  4351. boundB1 = bjPos - rj;
  4352. return boundB1 < boundA2;
  4353. } // Note: these are identical, save for x/y/z lowerbound
  4354. /**
  4355. * insertionSortX
  4356. */
  4357. static insertionSortX(a) {
  4358. for (let i = 1, l = a.length; i < l; i++) {
  4359. const v = a[i];
  4360. let j;
  4361. for (j = i - 1; j >= 0; j--) {
  4362. if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) {
  4363. break;
  4364. }
  4365. a[j + 1] = a[j];
  4366. }
  4367. a[j + 1] = v;
  4368. }
  4369. return a;
  4370. }
  4371. /**
  4372. * insertionSortY
  4373. */
  4374. static insertionSortY(a) {
  4375. for (let i = 1, l = a.length; i < l; i++) {
  4376. const v = a[i];
  4377. let j;
  4378. for (j = i - 1; j >= 0; j--) {
  4379. if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) {
  4380. break;
  4381. }
  4382. a[j + 1] = a[j];
  4383. }
  4384. a[j + 1] = v;
  4385. }
  4386. return a;
  4387. }
  4388. /**
  4389. * insertionSortZ
  4390. */
  4391. static insertionSortZ(a) {
  4392. for (let i = 1, l = a.length; i < l; i++) {
  4393. const v = a[i];
  4394. let j;
  4395. for (j = i - 1; j >= 0; j--) {
  4396. if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) {
  4397. break;
  4398. }
  4399. a[j + 1] = a[j];
  4400. }
  4401. a[j + 1] = v;
  4402. }
  4403. return a;
  4404. }
  4405. constructor(world) {
  4406. super();
  4407. this.axisList = [];
  4408. this.world = null;
  4409. this.axisIndex = 0;
  4410. const axisList = this.axisList;
  4411. this._addBodyHandler = event => {
  4412. axisList.push(event.body);
  4413. };
  4414. this._removeBodyHandler = event => {
  4415. const idx = axisList.indexOf(event.body);
  4416. if (idx !== -1) {
  4417. axisList.splice(idx, 1);
  4418. }
  4419. };
  4420. if (world) {
  4421. this.setWorld(world);
  4422. }
  4423. }
  4424. /**
  4425. * Change the world
  4426. */
  4427. setWorld(world) {
  4428. // Clear the old axis array
  4429. this.axisList.length = 0; // Add all bodies from the new world
  4430. for (let i = 0; i < world.bodies.length; i++) {
  4431. this.axisList.push(world.bodies[i]);
  4432. } // Remove old handlers, if any
  4433. world.removeEventListener('addBody', this._addBodyHandler);
  4434. world.removeEventListener('removeBody', this._removeBodyHandler); // Add handlers to update the list of bodies.
  4435. world.addEventListener('addBody', this._addBodyHandler);
  4436. world.addEventListener('removeBody', this._removeBodyHandler);
  4437. this.world = world;
  4438. this.dirty = true;
  4439. }
  4440. /**
  4441. * Collect all collision pairs
  4442. */
  4443. collisionPairs(world, p1, p2) {
  4444. const bodies = this.axisList;
  4445. const N = bodies.length;
  4446. const axisIndex = this.axisIndex;
  4447. let i;
  4448. let j;
  4449. if (this.dirty) {
  4450. this.sortList();
  4451. this.dirty = false;
  4452. } // Look through the list
  4453. for (i = 0; i !== N; i++) {
  4454. const bi = bodies[i];
  4455. for (j = i + 1; j < N; j++) {
  4456. const bj = bodies[j];
  4457. if (!this.needBroadphaseCollision(bi, bj)) {
  4458. continue;
  4459. }
  4460. if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) {
  4461. break;
  4462. }
  4463. this.intersectionTest(bi, bj, p1, p2);
  4464. }
  4465. }
  4466. }
  4467. sortList() {
  4468. const axisList = this.axisList;
  4469. const axisIndex = this.axisIndex;
  4470. const N = axisList.length; // Update AABBs
  4471. for (let i = 0; i !== N; i++) {
  4472. const bi = axisList[i];
  4473. if (bi.aabbNeedsUpdate) {
  4474. bi.updateAABB();
  4475. }
  4476. } // Sort the list
  4477. if (axisIndex === 0) {
  4478. SAPBroadphase.insertionSortX(axisList);
  4479. } else if (axisIndex === 1) {
  4480. SAPBroadphase.insertionSortY(axisList);
  4481. } else if (axisIndex === 2) {
  4482. SAPBroadphase.insertionSortZ(axisList);
  4483. }
  4484. }
  4485. /**
  4486. * Computes the variance of the body positions and estimates the best axis to use.
  4487. * Will automatically set property `axisIndex`.
  4488. */
  4489. autoDetectAxis() {
  4490. let sumX = 0;
  4491. let sumX2 = 0;
  4492. let sumY = 0;
  4493. let sumY2 = 0;
  4494. let sumZ = 0;
  4495. let sumZ2 = 0;
  4496. const bodies = this.axisList;
  4497. const N = bodies.length;
  4498. const invN = 1 / N;
  4499. for (let i = 0; i !== N; i++) {
  4500. const b = bodies[i];
  4501. const centerX = b.position.x;
  4502. sumX += centerX;
  4503. sumX2 += centerX * centerX;
  4504. const centerY = b.position.y;
  4505. sumY += centerY;
  4506. sumY2 += centerY * centerY;
  4507. const centerZ = b.position.z;
  4508. sumZ += centerZ;
  4509. sumZ2 += centerZ * centerZ;
  4510. }
  4511. const varianceX = sumX2 - sumX * sumX * invN;
  4512. const varianceY = sumY2 - sumY * sumY * invN;
  4513. const varianceZ = sumZ2 - sumZ * sumZ * invN;
  4514. if (varianceX > varianceY) {
  4515. if (varianceX > varianceZ) {
  4516. this.axisIndex = 0;
  4517. } else {
  4518. this.axisIndex = 2;
  4519. }
  4520. } else if (varianceY > varianceZ) {
  4521. this.axisIndex = 1;
  4522. } else {
  4523. this.axisIndex = 2;
  4524. }
  4525. }
  4526. /**
  4527. * Returns all the bodies within an AABB.
  4528. * @param result An array to store resulting bodies in.
  4529. */
  4530. aabbQuery(world, aabb, result) {
  4531. if (result === void 0) {
  4532. result = [];
  4533. }
  4534. if (this.dirty) {
  4535. this.sortList();
  4536. this.dirty = false;
  4537. }
  4538. const axisIndex = this.axisIndex;
  4539. let axis = 'x';
  4540. if (axisIndex === 1) {
  4541. axis = 'y';
  4542. }
  4543. if (axisIndex === 2) {
  4544. axis = 'z';
  4545. }
  4546. const axisList = this.axisList;
  4547. aabb.lowerBound[axis];
  4548. aabb.upperBound[axis];
  4549. for (let i = 0; i < axisList.length; i++) {
  4550. const b = axisList[i];
  4551. if (b.aabbNeedsUpdate) {
  4552. b.updateAABB();
  4553. }
  4554. if (b.aabb.overlaps(aabb)) {
  4555. result.push(b);
  4556. }
  4557. }
  4558. return result;
  4559. }
  4560. }
  4561. class Utils {
  4562. /**
  4563. * Extend an options object with default values.
  4564. * @param options The options object. May be falsy: in this case, a new object is created and returned.
  4565. * @param defaults An object containing default values.
  4566. * @return The modified options object.
  4567. */
  4568. static defaults(options, defaults) {
  4569. if (options === void 0) {
  4570. options = {};
  4571. }
  4572. for (let key in defaults) {
  4573. if (!(key in options)) {
  4574. options[key] = defaults[key];
  4575. }
  4576. }
  4577. return options;
  4578. }
  4579. }
  4580. /**
  4581. * Constraint base class
  4582. */
  4583. class Constraint {
  4584. /**
  4585. * Equations to be solved in this constraint.
  4586. */
  4587. /**
  4588. * Body A.
  4589. */
  4590. /**
  4591. * Body B.
  4592. */
  4593. /**
  4594. * Set to false if you don't want the bodies to collide when they are connected.
  4595. */
  4596. constructor(bodyA, bodyB, options) {
  4597. if (options === void 0) {
  4598. options = {};
  4599. }
  4600. options = Utils.defaults(options, {
  4601. collideConnected: true,
  4602. wakeUpBodies: true
  4603. });
  4604. this.equations = [];
  4605. this.bodyA = bodyA;
  4606. this.bodyB = bodyB;
  4607. this.id = Constraint.idCounter++;
  4608. this.collideConnected = options.collideConnected;
  4609. if (options.wakeUpBodies) {
  4610. if (bodyA) {
  4611. bodyA.wakeUp();
  4612. }
  4613. if (bodyB) {
  4614. bodyB.wakeUp();
  4615. }
  4616. }
  4617. }
  4618. /**
  4619. * Update all the equations with data.
  4620. */
  4621. update() {
  4622. throw new Error('method update() not implmemented in this Constraint subclass!');
  4623. }
  4624. /**
  4625. * Enables all equations in the constraint.
  4626. */
  4627. enable() {
  4628. const eqs = this.equations;
  4629. for (let i = 0; i < eqs.length; i++) {
  4630. eqs[i].enabled = true;
  4631. }
  4632. }
  4633. /**
  4634. * Disables all equations in the constraint.
  4635. */
  4636. disable() {
  4637. const eqs = this.equations;
  4638. for (let i = 0; i < eqs.length; i++) {
  4639. eqs[i].enabled = false;
  4640. }
  4641. }
  4642. }
  4643. Constraint.idCounter = 0;
  4644. /**
  4645. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  4646. */
  4647. class JacobianElement {
  4648. /**
  4649. * spatial
  4650. */
  4651. /**
  4652. * rotational
  4653. */
  4654. constructor() {
  4655. this.spatial = new Vec3();
  4656. this.rotational = new Vec3();
  4657. }
  4658. /**
  4659. * Multiply with other JacobianElement
  4660. */
  4661. multiplyElement(element) {
  4662. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  4663. }
  4664. /**
  4665. * Multiply with two vectors
  4666. */
  4667. multiplyVectors(spatial, rotational) {
  4668. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  4669. }
  4670. }
  4671. /**
  4672. * Equation base class.
  4673. *
  4674. * `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.
  4675. */
  4676. class Equation {
  4677. /**
  4678. * Minimum (read: negative max) force to be applied by the constraint.
  4679. */
  4680. /**
  4681. * Maximum (read: positive max) force to be applied by the constraint.
  4682. */
  4683. /**
  4684. * SPOOK parameter
  4685. */
  4686. /**
  4687. * SPOOK parameter
  4688. */
  4689. /**
  4690. * SPOOK parameter
  4691. */
  4692. /**
  4693. * A number, proportional to the force added to the bodies.
  4694. */
  4695. constructor(bi, bj, minForce, maxForce) {
  4696. if (minForce === void 0) {
  4697. minForce = -1e6;
  4698. }
  4699. if (maxForce === void 0) {
  4700. maxForce = 1e6;
  4701. }
  4702. this.id = Equation.idCounter++;
  4703. this.minForce = minForce;
  4704. this.maxForce = maxForce;
  4705. this.bi = bi;
  4706. this.bj = bj;
  4707. this.a = 0.0; // SPOOK parameter
  4708. this.b = 0.0; // SPOOK parameter
  4709. this.eps = 0.0; // SPOOK parameter
  4710. this.jacobianElementA = new JacobianElement();
  4711. this.jacobianElementB = new JacobianElement();
  4712. this.enabled = true;
  4713. this.multiplier = 0;
  4714. this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params
  4715. }
  4716. /**
  4717. * Recalculates a, b, and eps.
  4718. *
  4719. * The Equation constructor sets typical SPOOK parameters as such:
  4720. * * `stiffness` = 1e7
  4721. * * `relaxation` = 4
  4722. * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._
  4723. */
  4724. setSpookParams(stiffness, relaxation, timeStep) {
  4725. const d = relaxation;
  4726. const k = stiffness;
  4727. const h = timeStep;
  4728. this.a = 4.0 / (h * (1 + 4 * d));
  4729. this.b = 4.0 * d / (1 + 4 * d);
  4730. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  4731. }
  4732. /**
  4733. * Computes the right hand side of the SPOOK equation
  4734. */
  4735. computeB(a, b, h) {
  4736. const GW = this.computeGW();
  4737. const Gq = this.computeGq();
  4738. const GiMf = this.computeGiMf();
  4739. return -Gq * a - GW * b - GiMf * h;
  4740. }
  4741. /**
  4742. * Computes G*q, where q are the generalized body coordinates
  4743. */
  4744. computeGq() {
  4745. const GA = this.jacobianElementA;
  4746. const GB = this.jacobianElementB;
  4747. const bi = this.bi;
  4748. const bj = this.bj;
  4749. const xi = bi.position;
  4750. const xj = bj.position;
  4751. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  4752. }
  4753. /**
  4754. * Computes G*W, where W are the body velocities
  4755. */
  4756. computeGW() {
  4757. const GA = this.jacobianElementA;
  4758. const GB = this.jacobianElementB;
  4759. const bi = this.bi;
  4760. const bj = this.bj;
  4761. const vi = bi.velocity;
  4762. const vj = bj.velocity;
  4763. const wi = bi.angularVelocity;
  4764. const wj = bj.angularVelocity;
  4765. return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  4766. }
  4767. /**
  4768. * Computes G*Wlambda, where W are the body velocities
  4769. */
  4770. computeGWlambda() {
  4771. const GA = this.jacobianElementA;
  4772. const GB = this.jacobianElementB;
  4773. const bi = this.bi;
  4774. const bj = this.bj;
  4775. const vi = bi.vlambda;
  4776. const vj = bj.vlambda;
  4777. const wi = bi.wlambda;
  4778. const wj = bj.wlambda;
  4779. return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  4780. }
  4781. /**
  4782. * 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.
  4783. */
  4784. computeGiMf() {
  4785. const GA = this.jacobianElementA;
  4786. const GB = this.jacobianElementB;
  4787. const bi = this.bi;
  4788. const bj = this.bj;
  4789. const fi = bi.force;
  4790. const ti = bi.torque;
  4791. const fj = bj.force;
  4792. const tj = bj.torque;
  4793. const invMassi = bi.invMassSolve;
  4794. const invMassj = bj.invMassSolve;
  4795. fi.scale(invMassi, iMfi);
  4796. fj.scale(invMassj, iMfj);
  4797. bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui);
  4798. bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj);
  4799. return GA.multiplyVectors(iMfi, invIi_vmult_taui) + GB.multiplyVectors(iMfj, invIj_vmult_tauj);
  4800. }
  4801. /**
  4802. * Computes G*inv(M)*G'
  4803. */
  4804. computeGiMGt() {
  4805. const GA = this.jacobianElementA;
  4806. const GB = this.jacobianElementB;
  4807. const bi = this.bi;
  4808. const bj = this.bj;
  4809. const invMassi = bi.invMassSolve;
  4810. const invMassj = bj.invMassSolve;
  4811. const invIi = bi.invInertiaWorldSolve;
  4812. const invIj = bj.invInertiaWorldSolve;
  4813. let result = invMassi + invMassj;
  4814. invIi.vmult(GA.rotational, tmp);
  4815. result += tmp.dot(GA.rotational);
  4816. invIj.vmult(GB.rotational, tmp);
  4817. result += tmp.dot(GB.rotational);
  4818. return result;
  4819. }
  4820. /**
  4821. * Add constraint velocity to the bodies.
  4822. */
  4823. addToWlambda(deltalambda) {
  4824. const GA = this.jacobianElementA;
  4825. const GB = this.jacobianElementB;
  4826. const bi = this.bi;
  4827. const bj = this.bj;
  4828. const temp = addToWlambda_temp; // Add to linear velocity
  4829. // v_lambda += inv(M) * delta_lamba * G
  4830. bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);
  4831. bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda); // Add to angular velocity
  4832. bi.invInertiaWorldSolve.vmult(GA.rotational, temp);
  4833. bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);
  4834. bj.invInertiaWorldSolve.vmult(GB.rotational, temp);
  4835. bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);
  4836. }
  4837. /**
  4838. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  4839. */
  4840. computeC() {
  4841. return this.computeGiMGt() + this.eps;
  4842. }
  4843. }
  4844. Equation.idCounter = 0;
  4845. const iMfi = new Vec3();
  4846. const iMfj = new Vec3();
  4847. const invIi_vmult_taui = new Vec3();
  4848. const invIj_vmult_tauj = new Vec3();
  4849. const tmp = new Vec3();
  4850. const addToWlambda_temp = new Vec3();
  4851. /**
  4852. * Contact/non-penetration constraint equation
  4853. */
  4854. class ContactEquation extends Equation {
  4855. /**
  4856. * "bounciness": u1 = -e*u0
  4857. */
  4858. /**
  4859. * World-oriented vector that goes from the center of bi to the contact point.
  4860. */
  4861. /**
  4862. * World-oriented vector that starts in body j position and goes to the contact point.
  4863. */
  4864. /**
  4865. * Contact normal, pointing out of body i.
  4866. */
  4867. constructor(bodyA, bodyB, maxForce) {
  4868. if (maxForce === void 0) {
  4869. maxForce = 1e6;
  4870. }
  4871. super(bodyA, bodyB, 0, maxForce);
  4872. this.restitution = 0.0;
  4873. this.ri = new Vec3();
  4874. this.rj = new Vec3();
  4875. this.ni = new Vec3();
  4876. }
  4877. computeB(h) {
  4878. const a = this.a;
  4879. const b = this.b;
  4880. const bi = this.bi;
  4881. const bj = this.bj;
  4882. const ri = this.ri;
  4883. const rj = this.rj;
  4884. const rixn = ContactEquation_computeB_temp1;
  4885. const rjxn = ContactEquation_computeB_temp2;
  4886. const vi = bi.velocity;
  4887. const wi = bi.angularVelocity;
  4888. bi.force;
  4889. bi.torque;
  4890. const vj = bj.velocity;
  4891. const wj = bj.angularVelocity;
  4892. bj.force;
  4893. bj.torque;
  4894. const penetrationVec = ContactEquation_computeB_temp3;
  4895. const GA = this.jacobianElementA;
  4896. const GB = this.jacobianElementB;
  4897. const n = this.ni; // Caluclate cross products
  4898. ri.cross(n, rixn);
  4899. rj.cross(n, rjxn); // g = xj+rj -(xi+ri)
  4900. // G = [ -ni -rixn ni rjxn ]
  4901. n.negate(GA.spatial);
  4902. rixn.negate(GA.rotational);
  4903. GB.spatial.copy(n);
  4904. GB.rotational.copy(rjxn); // Calculate the penetration vector
  4905. penetrationVec.copy(bj.position);
  4906. penetrationVec.vadd(rj, penetrationVec);
  4907. penetrationVec.vsub(bi.position, penetrationVec);
  4908. penetrationVec.vsub(ri, penetrationVec);
  4909. const g = n.dot(penetrationVec); // Compute iteration
  4910. const ePlusOne = this.restitution + 1;
  4911. const GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  4912. const GiMf = this.computeGiMf();
  4913. const B = -g * a - GW * b - h * GiMf;
  4914. return B;
  4915. }
  4916. /**
  4917. * Get the current relative velocity in the contact point.
  4918. */
  4919. getImpactVelocityAlongNormal() {
  4920. const vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  4921. const vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  4922. const xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  4923. const xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  4924. const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  4925. this.bi.position.vadd(this.ri, xi);
  4926. this.bj.position.vadd(this.rj, xj);
  4927. this.bi.getVelocityAtWorldPoint(xi, vi);
  4928. this.bj.getVelocityAtWorldPoint(xj, vj);
  4929. vi.vsub(vj, relVel);
  4930. return this.ni.dot(relVel);
  4931. }
  4932. }
  4933. const ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  4934. const ContactEquation_computeB_temp2 = new Vec3();
  4935. const ContactEquation_computeB_temp3 = new Vec3();
  4936. const ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  4937. const ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  4938. const ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  4939. const ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  4940. const ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  4941. /**
  4942. * Connects two bodies at given offset points.
  4943. * @example
  4944. * const bodyA = new Body({ mass: 1 })
  4945. * const bodyB = new Body({ mass: 1 })
  4946. * bodyA.position.set(-1, 0, 0)
  4947. * bodyB.position.set(1, 0, 0)
  4948. * bodyA.addShape(shapeA)
  4949. * bodyB.addShape(shapeB)
  4950. * world.addBody(bodyA)
  4951. * world.addBody(bodyB)
  4952. * const localPivotA = new Vec3(1, 0, 0)
  4953. * const localPivotB = new Vec3(-1, 0, 0)
  4954. * const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB)
  4955. * world.addConstraint(constraint)
  4956. */
  4957. class PointToPointConstraint extends Constraint {
  4958. /**
  4959. * Pivot, defined locally in bodyA.
  4960. */
  4961. /**
  4962. * Pivot, defined locally in bodyB.
  4963. */
  4964. /**
  4965. * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  4966. * @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.
  4967. * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to.
  4968. * @param maxForce The maximum force that should be applied to constrain the bodies.
  4969. */
  4970. constructor(bodyA, pivotA, bodyB, pivotB, maxForce) {
  4971. if (pivotA === void 0) {
  4972. pivotA = new Vec3();
  4973. }
  4974. if (pivotB === void 0) {
  4975. pivotB = new Vec3();
  4976. }
  4977. if (maxForce === void 0) {
  4978. maxForce = 1e6;
  4979. }
  4980. super(bodyA, bodyB);
  4981. this.pivotA = pivotA.clone();
  4982. this.pivotB = pivotB.clone();
  4983. const x = this.equationX = new ContactEquation(bodyA, bodyB);
  4984. const y = this.equationY = new ContactEquation(bodyA, bodyB);
  4985. const z = this.equationZ = new ContactEquation(bodyA, bodyB); // Equations to be fed to the solver
  4986. this.equations.push(x, y, z); // Make the equations bidirectional
  4987. x.minForce = y.minForce = z.minForce = -maxForce;
  4988. x.maxForce = y.maxForce = z.maxForce = maxForce;
  4989. x.ni.set(1, 0, 0);
  4990. y.ni.set(0, 1, 0);
  4991. z.ni.set(0, 0, 1);
  4992. }
  4993. update() {
  4994. const bodyA = this.bodyA;
  4995. const bodyB = this.bodyB;
  4996. const x = this.equationX;
  4997. const y = this.equationY;
  4998. const z = this.equationZ; // Rotate the pivots to world space
  4999. bodyA.quaternion.vmult(this.pivotA, x.ri);
  5000. bodyB.quaternion.vmult(this.pivotB, x.rj);
  5001. y.ri.copy(x.ri);
  5002. y.rj.copy(x.rj);
  5003. z.ri.copy(x.ri);
  5004. z.rj.copy(x.rj);
  5005. }
  5006. }
  5007. /**
  5008. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  5009. */
  5010. class ConeEquation extends Equation {
  5011. /**
  5012. * Local axis in A
  5013. */
  5014. /**
  5015. * Local axis in B
  5016. */
  5017. /**
  5018. * The "cone angle" to keep
  5019. */
  5020. constructor(bodyA, bodyB, options) {
  5021. if (options === void 0) {
  5022. options = {};
  5023. }
  5024. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5025. super(bodyA, bodyB, -maxForce, maxForce);
  5026. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5027. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  5028. this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  5029. }
  5030. computeB(h) {
  5031. const a = this.a;
  5032. const b = this.b;
  5033. const ni = this.axisA;
  5034. const nj = this.axisB;
  5035. const nixnj = tmpVec1$2;
  5036. const njxni = tmpVec2$2;
  5037. const GA = this.jacobianElementA;
  5038. const GB = this.jacobianElementB; // Caluclate cross products
  5039. ni.cross(nj, nixnj);
  5040. nj.cross(ni, njxni); // The angle between two vector is:
  5041. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  5042. // g = a * b
  5043. // gdot = (b x a) * wi + (a x b) * wj
  5044. // G = [0 bxa 0 axb]
  5045. // W = [vi wi vj wj]
  5046. GA.rotational.copy(njxni);
  5047. GB.rotational.copy(nixnj);
  5048. const g = Math.cos(this.angle) - ni.dot(nj);
  5049. const GW = this.computeGW();
  5050. const GiMf = this.computeGiMf();
  5051. const B = -g * a - GW * b - h * GiMf;
  5052. return B;
  5053. }
  5054. }
  5055. const tmpVec1$2 = new Vec3();
  5056. const tmpVec2$2 = new Vec3();
  5057. /**
  5058. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  5059. */
  5060. class RotationalEquation extends Equation {
  5061. /**
  5062. * World oriented rotational axis.
  5063. */
  5064. /**
  5065. * World oriented rotational axis.
  5066. */
  5067. /**
  5068. * maxAngle
  5069. */
  5070. constructor(bodyA, bodyB, options) {
  5071. if (options === void 0) {
  5072. options = {};
  5073. }
  5074. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5075. super(bodyA, bodyB, -maxForce, maxForce);
  5076. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5077. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  5078. this.maxAngle = Math.PI / 2;
  5079. }
  5080. computeB(h) {
  5081. const a = this.a;
  5082. const b = this.b;
  5083. const ni = this.axisA;
  5084. const nj = this.axisB;
  5085. const nixnj = tmpVec1$1;
  5086. const njxni = tmpVec2$1;
  5087. const GA = this.jacobianElementA;
  5088. const GB = this.jacobianElementB; // Caluclate cross products
  5089. ni.cross(nj, nixnj);
  5090. nj.cross(ni, njxni); // g = ni * nj
  5091. // gdot = (nj x ni) * wi + (ni x nj) * wj
  5092. // G = [0 njxni 0 nixnj]
  5093. // W = [vi wi vj wj]
  5094. GA.rotational.copy(njxni);
  5095. GB.rotational.copy(nixnj);
  5096. const g = Math.cos(this.maxAngle) - ni.dot(nj);
  5097. const GW = this.computeGW();
  5098. const GiMf = this.computeGiMf();
  5099. const B = -g * a - GW * b - h * GiMf;
  5100. return B;
  5101. }
  5102. }
  5103. const tmpVec1$1 = new Vec3();
  5104. const tmpVec2$1 = new Vec3();
  5105. /**
  5106. * A Cone Twist constraint, useful for ragdolls.
  5107. */
  5108. class ConeTwistConstraint extends PointToPointConstraint {
  5109. /**
  5110. * The axis direction for the constraint of the body A.
  5111. */
  5112. /**
  5113. * The axis direction for the constraint of the body B.
  5114. */
  5115. /**
  5116. * The aperture angle of the cone.
  5117. */
  5118. /**
  5119. * The twist angle of the joint.
  5120. */
  5121. constructor(bodyA, bodyB, options) {
  5122. if (options === void 0) {
  5123. options = {};
  5124. }
  5125. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between
  5126. const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  5127. const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  5128. super(bodyA, pivotA, bodyB, pivotB, maxForce);
  5129. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  5130. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  5131. this.collideConnected = !!options.collideConnected;
  5132. this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  5133. const c = this.coneEquation = new ConeEquation(bodyA, bodyB, options);
  5134. const t = this.twistEquation = new RotationalEquation(bodyA, bodyB, options);
  5135. this.twistAngle = typeof options.twistAngle !== 'undefined' ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward
  5136. c.maxForce = 0;
  5137. c.minForce = -maxForce; // Make the twist equation add torque toward the initial position
  5138. t.maxForce = 0;
  5139. t.minForce = -maxForce;
  5140. this.equations.push(c, t);
  5141. }
  5142. update() {
  5143. const bodyA = this.bodyA;
  5144. const bodyB = this.bodyB;
  5145. const cone = this.coneEquation;
  5146. const twist = this.twistEquation;
  5147. super.update(); // Update the axes to the cone constraint
  5148. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  5149. bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint
  5150. this.axisA.tangents(twist.axisA, twist.axisA);
  5151. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  5152. this.axisB.tangents(twist.axisB, twist.axisB);
  5153. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  5154. cone.angle = this.angle;
  5155. twist.maxAngle = this.twistAngle;
  5156. }
  5157. }
  5158. new Vec3();
  5159. new Vec3();
  5160. /**
  5161. * Constrains two bodies to be at a constant distance from each others center of mass.
  5162. */
  5163. class DistanceConstraint extends Constraint {
  5164. /**
  5165. * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  5166. */
  5167. /**
  5168. * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.
  5169. * @param maxForce The maximum force that should be applied to constrain the bodies.
  5170. */
  5171. constructor(bodyA, bodyB, distance, maxForce) {
  5172. if (maxForce === void 0) {
  5173. maxForce = 1e6;
  5174. }
  5175. super(bodyA, bodyB);
  5176. if (typeof distance === 'undefined') {
  5177. distance = bodyA.position.distanceTo(bodyB.position);
  5178. }
  5179. this.distance = distance;
  5180. const eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  5181. this.equations.push(eq); // Make it bidirectional
  5182. eq.minForce = -maxForce;
  5183. eq.maxForce = maxForce;
  5184. }
  5185. /**
  5186. * update
  5187. */
  5188. update() {
  5189. const bodyA = this.bodyA;
  5190. const bodyB = this.bodyB;
  5191. const eq = this.distanceEquation;
  5192. const halfDist = this.distance * 0.5;
  5193. const normal = eq.ni;
  5194. bodyB.position.vsub(bodyA.position, normal);
  5195. normal.normalize();
  5196. normal.scale(halfDist, eq.ri);
  5197. normal.scale(-halfDist, eq.rj);
  5198. }
  5199. }
  5200. /**
  5201. * Lock constraint. Will remove all degrees of freedom between the bodies.
  5202. */
  5203. class LockConstraint extends PointToPointConstraint {
  5204. constructor(bodyA, bodyB, options) {
  5205. if (options === void 0) {
  5206. options = {};
  5207. }
  5208. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between
  5209. const pivotA = new Vec3();
  5210. const pivotB = new Vec3();
  5211. const halfWay = new Vec3();
  5212. bodyA.position.vadd(bodyB.position, halfWay);
  5213. halfWay.scale(0.5, halfWay);
  5214. bodyB.pointToLocalFrame(halfWay, pivotB);
  5215. bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies
  5216. super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces
  5217. this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);
  5218. this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);
  5219. this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);
  5220. this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);
  5221. this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);
  5222. this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place
  5223. const r1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
  5224. const r2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
  5225. const r3 = this.rotationalEquation3 = new RotationalEquation(bodyA, bodyB, options);
  5226. this.equations.push(r1, r2, r3);
  5227. }
  5228. /**
  5229. * update
  5230. */
  5231. update() {
  5232. const bodyA = this.bodyA;
  5233. const bodyB = this.bodyB;
  5234. this.motorEquation;
  5235. const r1 = this.rotationalEquation1;
  5236. const r2 = this.rotationalEquation2;
  5237. const r3 = this.rotationalEquation3;
  5238. LockConstraint_update_tmpVec1;
  5239. LockConstraint_update_tmpVec2;
  5240. super.update(); // These vector pairs must be orthogonal
  5241. bodyA.vectorToWorldFrame(this.xA, r1.axisA);
  5242. bodyB.vectorToWorldFrame(this.yB, r1.axisB);
  5243. bodyA.vectorToWorldFrame(this.yA, r2.axisA);
  5244. bodyB.vectorToWorldFrame(this.zB, r2.axisB);
  5245. bodyA.vectorToWorldFrame(this.zA, r3.axisA);
  5246. bodyB.vectorToWorldFrame(this.xB, r3.axisB);
  5247. }
  5248. }
  5249. const LockConstraint_update_tmpVec1 = new Vec3();
  5250. const LockConstraint_update_tmpVec2 = new Vec3();
  5251. /**
  5252. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  5253. */
  5254. class RotationalMotorEquation extends Equation {
  5255. /**
  5256. * World oriented rotational axis.
  5257. */
  5258. /**
  5259. * World oriented rotational axis.
  5260. */
  5261. /**
  5262. * Motor velocity.
  5263. */
  5264. constructor(bodyA, bodyB, maxForce) {
  5265. if (maxForce === void 0) {
  5266. maxForce = 1e6;
  5267. }
  5268. super(bodyA, bodyB, -maxForce, maxForce);
  5269. this.axisA = new Vec3();
  5270. this.axisB = new Vec3();
  5271. this.targetVelocity = 0;
  5272. }
  5273. computeB(h) {
  5274. this.a;
  5275. const b = this.b;
  5276. this.bi;
  5277. this.bj;
  5278. const axisA = this.axisA;
  5279. const axisB = this.axisB;
  5280. const GA = this.jacobianElementA;
  5281. const GB = this.jacobianElementB; // g = 0
  5282. // gdot = axisA * wi - axisB * wj
  5283. // gdot = G * W = G * [vi wi vj wj]
  5284. // =>
  5285. // G = [0 axisA 0 -axisB]
  5286. GA.rotational.copy(axisA);
  5287. axisB.negate(GB.rotational);
  5288. const GW = this.computeGW() - this.targetVelocity;
  5289. const GiMf = this.computeGiMf();
  5290. const B = -GW * b - h * GiMf;
  5291. return B;
  5292. }
  5293. }
  5294. /**
  5295. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  5296. */
  5297. class HingeConstraint extends PointToPointConstraint {
  5298. /**
  5299. * Rotation axis, defined locally in bodyA.
  5300. */
  5301. /**
  5302. * Rotation axis, defined locally in bodyB.
  5303. */
  5304. constructor(bodyA, bodyB, options) {
  5305. if (options === void 0) {
  5306. options = {};
  5307. }
  5308. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5309. const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  5310. const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  5311. super(bodyA, pivotA, bodyB, pivotB, maxForce);
  5312. const axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5313. axisA.normalize();
  5314. const axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0);
  5315. axisB.normalize();
  5316. this.collideConnected = !!options.collideConnected;
  5317. const rotational1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
  5318. const rotational2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
  5319. const motor = this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce);
  5320. motor.enabled = false; // Not enabled by default
  5321. // Equations to be fed to the solver
  5322. this.equations.push(rotational1, rotational2, motor);
  5323. }
  5324. /**
  5325. * enableMotor
  5326. */
  5327. enableMotor() {
  5328. this.motorEquation.enabled = true;
  5329. }
  5330. /**
  5331. * disableMotor
  5332. */
  5333. disableMotor() {
  5334. this.motorEquation.enabled = false;
  5335. }
  5336. /**
  5337. * setMotorSpeed
  5338. */
  5339. setMotorSpeed(speed) {
  5340. this.motorEquation.targetVelocity = speed;
  5341. }
  5342. /**
  5343. * setMotorMaxForce
  5344. */
  5345. setMotorMaxForce(maxForce) {
  5346. this.motorEquation.maxForce = maxForce;
  5347. this.motorEquation.minForce = -maxForce;
  5348. }
  5349. /**
  5350. * update
  5351. */
  5352. update() {
  5353. const bodyA = this.bodyA;
  5354. const bodyB = this.bodyB;
  5355. const motor = this.motorEquation;
  5356. const r1 = this.rotationalEquation1;
  5357. const r2 = this.rotationalEquation2;
  5358. const worldAxisA = HingeConstraint_update_tmpVec1;
  5359. const worldAxisB = HingeConstraint_update_tmpVec2;
  5360. const axisA = this.axisA;
  5361. const axisB = this.axisB;
  5362. super.update(); // Get world axes
  5363. bodyA.quaternion.vmult(axisA, worldAxisA);
  5364. bodyB.quaternion.vmult(axisB, worldAxisB);
  5365. worldAxisA.tangents(r1.axisA, r2.axisA);
  5366. r1.axisB.copy(worldAxisB);
  5367. r2.axisB.copy(worldAxisB);
  5368. if (this.motorEquation.enabled) {
  5369. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  5370. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  5371. }
  5372. }
  5373. }
  5374. const HingeConstraint_update_tmpVec1 = new Vec3();
  5375. const HingeConstraint_update_tmpVec2 = new Vec3();
  5376. /**
  5377. * Constrains the slipping in a contact along a tangent
  5378. */
  5379. class FrictionEquation extends Equation {
  5380. // Tangent
  5381. /**
  5382. * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  5383. */
  5384. constructor(bodyA, bodyB, slipForce) {
  5385. super(bodyA, bodyB, -slipForce, slipForce);
  5386. this.ri = new Vec3();
  5387. this.rj = new Vec3();
  5388. this.t = new Vec3();
  5389. }
  5390. computeB(h) {
  5391. this.a;
  5392. const b = this.b;
  5393. this.bi;
  5394. this.bj;
  5395. const ri = this.ri;
  5396. const rj = this.rj;
  5397. const rixt = FrictionEquation_computeB_temp1;
  5398. const rjxt = FrictionEquation_computeB_temp2;
  5399. const t = this.t; // Caluclate cross products
  5400. ri.cross(t, rixt);
  5401. rj.cross(t, rjxt); // G = [-t -rixt t rjxt]
  5402. // And remember, this is a pure velocity constraint, g is always zero!
  5403. const GA = this.jacobianElementA;
  5404. const GB = this.jacobianElementB;
  5405. t.negate(GA.spatial);
  5406. rixt.negate(GA.rotational);
  5407. GB.spatial.copy(t);
  5408. GB.rotational.copy(rjxt);
  5409. const GW = this.computeGW();
  5410. const GiMf = this.computeGiMf();
  5411. const B = -GW * b - h * GiMf;
  5412. return B;
  5413. }
  5414. }
  5415. const FrictionEquation_computeB_temp1 = new Vec3();
  5416. const FrictionEquation_computeB_temp2 = new Vec3();
  5417. /**
  5418. * Defines what happens when two materials meet.
  5419. * @todo Refactor materials to materialA and materialB
  5420. */
  5421. class ContactMaterial {
  5422. /**
  5423. * Identifier of this material.
  5424. */
  5425. /**
  5426. * Participating materials.
  5427. */
  5428. /**
  5429. * Friction coefficient.
  5430. * @default 0.3
  5431. */
  5432. /**
  5433. * Restitution coefficient.
  5434. * @default 0.3
  5435. */
  5436. /**
  5437. * Stiffness of the produced contact equations.
  5438. * @default 1e7
  5439. */
  5440. /**
  5441. * Relaxation time of the produced contact equations.
  5442. * @default 3
  5443. */
  5444. /**
  5445. * Stiffness of the produced friction equations.
  5446. * @default 1e7
  5447. */
  5448. /**
  5449. * Relaxation time of the produced friction equations
  5450. * @default 3
  5451. */
  5452. constructor(m1, m2, options) {
  5453. options = Utils.defaults(options, {
  5454. friction: 0.3,
  5455. restitution: 0.3,
  5456. contactEquationStiffness: 1e7,
  5457. contactEquationRelaxation: 3,
  5458. frictionEquationStiffness: 1e7,
  5459. frictionEquationRelaxation: 3
  5460. });
  5461. this.id = ContactMaterial.idCounter++;
  5462. this.materials = [m1, m2];
  5463. this.friction = options.friction;
  5464. this.restitution = options.restitution;
  5465. this.contactEquationStiffness = options.contactEquationStiffness;
  5466. this.contactEquationRelaxation = options.contactEquationRelaxation;
  5467. this.frictionEquationStiffness = options.frictionEquationStiffness;
  5468. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  5469. }
  5470. }
  5471. ContactMaterial.idCounter = 0;
  5472. /**
  5473. * Defines a physics material.
  5474. */
  5475. class Material {
  5476. /**
  5477. * Material name.
  5478. * If options is a string, name will be set to that string.
  5479. * @todo Deprecate this
  5480. */
  5481. /** Material id. */
  5482. /**
  5483. * Friction for this material.
  5484. * 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.
  5485. */
  5486. /**
  5487. * Restitution for this material.
  5488. * 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.
  5489. */
  5490. constructor(options) {
  5491. if (options === void 0) {
  5492. options = {};
  5493. }
  5494. let name = ''; // Backwards compatibility fix
  5495. if (typeof options === 'string') {
  5496. //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`)
  5497. name = options;
  5498. options = {};
  5499. }
  5500. this.name = name;
  5501. this.id = Material.idCounter++;
  5502. this.friction = typeof options.friction !== 'undefined' ? options.friction : -1;
  5503. this.restitution = typeof options.restitution !== 'undefined' ? options.restitution : -1;
  5504. }
  5505. }
  5506. Material.idCounter = 0;
  5507. /**
  5508. * A spring, connecting two bodies.
  5509. * @example
  5510. * const spring = new Spring(boxBody, sphereBody, {
  5511. * restLength: 0,
  5512. * stiffness: 50,
  5513. * damping: 1,
  5514. * })
  5515. *
  5516. * // Compute the force after each step
  5517. * world.addEventListener('postStep', (event) => {
  5518. * spring.applyForce()
  5519. * })
  5520. */
  5521. class Spring {
  5522. /**
  5523. * Rest length of the spring. A number > 0.
  5524. * @default 1
  5525. */
  5526. /**
  5527. * Stiffness of the spring. A number >= 0.
  5528. * @default 100
  5529. */
  5530. /**
  5531. * Damping of the spring. A number >= 0.
  5532. * @default 1
  5533. */
  5534. /**
  5535. * First connected body.
  5536. */
  5537. /**
  5538. * Second connected body.
  5539. */
  5540. /**
  5541. * Anchor for bodyA in local bodyA coordinates.
  5542. * Where to hook the spring to body A, in local body coordinates.
  5543. * @default new Vec3()
  5544. */
  5545. /**
  5546. * Anchor for bodyB in local bodyB coordinates.
  5547. * Where to hook the spring to body B, in local body coordinates.
  5548. * @default new Vec3()
  5549. */
  5550. constructor(bodyA, bodyB, options) {
  5551. if (options === void 0) {
  5552. options = {};
  5553. }
  5554. this.restLength = typeof options.restLength === 'number' ? options.restLength : 1;
  5555. this.stiffness = options.stiffness || 100;
  5556. this.damping = options.damping || 1;
  5557. this.bodyA = bodyA;
  5558. this.bodyB = bodyB;
  5559. this.localAnchorA = new Vec3();
  5560. this.localAnchorB = new Vec3();
  5561. if (options.localAnchorA) {
  5562. this.localAnchorA.copy(options.localAnchorA);
  5563. }
  5564. if (options.localAnchorB) {
  5565. this.localAnchorB.copy(options.localAnchorB);
  5566. }
  5567. if (options.worldAnchorA) {
  5568. this.setWorldAnchorA(options.worldAnchorA);
  5569. }
  5570. if (options.worldAnchorB) {
  5571. this.setWorldAnchorB(options.worldAnchorB);
  5572. }
  5573. }
  5574. /**
  5575. * Set the anchor point on body A, using world coordinates.
  5576. */
  5577. setWorldAnchorA(worldAnchorA) {
  5578. this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA);
  5579. }
  5580. /**
  5581. * Set the anchor point on body B, using world coordinates.
  5582. */
  5583. setWorldAnchorB(worldAnchorB) {
  5584. this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB);
  5585. }
  5586. /**
  5587. * Get the anchor point on body A, in world coordinates.
  5588. * @param result The vector to store the result in.
  5589. */
  5590. getWorldAnchorA(result) {
  5591. this.bodyA.pointToWorldFrame(this.localAnchorA, result);
  5592. }
  5593. /**
  5594. * Get the anchor point on body B, in world coordinates.
  5595. * @param result The vector to store the result in.
  5596. */
  5597. getWorldAnchorB(result) {
  5598. this.bodyB.pointToWorldFrame(this.localAnchorB, result);
  5599. }
  5600. /**
  5601. * Apply the spring force to the connected bodies.
  5602. */
  5603. applyForce() {
  5604. const k = this.stiffness;
  5605. const d = this.damping;
  5606. const l = this.restLength;
  5607. const bodyA = this.bodyA;
  5608. const bodyB = this.bodyB;
  5609. const r = applyForce_r;
  5610. const r_unit = applyForce_r_unit;
  5611. const u = applyForce_u;
  5612. const f = applyForce_f;
  5613. const tmp = applyForce_tmp;
  5614. const worldAnchorA = applyForce_worldAnchorA;
  5615. const worldAnchorB = applyForce_worldAnchorB;
  5616. const ri = applyForce_ri;
  5617. const rj = applyForce_rj;
  5618. const ri_x_f = applyForce_ri_x_f;
  5619. const rj_x_f = applyForce_rj_x_f; // Get world anchors
  5620. this.getWorldAnchorA(worldAnchorA);
  5621. this.getWorldAnchorB(worldAnchorB); // Get offset points
  5622. worldAnchorA.vsub(bodyA.position, ri);
  5623. worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points
  5624. worldAnchorB.vsub(worldAnchorA, r);
  5625. const rlen = r.length();
  5626. r_unit.copy(r);
  5627. r_unit.normalize(); // Compute relative velocity of the anchor points, u
  5628. bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity
  5629. bodyB.angularVelocity.cross(rj, tmp);
  5630. u.vadd(tmp, u);
  5631. bodyA.angularVelocity.cross(ri, tmp);
  5632. u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u )
  5633. r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies
  5634. bodyA.force.vsub(f, bodyA.force);
  5635. bodyB.force.vadd(f, bodyB.force); // Angular force
  5636. ri.cross(f, ri_x_f);
  5637. rj.cross(f, rj_x_f);
  5638. bodyA.torque.vsub(ri_x_f, bodyA.torque);
  5639. bodyB.torque.vadd(rj_x_f, bodyB.torque);
  5640. }
  5641. }
  5642. const applyForce_r = new Vec3();
  5643. const applyForce_r_unit = new Vec3();
  5644. const applyForce_u = new Vec3();
  5645. const applyForce_f = new Vec3();
  5646. const applyForce_worldAnchorA = new Vec3();
  5647. const applyForce_worldAnchorB = new Vec3();
  5648. const applyForce_ri = new Vec3();
  5649. const applyForce_rj = new Vec3();
  5650. const applyForce_ri_x_f = new Vec3();
  5651. const applyForce_rj_x_f = new Vec3();
  5652. const applyForce_tmp = new Vec3();
  5653. /**
  5654. * WheelInfo
  5655. */
  5656. class WheelInfo {
  5657. /**
  5658. * Max travel distance of the suspension, in meters.
  5659. * @default 1
  5660. */
  5661. /**
  5662. * Speed to apply to the wheel rotation when the wheel is sliding.
  5663. * @default -0.1
  5664. */
  5665. /**
  5666. * If the customSlidingRotationalSpeed should be used.
  5667. * @default false
  5668. */
  5669. /**
  5670. * sliding
  5671. */
  5672. /**
  5673. * Connection point, defined locally in the chassis body frame.
  5674. */
  5675. /**
  5676. * chassisConnectionPointWorld
  5677. */
  5678. /**
  5679. * directionLocal
  5680. */
  5681. /**
  5682. * directionWorld
  5683. */
  5684. /**
  5685. * axleLocal
  5686. */
  5687. /**
  5688. * axleWorld
  5689. */
  5690. /**
  5691. * suspensionRestLength
  5692. * @default 1
  5693. */
  5694. /**
  5695. * suspensionMaxLength
  5696. * @default 2
  5697. */
  5698. /**
  5699. * radius
  5700. * @default 1
  5701. */
  5702. /**
  5703. * suspensionStiffness
  5704. * @default 100
  5705. */
  5706. /**
  5707. * dampingCompression
  5708. * @default 10
  5709. */
  5710. /**
  5711. * dampingRelaxation
  5712. * @default 10
  5713. */
  5714. /**
  5715. * frictionSlip
  5716. * @default 10.5
  5717. */
  5718. /** forwardAcceleration */
  5719. /** sideAcceleration */
  5720. /**
  5721. * steering
  5722. * @default 0
  5723. */
  5724. /**
  5725. * Rotation value, in radians.
  5726. * @default 0
  5727. */
  5728. /**
  5729. * deltaRotation
  5730. * @default 0
  5731. */
  5732. /**
  5733. * rollInfluence
  5734. * @default 0.01
  5735. */
  5736. /**
  5737. * maxSuspensionForce
  5738. */
  5739. /**
  5740. * engineForce
  5741. */
  5742. /**
  5743. * brake
  5744. */
  5745. /**
  5746. * isFrontWheel
  5747. * @default true
  5748. */
  5749. /**
  5750. * clippedInvContactDotSuspension
  5751. * @default 1
  5752. */
  5753. /**
  5754. * suspensionRelativeVelocity
  5755. * @default 0
  5756. */
  5757. /**
  5758. * suspensionForce
  5759. * @default 0
  5760. */
  5761. /**
  5762. * slipInfo
  5763. */
  5764. /**
  5765. * skidInfo
  5766. * @default 0
  5767. */
  5768. /**
  5769. * suspensionLength
  5770. * @default 0
  5771. */
  5772. /**
  5773. * sideImpulse
  5774. */
  5775. /**
  5776. * forwardImpulse
  5777. */
  5778. /**
  5779. * The result from raycasting.
  5780. */
  5781. /**
  5782. * Wheel world transform.
  5783. */
  5784. /**
  5785. * isInContact
  5786. */
  5787. constructor(options) {
  5788. if (options === void 0) {
  5789. options = {};
  5790. }
  5791. options = Utils.defaults(options, {
  5792. chassisConnectionPointLocal: new Vec3(),
  5793. chassisConnectionPointWorld: new Vec3(),
  5794. directionLocal: new Vec3(),
  5795. directionWorld: new Vec3(),
  5796. axleLocal: new Vec3(),
  5797. axleWorld: new Vec3(),
  5798. suspensionRestLength: 1,
  5799. suspensionMaxLength: 2,
  5800. radius: 1,
  5801. suspensionStiffness: 100,
  5802. dampingCompression: 10,
  5803. dampingRelaxation: 10,
  5804. frictionSlip: 10.5,
  5805. forwardAcceleration: 1,
  5806. sideAcceleration: 1,
  5807. steering: 0,
  5808. rotation: 0,
  5809. deltaRotation: 0,
  5810. rollInfluence: 0.01,
  5811. maxSuspensionForce: Number.MAX_VALUE,
  5812. isFrontWheel: true,
  5813. clippedInvContactDotSuspension: 1,
  5814. suspensionRelativeVelocity: 0,
  5815. suspensionForce: 0,
  5816. slipInfo: 0,
  5817. skidInfo: 0,
  5818. suspensionLength: 0,
  5819. maxSuspensionTravel: 1,
  5820. useCustomSlidingRotationalSpeed: false,
  5821. customSlidingRotationalSpeed: -0.1
  5822. });
  5823. this.maxSuspensionTravel = options.maxSuspensionTravel;
  5824. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  5825. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  5826. this.sliding = false;
  5827. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  5828. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  5829. this.directionLocal = options.directionLocal.clone();
  5830. this.directionWorld = options.directionWorld.clone();
  5831. this.axleLocal = options.axleLocal.clone();
  5832. this.axleWorld = options.axleWorld.clone();
  5833. this.suspensionRestLength = options.suspensionRestLength;
  5834. this.suspensionMaxLength = options.suspensionMaxLength;
  5835. this.radius = options.radius;
  5836. this.suspensionStiffness = options.suspensionStiffness;
  5837. this.dampingCompression = options.dampingCompression;
  5838. this.dampingRelaxation = options.dampingRelaxation;
  5839. this.frictionSlip = options.frictionSlip;
  5840. this.forwardAcceleration = options.forwardAcceleration;
  5841. this.sideAcceleration = options.sideAcceleration;
  5842. this.steering = 0;
  5843. this.rotation = 0;
  5844. this.deltaRotation = 0;
  5845. this.rollInfluence = options.rollInfluence;
  5846. this.maxSuspensionForce = options.maxSuspensionForce;
  5847. this.engineForce = 0;
  5848. this.brake = 0;
  5849. this.isFrontWheel = options.isFrontWheel;
  5850. this.clippedInvContactDotSuspension = 1;
  5851. this.suspensionRelativeVelocity = 0;
  5852. this.suspensionForce = 0;
  5853. this.slipInfo = 0;
  5854. this.skidInfo = 0;
  5855. this.suspensionLength = 0;
  5856. this.sideImpulse = 0;
  5857. this.forwardImpulse = 0;
  5858. this.raycastResult = new RaycastResult();
  5859. this.worldTransform = new Transform();
  5860. this.isInContact = false;
  5861. }
  5862. updateWheel(chassis) {
  5863. const raycastResult = this.raycastResult;
  5864. if (this.isInContact) {
  5865. const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  5866. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  5867. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  5868. const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);
  5869. if (project >= -0.1) {
  5870. this.suspensionRelativeVelocity = 0.0;
  5871. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  5872. } else {
  5873. const inv = -1 / project;
  5874. this.suspensionRelativeVelocity = projVel * inv;
  5875. this.clippedInvContactDotSuspension = inv;
  5876. }
  5877. } else {
  5878. // Not in contact : position wheel in a nice (rest length) position
  5879. raycastResult.suspensionLength = this.suspensionRestLength;
  5880. this.suspensionRelativeVelocity = 0.0;
  5881. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  5882. this.clippedInvContactDotSuspension = 1.0;
  5883. }
  5884. }
  5885. }
  5886. const chassis_velocity_at_contactPoint = new Vec3();
  5887. const relpos = new Vec3();
  5888. /**
  5889. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  5890. */
  5891. class RaycastVehicle {
  5892. /** The car chassis body. */
  5893. /** The wheels. */
  5894. /** Will be set to true if the car is sliding. */
  5895. /** Index of the right axis. x=0, y=1, z=2 */
  5896. /** Index of the forward axis. x=0, y=1, z=2 */
  5897. /** Index of the up axis. x=0, y=1, z=2 */
  5898. /** The constraints. */
  5899. /** Optional pre-step callback. */
  5900. /** Number of wheels on the ground. */
  5901. constructor(options) {
  5902. this.chassisBody = options.chassisBody;
  5903. this.wheelInfos = [];
  5904. this.sliding = false;
  5905. this.world = null;
  5906. this.indexRightAxis = typeof options.indexRightAxis !== 'undefined' ? options.indexRightAxis : 2;
  5907. this.indexForwardAxis = typeof options.indexForwardAxis !== 'undefined' ? options.indexForwardAxis : 0;
  5908. this.indexUpAxis = typeof options.indexUpAxis !== 'undefined' ? options.indexUpAxis : 1;
  5909. this.constraints = [];
  5910. this.preStepCallback = () => {};
  5911. this.currentVehicleSpeedKmHour = 0;
  5912. this.numWheelsOnGround = 0;
  5913. }
  5914. /**
  5915. * Add a wheel. For information about the options, see `WheelInfo`.
  5916. */
  5917. addWheel(options) {
  5918. if (options === void 0) {
  5919. options = {};
  5920. }
  5921. const info = new WheelInfo(options);
  5922. const index = this.wheelInfos.length;
  5923. this.wheelInfos.push(info);
  5924. return index;
  5925. }
  5926. /**
  5927. * Set the steering value of a wheel.
  5928. */
  5929. setSteeringValue(value, wheelIndex) {
  5930. const wheel = this.wheelInfos[wheelIndex];
  5931. wheel.steering = value;
  5932. }
  5933. /**
  5934. * Set the wheel force to apply on one of the wheels each time step
  5935. */
  5936. applyEngineForce(value, wheelIndex) {
  5937. this.wheelInfos[wheelIndex].engineForce = value;
  5938. }
  5939. /**
  5940. * Set the braking force of a wheel
  5941. */
  5942. setBrake(brake, wheelIndex) {
  5943. this.wheelInfos[wheelIndex].brake = brake;
  5944. }
  5945. /**
  5946. * Add the vehicle including its constraints to the world.
  5947. */
  5948. addToWorld(world) {
  5949. world.addBody(this.chassisBody);
  5950. const that = this;
  5951. this.preStepCallback = () => {
  5952. that.updateVehicle(world.dt);
  5953. };
  5954. world.addEventListener('preStep', this.preStepCallback);
  5955. this.world = world;
  5956. }
  5957. /**
  5958. * Get one of the wheel axles, world-oriented.
  5959. */
  5960. getVehicleAxisWorld(axisIndex, result) {
  5961. result.set(axisIndex === 0 ? 1 : 0, axisIndex === 1 ? 1 : 0, axisIndex === 2 ? 1 : 0);
  5962. this.chassisBody.vectorToWorldFrame(result, result);
  5963. }
  5964. updateVehicle(timeStep) {
  5965. const wheelInfos = this.wheelInfos;
  5966. const numWheels = wheelInfos.length;
  5967. const chassisBody = this.chassisBody;
  5968. for (let i = 0; i < numWheels; i++) {
  5969. this.updateWheelTransform(i);
  5970. }
  5971. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();
  5972. const forwardWorld = new Vec3();
  5973. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  5974. if (forwardWorld.dot(chassisBody.velocity) < 0) {
  5975. this.currentVehicleSpeedKmHour *= -1;
  5976. } // simulate suspension
  5977. for (let i = 0; i < numWheels; i++) {
  5978. this.castRay(wheelInfos[i]);
  5979. }
  5980. this.updateSuspension(timeStep);
  5981. const impulse = new Vec3();
  5982. const relpos = new Vec3();
  5983. for (let i = 0; i < numWheels; i++) {
  5984. //apply suspension force
  5985. const wheel = wheelInfos[i];
  5986. let suspensionForce = wheel.suspensionForce;
  5987. if (suspensionForce > wheel.maxSuspensionForce) {
  5988. suspensionForce = wheel.maxSuspensionForce;
  5989. }
  5990. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  5991. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  5992. chassisBody.applyImpulse(impulse, relpos);
  5993. }
  5994. this.updateFriction(timeStep);
  5995. const hitNormalWorldScaledWithProj = new Vec3();
  5996. const fwd = new Vec3();
  5997. const vel = new Vec3();
  5998. for (let i = 0; i < numWheels; i++) {
  5999. const wheel = wheelInfos[i]; //const relpos = new Vec3();
  6000. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  6001. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); // Hack to get the rotation in the correct direction
  6002. let m = 1;
  6003. switch (this.indexUpAxis) {
  6004. case 1:
  6005. m = -1;
  6006. break;
  6007. }
  6008. if (wheel.isInContact) {
  6009. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  6010. const proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  6011. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  6012. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  6013. const proj2 = fwd.dot(vel);
  6014. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  6015. }
  6016. if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed) {
  6017. // Apply custom rotation when accelerating and sliding
  6018. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  6019. } // Lock wheels
  6020. if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) {
  6021. wheel.deltaRotation = 0;
  6022. }
  6023. wheel.rotation += wheel.deltaRotation; // Use the old value
  6024. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  6025. }
  6026. }
  6027. updateSuspension(deltaTime) {
  6028. const chassisBody = this.chassisBody;
  6029. const chassisMass = chassisBody.mass;
  6030. const wheelInfos = this.wheelInfos;
  6031. const numWheels = wheelInfos.length;
  6032. for (let w_it = 0; w_it < numWheels; w_it++) {
  6033. const wheel = wheelInfos[w_it];
  6034. if (wheel.isInContact) {
  6035. let force; // Spring
  6036. const susp_length = wheel.suspensionRestLength;
  6037. const current_length = wheel.suspensionLength;
  6038. const length_diff = susp_length - current_length;
  6039. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; // Damper
  6040. const projected_rel_vel = wheel.suspensionRelativeVelocity;
  6041. let susp_damping;
  6042. if (projected_rel_vel < 0) {
  6043. susp_damping = wheel.dampingCompression;
  6044. } else {
  6045. susp_damping = wheel.dampingRelaxation;
  6046. }
  6047. force -= susp_damping * projected_rel_vel;
  6048. wheel.suspensionForce = force * chassisMass;
  6049. if (wheel.suspensionForce < 0) {
  6050. wheel.suspensionForce = 0;
  6051. }
  6052. } else {
  6053. wheel.suspensionForce = 0;
  6054. }
  6055. }
  6056. }
  6057. /**
  6058. * Remove the vehicle including its constraints from the world.
  6059. */
  6060. removeFromWorld(world) {
  6061. this.constraints;
  6062. world.removeBody(this.chassisBody);
  6063. world.removeEventListener('preStep', this.preStepCallback);
  6064. this.world = null;
  6065. }
  6066. castRay(wheel) {
  6067. const rayvector = castRay_rayvector;
  6068. const target = castRay_target;
  6069. this.updateWheelTransformWorld(wheel);
  6070. const chassisBody = this.chassisBody;
  6071. let depth = -1;
  6072. const raylen = wheel.suspensionRestLength + wheel.radius;
  6073. wheel.directionWorld.scale(raylen, rayvector);
  6074. const source = wheel.chassisConnectionPointWorld;
  6075. source.vadd(rayvector, target);
  6076. const raycastResult = wheel.raycastResult;
  6077. raycastResult.reset(); // Turn off ray collision with the chassis temporarily
  6078. const oldState = chassisBody.collisionResponse;
  6079. chassisBody.collisionResponse = false; // Cast ray against world
  6080. this.world.rayTest(source, target, raycastResult);
  6081. chassisBody.collisionResponse = oldState;
  6082. const object = raycastResult.body;
  6083. wheel.raycastResult.groundObject = 0;
  6084. if (object) {
  6085. depth = raycastResult.distance;
  6086. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  6087. wheel.isInContact = true;
  6088. const hitDistance = raycastResult.distance;
  6089. wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel
  6090. const minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  6091. const maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  6092. if (wheel.suspensionLength < minSuspensionLength) {
  6093. wheel.suspensionLength = minSuspensionLength;
  6094. }
  6095. if (wheel.suspensionLength > maxSuspensionLength) {
  6096. wheel.suspensionLength = maxSuspensionLength;
  6097. wheel.raycastResult.reset();
  6098. }
  6099. const denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  6100. const chassis_velocity_at_contactPoint = new Vec3();
  6101. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  6102. const projVel = wheel.raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);
  6103. if (denominator >= -0.1) {
  6104. wheel.suspensionRelativeVelocity = 0;
  6105. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  6106. } else {
  6107. const inv = -1 / denominator;
  6108. wheel.suspensionRelativeVelocity = projVel * inv;
  6109. wheel.clippedInvContactDotSuspension = inv;
  6110. }
  6111. } else {
  6112. //put wheel info as in rest position
  6113. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  6114. wheel.suspensionRelativeVelocity = 0.0;
  6115. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  6116. wheel.clippedInvContactDotSuspension = 1.0;
  6117. }
  6118. return depth;
  6119. }
  6120. updateWheelTransformWorld(wheel) {
  6121. wheel.isInContact = false;
  6122. const chassisBody = this.chassisBody;
  6123. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  6124. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  6125. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  6126. }
  6127. /**
  6128. * Update one of the wheel transform.
  6129. * 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.
  6130. * @param wheelIndex The wheel index to update.
  6131. */
  6132. updateWheelTransform(wheelIndex) {
  6133. const up = tmpVec4;
  6134. const right = tmpVec5;
  6135. const fwd = tmpVec6;
  6136. const wheel = this.wheelInfos[wheelIndex];
  6137. this.updateWheelTransformWorld(wheel);
  6138. wheel.directionLocal.scale(-1, up);
  6139. right.copy(wheel.axleLocal);
  6140. up.cross(right, fwd);
  6141. fwd.normalize();
  6142. right.normalize(); // Rotate around steering over the wheelAxle
  6143. const steering = wheel.steering;
  6144. const steeringOrn = new Quaternion();
  6145. steeringOrn.setFromAxisAngle(up, steering);
  6146. const rotatingOrn = new Quaternion();
  6147. rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel
  6148. const q = wheel.worldTransform.quaternion;
  6149. this.chassisBody.quaternion.mult(steeringOrn, q);
  6150. q.mult(rotatingOrn, q);
  6151. q.normalize(); // world position of the wheel
  6152. const p = wheel.worldTransform.position;
  6153. p.copy(wheel.directionWorld);
  6154. p.scale(wheel.suspensionLength, p);
  6155. p.vadd(wheel.chassisConnectionPointWorld, p);
  6156. }
  6157. /**
  6158. * Get the world transform of one of the wheels
  6159. */
  6160. getWheelTransformWorld(wheelIndex) {
  6161. return this.wheelInfos[wheelIndex].worldTransform;
  6162. }
  6163. updateFriction(timeStep) {
  6164. const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards
  6165. const wheelInfos = this.wheelInfos;
  6166. const numWheels = wheelInfos.length;
  6167. const chassisBody = this.chassisBody;
  6168. const forwardWS = updateFriction_forwardWS;
  6169. const axle = updateFriction_axle;
  6170. this.numWheelsOnGround = 0;
  6171. for (let i = 0; i < numWheels; i++) {
  6172. const wheel = wheelInfos[i];
  6173. const groundObject = wheel.raycastResult.body;
  6174. if (groundObject) {
  6175. this.numWheelsOnGround++;
  6176. }
  6177. wheel.sideImpulse = 0;
  6178. wheel.forwardImpulse = 0;
  6179. if (!forwardWS[i]) {
  6180. forwardWS[i] = new Vec3();
  6181. }
  6182. if (!axle[i]) {
  6183. axle[i] = new Vec3();
  6184. }
  6185. }
  6186. for (let i = 0; i < numWheels; i++) {
  6187. const wheel = wheelInfos[i];
  6188. const groundObject = wheel.raycastResult.body;
  6189. if (groundObject) {
  6190. const axlei = axle[i];
  6191. const wheelTrans = this.getWheelTransformWorld(i); // Get world axle
  6192. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  6193. const surfNormalWS = wheel.raycastResult.hitNormalWorld;
  6194. const proj = axlei.dot(surfNormalWS);
  6195. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  6196. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  6197. axlei.normalize();
  6198. surfNormalWS.cross(axlei, forwardWS[i]);
  6199. forwardWS[i].normalize();
  6200. wheel.sideImpulse = resolveSingleBilateral(chassisBody, wheel.raycastResult.hitPointWorld, groundObject, wheel.raycastResult.hitPointWorld, axlei);
  6201. wheel.sideImpulse *= sideFrictionStiffness2;
  6202. }
  6203. }
  6204. const sideFactor = 1;
  6205. const fwdFactor = 0.5;
  6206. this.sliding = false;
  6207. for (let i = 0; i < numWheels; i++) {
  6208. const wheel = wheelInfos[i];
  6209. const groundObject = wheel.raycastResult.body;
  6210. let rollingFriction = 0;
  6211. wheel.slipInfo = 1;
  6212. if (groundObject) {
  6213. const defaultRollingFrictionImpulse = 0;
  6214. const maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  6215. // rollingFriction = calcRollingFriction(contactPt);
  6216. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  6217. rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0;
  6218. const factor = maxImpulse / rollingFriction;
  6219. wheel.slipInfo *= factor;
  6220. } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  6221. wheel.forwardImpulse = 0;
  6222. wheel.skidInfo = 1;
  6223. if (groundObject) {
  6224. wheel.skidInfo = 1;
  6225. const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  6226. const maximpSide = maximp;
  6227. const maximpSquared = maximp * maximpSide;
  6228. wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep;
  6229. const x = wheel.forwardImpulse * fwdFactor / wheel.forwardAcceleration;
  6230. const y = wheel.sideImpulse * sideFactor / wheel.sideAcceleration;
  6231. const impulseSquared = x * x + y * y;
  6232. wheel.sliding = false;
  6233. if (impulseSquared > maximpSquared) {
  6234. this.sliding = true;
  6235. wheel.sliding = true;
  6236. const factor = maximp / Math.sqrt(impulseSquared);
  6237. wheel.skidInfo *= factor;
  6238. }
  6239. }
  6240. }
  6241. if (this.sliding) {
  6242. for (let i = 0; i < numWheels; i++) {
  6243. const wheel = wheelInfos[i];
  6244. if (wheel.sideImpulse !== 0) {
  6245. if (wheel.skidInfo < 1) {
  6246. wheel.forwardImpulse *= wheel.skidInfo;
  6247. wheel.sideImpulse *= wheel.skidInfo;
  6248. }
  6249. }
  6250. }
  6251. } // apply the impulses
  6252. for (let i = 0; i < numWheels; i++) {
  6253. const wheel = wheelInfos[i];
  6254. const rel_pos = new Vec3();
  6255. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position
  6256. //rel_pos.copy(wheel.raycastResult.hitPointWorld);
  6257. if (wheel.forwardImpulse !== 0) {
  6258. const impulse = new Vec3();
  6259. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  6260. chassisBody.applyImpulse(impulse, rel_pos);
  6261. }
  6262. if (wheel.sideImpulse !== 0) {
  6263. const groundObject = wheel.raycastResult.body;
  6264. const rel_pos2 = new Vec3();
  6265. wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  6266. const sideImp = new Vec3();
  6267. axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence.
  6268. // 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).
  6269. chassisBody.vectorToLocalFrame(rel_pos, rel_pos);
  6270. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  6271. chassisBody.vectorToWorldFrame(rel_pos, rel_pos);
  6272. chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground
  6273. sideImp.scale(-1, sideImp);
  6274. groundObject.applyImpulse(sideImp, rel_pos2);
  6275. }
  6276. }
  6277. }
  6278. }
  6279. new Vec3();
  6280. new Vec3();
  6281. new Vec3();
  6282. const tmpVec4 = new Vec3();
  6283. const tmpVec5 = new Vec3();
  6284. const tmpVec6 = new Vec3();
  6285. new Ray();
  6286. new Vec3();
  6287. const castRay_rayvector = new Vec3();
  6288. const castRay_target = new Vec3();
  6289. const directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)];
  6290. const updateFriction_surfNormalWS_scaled_proj = new Vec3();
  6291. const updateFriction_axle = [];
  6292. const updateFriction_forwardWS = [];
  6293. const sideFrictionStiffness2 = 1;
  6294. const calcRollingFriction_vel1 = new Vec3();
  6295. const calcRollingFriction_vel2 = new Vec3();
  6296. const calcRollingFriction_vel = new Vec3();
  6297. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  6298. let j1 = 0;
  6299. const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3();
  6300. // const rel_pos2 = new Vec3();
  6301. const vel1 = calcRollingFriction_vel1;
  6302. const vel2 = calcRollingFriction_vel2;
  6303. const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1);
  6304. // contactPosWorld.vsub(body1.position, rel_pos2);
  6305. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  6306. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  6307. vel1.vsub(vel2, vel);
  6308. const vrel = frictionDirectionWorld.dot(vel);
  6309. const denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  6310. const denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  6311. const relaxation = 1;
  6312. const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity
  6313. j1 = -vrel * jacDiagABInv;
  6314. if (maxImpulse < j1) {
  6315. j1 = maxImpulse;
  6316. }
  6317. if (j1 < -maxImpulse) {
  6318. j1 = -maxImpulse;
  6319. }
  6320. return j1;
  6321. }
  6322. const computeImpulseDenominator_r0 = new Vec3();
  6323. const computeImpulseDenominator_c0 = new Vec3();
  6324. const computeImpulseDenominator_vec = new Vec3();
  6325. const computeImpulseDenominator_m = new Vec3();
  6326. function computeImpulseDenominator(body, pos, normal) {
  6327. const r0 = computeImpulseDenominator_r0;
  6328. const c0 = computeImpulseDenominator_c0;
  6329. const vec = computeImpulseDenominator_vec;
  6330. const m = computeImpulseDenominator_m;
  6331. pos.vsub(body.position, r0);
  6332. r0.cross(normal, c0);
  6333. body.invInertiaWorld.vmult(c0, m);
  6334. m.cross(r0, vec);
  6335. return body.invMass + normal.dot(vec);
  6336. }
  6337. const resolveSingleBilateral_vel1 = new Vec3();
  6338. const resolveSingleBilateral_vel2 = new Vec3();
  6339. const resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects
  6340. function resolveSingleBilateral(body1, pos1, body2, pos2, normal) {
  6341. const normalLenSqr = normal.lengthSquared();
  6342. if (normalLenSqr > 1.1) {
  6343. return 0; // no impulse
  6344. } // const rel_pos1 = new Vec3();
  6345. // const rel_pos2 = new Vec3();
  6346. // pos1.vsub(body1.position, rel_pos1);
  6347. // pos2.vsub(body2.position, rel_pos2);
  6348. const vel1 = resolveSingleBilateral_vel1;
  6349. const vel2 = resolveSingleBilateral_vel2;
  6350. const vel = resolveSingleBilateral_vel;
  6351. body1.getVelocityAtWorldPoint(pos1, vel1);
  6352. body2.getVelocityAtWorldPoint(pos2, vel2);
  6353. vel1.vsub(vel2, vel);
  6354. const rel_vel = normal.dot(vel);
  6355. const contactDamping = 0.2;
  6356. const massTerm = 1 / (body1.invMass + body2.invMass);
  6357. const impulse = -contactDamping * rel_vel * massTerm;
  6358. return impulse;
  6359. }
  6360. /**
  6361. * Spherical shape
  6362. * @example
  6363. * const radius = 1
  6364. * const sphereShape = new CANNON.Sphere(radius)
  6365. * const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape })
  6366. * world.addBody(sphereBody)
  6367. */
  6368. class Sphere extends Shape {
  6369. /**
  6370. * The radius of the sphere.
  6371. */
  6372. /**
  6373. *
  6374. * @param radius The radius of the sphere, a non-negative number.
  6375. */
  6376. constructor(radius) {
  6377. super({
  6378. type: Shape.types.SPHERE
  6379. });
  6380. this.radius = radius !== undefined ? radius : 1.0;
  6381. if (this.radius < 0) {
  6382. throw new Error('The sphere radius cannot be negative.');
  6383. }
  6384. this.updateBoundingSphereRadius();
  6385. }
  6386. /** calculateLocalInertia */
  6387. calculateLocalInertia(mass, target) {
  6388. if (target === void 0) {
  6389. target = new Vec3();
  6390. }
  6391. const I = 2.0 * mass * this.radius * this.radius / 5.0;
  6392. target.x = I;
  6393. target.y = I;
  6394. target.z = I;
  6395. return target;
  6396. }
  6397. /** volume */
  6398. volume() {
  6399. return 4.0 * Math.PI * Math.pow(this.radius, 3) / 3.0;
  6400. }
  6401. updateBoundingSphereRadius() {
  6402. this.boundingSphereRadius = this.radius;
  6403. }
  6404. calculateWorldAABB(pos, quat, min, max) {
  6405. const r = this.radius;
  6406. const axes = ['x', 'y', 'z'];
  6407. for (let i = 0; i < axes.length; i++) {
  6408. const ax = axes[i];
  6409. min[ax] = pos[ax] - r;
  6410. max[ax] = pos[ax] + r;
  6411. }
  6412. }
  6413. }
  6414. /**
  6415. * Simple vehicle helper class with spherical rigid body wheels.
  6416. */
  6417. class RigidVehicle {
  6418. /**
  6419. * The bodies of the wheels.
  6420. */
  6421. /**
  6422. * The chassis body.
  6423. */
  6424. /**
  6425. * The constraints.
  6426. */
  6427. /**
  6428. * The wheel axes.
  6429. */
  6430. /**
  6431. * The wheel forces.
  6432. */
  6433. constructor(options) {
  6434. if (options === void 0) {
  6435. options = {};
  6436. }
  6437. this.wheelBodies = [];
  6438. this.coordinateSystem = typeof options.coordinateSystem !== 'undefined' ? options.coordinateSystem.clone() : new Vec3(1, 2, 3);
  6439. if (options.chassisBody) {
  6440. this.chassisBody = options.chassisBody;
  6441. } else {
  6442. // No chassis body given. Create it!
  6443. this.chassisBody = new Body({
  6444. mass: 1,
  6445. shape: new Box(new Vec3(5, 0.5, 2))
  6446. });
  6447. }
  6448. this.constraints = [];
  6449. this.wheelAxes = [];
  6450. this.wheelForces = [];
  6451. }
  6452. /**
  6453. * Add a wheel
  6454. */
  6455. addWheel(options) {
  6456. if (options === void 0) {
  6457. options = {};
  6458. }
  6459. let wheelBody;
  6460. if (options.body) {
  6461. wheelBody = options.body;
  6462. } else {
  6463. // No wheel body given. Create it!
  6464. wheelBody = new Body({
  6465. mass: 1,
  6466. shape: new Sphere(1.2)
  6467. });
  6468. }
  6469. this.wheelBodies.push(wheelBody);
  6470. this.wheelForces.push(0); // Position constrain wheels
  6471. const position = typeof options.position !== 'undefined' ? options.position.clone() : new Vec3(); // Set position locally to the chassis
  6472. const worldPosition = new Vec3();
  6473. this.chassisBody.pointToWorldFrame(position, worldPosition);
  6474. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel
  6475. const axis = typeof options.axis !== 'undefined' ? options.axis.clone() : new Vec3(0, 0, 1);
  6476. this.wheelAxes.push(axis);
  6477. const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  6478. pivotA: position,
  6479. axisA: axis,
  6480. pivotB: Vec3.ZERO,
  6481. axisB: axis,
  6482. collideConnected: false
  6483. });
  6484. this.constraints.push(hingeConstraint);
  6485. return this.wheelBodies.length - 1;
  6486. }
  6487. /**
  6488. * Set the steering value of a wheel.
  6489. * @todo check coordinateSystem
  6490. */
  6491. setSteeringValue(value, wheelIndex) {
  6492. // Set angle of the hinge axis
  6493. const axis = this.wheelAxes[wheelIndex];
  6494. const c = Math.cos(value);
  6495. const s = Math.sin(value);
  6496. const x = axis.x;
  6497. const z = axis.z;
  6498. this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z);
  6499. }
  6500. /**
  6501. * Set the target rotational speed of the hinge constraint.
  6502. */
  6503. setMotorSpeed(value, wheelIndex) {
  6504. const hingeConstraint = this.constraints[wheelIndex];
  6505. hingeConstraint.enableMotor();
  6506. hingeConstraint.motorTargetVelocity = value;
  6507. }
  6508. /**
  6509. * Set the target rotational speed of the hinge constraint.
  6510. */
  6511. disableMotor(wheelIndex) {
  6512. const hingeConstraint = this.constraints[wheelIndex];
  6513. hingeConstraint.disableMotor();
  6514. }
  6515. /**
  6516. * Set the wheel force to apply on one of the wheels each time step
  6517. */
  6518. setWheelForce(value, wheelIndex) {
  6519. this.wheelForces[wheelIndex] = value;
  6520. }
  6521. /**
  6522. * Apply a torque on one of the wheels.
  6523. */
  6524. applyWheelForce(value, wheelIndex) {
  6525. const axis = this.wheelAxes[wheelIndex];
  6526. const wheelBody = this.wheelBodies[wheelIndex];
  6527. const bodyTorque = wheelBody.torque;
  6528. axis.scale(value, torque);
  6529. wheelBody.vectorToWorldFrame(torque, torque);
  6530. bodyTorque.vadd(torque, bodyTorque);
  6531. }
  6532. /**
  6533. * Add the vehicle including its constraints to the world.
  6534. */
  6535. addToWorld(world) {
  6536. const constraints = this.constraints;
  6537. const bodies = this.wheelBodies.concat([this.chassisBody]);
  6538. for (let i = 0; i < bodies.length; i++) {
  6539. world.addBody(bodies[i]);
  6540. }
  6541. for (let i = 0; i < constraints.length; i++) {
  6542. world.addConstraint(constraints[i]);
  6543. }
  6544. world.addEventListener('preStep', this._update.bind(this));
  6545. }
  6546. _update() {
  6547. const wheelForces = this.wheelForces;
  6548. for (let i = 0; i < wheelForces.length; i++) {
  6549. this.applyWheelForce(wheelForces[i], i);
  6550. }
  6551. }
  6552. /**
  6553. * Remove the vehicle including its constraints from the world.
  6554. */
  6555. removeFromWorld(world) {
  6556. const constraints = this.constraints;
  6557. const bodies = this.wheelBodies.concat([this.chassisBody]);
  6558. for (let i = 0; i < bodies.length; i++) {
  6559. world.removeBody(bodies[i]);
  6560. }
  6561. for (let i = 0; i < constraints.length; i++) {
  6562. world.removeConstraint(constraints[i]);
  6563. }
  6564. }
  6565. /**
  6566. * Get current rotational velocity of a wheel
  6567. */
  6568. getWheelSpeed(wheelIndex) {
  6569. const axis = this.wheelAxes[wheelIndex];
  6570. const wheelBody = this.wheelBodies[wheelIndex];
  6571. const w = wheelBody.angularVelocity;
  6572. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  6573. return w.dot(worldAxis);
  6574. }
  6575. }
  6576. const torque = new Vec3();
  6577. const worldAxis = new Vec3();
  6578. /**
  6579. * Smoothed-particle hydrodynamics system
  6580. * @todo Make parameters customizable in the constructor
  6581. */
  6582. class SPHSystem {
  6583. /**
  6584. * The particles array.
  6585. */
  6586. /**
  6587. * Density of the system (kg/m3).
  6588. * @default 1
  6589. */
  6590. /**
  6591. * Distance below which two particles are considered to be neighbors.
  6592. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  6593. * @default 1
  6594. */
  6595. /**
  6596. * @default 1
  6597. */
  6598. /**
  6599. * Viscosity of the system.
  6600. * @default 0.01
  6601. */
  6602. /**
  6603. * @default 0.000001
  6604. */
  6605. constructor() {
  6606. this.particles = [];
  6607. this.density = 1;
  6608. this.smoothingRadius = 1;
  6609. this.speedOfSound = 1;
  6610. this.viscosity = 0.01;
  6611. this.eps = 0.000001; // Stuff Computed per particle
  6612. this.pressures = [];
  6613. this.densities = [];
  6614. this.neighbors = [];
  6615. }
  6616. /**
  6617. * Add a particle to the system.
  6618. */
  6619. add(particle) {
  6620. this.particles.push(particle);
  6621. if (this.neighbors.length < this.particles.length) {
  6622. this.neighbors.push([]);
  6623. }
  6624. }
  6625. /**
  6626. * Remove a particle from the system.
  6627. */
  6628. remove(particle) {
  6629. const idx = this.particles.indexOf(particle);
  6630. if (idx !== -1) {
  6631. this.particles.splice(idx, 1);
  6632. if (this.neighbors.length > this.particles.length) {
  6633. this.neighbors.pop();
  6634. }
  6635. }
  6636. }
  6637. /**
  6638. * Get neighbors within smoothing volume, save in the array neighbors
  6639. */
  6640. getNeighbors(particle, neighbors) {
  6641. const N = this.particles.length;
  6642. const id = particle.id;
  6643. const R2 = this.smoothingRadius * this.smoothingRadius;
  6644. const dist = SPHSystem_getNeighbors_dist;
  6645. for (let i = 0; i !== N; i++) {
  6646. const p = this.particles[i];
  6647. p.position.vsub(particle.position, dist);
  6648. if (id !== p.id && dist.lengthSquared() < R2) {
  6649. neighbors.push(p);
  6650. }
  6651. }
  6652. }
  6653. update() {
  6654. const N = this.particles.length;
  6655. const dist = SPHSystem_update_dist;
  6656. const cs = this.speedOfSound;
  6657. const eps = this.eps;
  6658. for (let i = 0; i !== N; i++) {
  6659. const p = this.particles[i]; // Current particle
  6660. const neighbors = this.neighbors[i]; // Get neighbors
  6661. neighbors.length = 0;
  6662. this.getNeighbors(p, neighbors);
  6663. neighbors.push(this.particles[i]); // Add current too
  6664. const numNeighbors = neighbors.length; // Accumulate density for the particle
  6665. let sum = 0.0;
  6666. for (let j = 0; j !== numNeighbors; j++) {
  6667. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  6668. p.position.vsub(neighbors[j].position, dist);
  6669. const len = dist.length();
  6670. const weight = this.w(len);
  6671. sum += neighbors[j].mass * weight;
  6672. } // Save
  6673. this.densities[i] = sum;
  6674. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  6675. } // Add forces
  6676. // Sum to these accelerations
  6677. const a_pressure = SPHSystem_update_a_pressure;
  6678. const a_visc = SPHSystem_update_a_visc;
  6679. const gradW = SPHSystem_update_gradW;
  6680. const r_vec = SPHSystem_update_r_vec;
  6681. const u = SPHSystem_update_u;
  6682. for (let i = 0; i !== N; i++) {
  6683. const particle = this.particles[i];
  6684. a_pressure.set(0, 0, 0);
  6685. a_visc.set(0, 0, 0); // Init vars
  6686. let Pij;
  6687. let nabla;
  6688. const neighbors = this.neighbors[i];
  6689. const numNeighbors = neighbors.length; //printf("Neighbors: ");
  6690. for (let j = 0; j !== numNeighbors; j++) {
  6691. const neighbor = neighbors[j]; //printf("%d ",nj);
  6692. // Get r once for all..
  6693. particle.position.vsub(neighbor.position, r_vec);
  6694. const r = r_vec.length(); // Pressure contribution
  6695. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + this.pressures[j] / (this.densities[j] * this.densities[j] + eps));
  6696. this.gradw(r_vec, gradW); // Add to pressure acceleration
  6697. gradW.scale(Pij, gradW);
  6698. a_pressure.vadd(gradW, a_pressure); // Viscosity contribution
  6699. neighbor.velocity.vsub(particle.velocity, u);
  6700. u.scale(1.0 / (0.0001 + this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass, u);
  6701. nabla = this.nablaw(r);
  6702. u.scale(nabla, u); // Add to viscosity acceleration
  6703. a_visc.vadd(u, a_visc);
  6704. } // Calculate force
  6705. a_visc.scale(particle.mass, a_visc);
  6706. a_pressure.scale(particle.mass, a_pressure); // Add force to particles
  6707. particle.force.vadd(a_visc, particle.force);
  6708. particle.force.vadd(a_pressure, particle.force);
  6709. }
  6710. } // Calculate the weight using the W(r) weightfunction
  6711. w(r) {
  6712. // 315
  6713. const h = this.smoothingRadius;
  6714. return 315.0 / (64.0 * Math.PI * h ** 9) * (h * h - r * r) ** 3;
  6715. } // calculate gradient of the weight function
  6716. gradw(rVec, resultVec) {
  6717. const r = rVec.length();
  6718. const h = this.smoothingRadius;
  6719. rVec.scale(945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) ** 2, resultVec);
  6720. } // Calculate nabla(W)
  6721. nablaw(r) {
  6722. const h = this.smoothingRadius;
  6723. const nabla = 945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) * (7 * r * r - 3 * h * h);
  6724. return nabla;
  6725. }
  6726. }
  6727. const SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation
  6728. const SPHSystem_update_dist = new Vec3(); // Relative velocity
  6729. const SPHSystem_update_a_pressure = new Vec3();
  6730. const SPHSystem_update_a_visc = new Vec3();
  6731. const SPHSystem_update_gradW = new Vec3();
  6732. const SPHSystem_update_r_vec = new Vec3();
  6733. const SPHSystem_update_u = new Vec3();
  6734. /**
  6735. * Cylinder class.
  6736. * @example
  6737. * const radiusTop = 0.5
  6738. * const radiusBottom = 0.5
  6739. * const height = 2
  6740. * const numSegments = 12
  6741. * const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments)
  6742. * const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape })
  6743. * world.addBody(cylinderBody)
  6744. */
  6745. class Cylinder extends ConvexPolyhedron {
  6746. /** The radius of the top of the Cylinder. */
  6747. /** The radius of the bottom of the Cylinder. */
  6748. /** The height of the Cylinder. */
  6749. /** The number of segments to build the cylinder out of. */
  6750. /**
  6751. * @param radiusTop The radius of the top of the Cylinder.
  6752. * @param radiusBottom The radius of the bottom of the Cylinder.
  6753. * @param height The height of the Cylinder.
  6754. * @param numSegments The number of segments to build the cylinder out of.
  6755. */
  6756. constructor(radiusTop, radiusBottom, height, numSegments) {
  6757. if (radiusTop === void 0) {
  6758. radiusTop = 1;
  6759. }
  6760. if (radiusBottom === void 0) {
  6761. radiusBottom = 1;
  6762. }
  6763. if (height === void 0) {
  6764. height = 1;
  6765. }
  6766. if (numSegments === void 0) {
  6767. numSegments = 8;
  6768. }
  6769. if (radiusTop < 0) {
  6770. throw new Error('The cylinder radiusTop cannot be negative.');
  6771. }
  6772. if (radiusBottom < 0) {
  6773. throw new Error('The cylinder radiusBottom cannot be negative.');
  6774. }
  6775. const N = numSegments;
  6776. const vertices = [];
  6777. const axes = [];
  6778. const faces = [];
  6779. const bottomface = [];
  6780. const topface = [];
  6781. const cos = Math.cos;
  6782. const sin = Math.sin; // First bottom point
  6783. vertices.push(new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)));
  6784. bottomface.push(0); // First top point
  6785. vertices.push(new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)));
  6786. topface.push(1);
  6787. for (let i = 0; i < N; i++) {
  6788. const theta = 2 * Math.PI / N * (i + 1);
  6789. const thetaN = 2 * Math.PI / N * (i + 0.5);
  6790. if (i < N - 1) {
  6791. // Bottom
  6792. vertices.push(new Vec3(-radiusBottom * sin(theta), -height * 0.5, radiusBottom * cos(theta)));
  6793. bottomface.push(2 * i + 2); // Top
  6794. vertices.push(new Vec3(-radiusTop * sin(theta), height * 0.5, radiusTop * cos(theta)));
  6795. topface.push(2 * i + 3); // Face
  6796. faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]);
  6797. } else {
  6798. faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect
  6799. } // Axis: we can cut off half of them if we have even number of segments
  6800. if (N % 2 === 1 || i < N / 2) {
  6801. axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN)));
  6802. }
  6803. }
  6804. faces.push(bottomface);
  6805. axes.push(new Vec3(0, 1, 0)); // Reorder top face
  6806. const temp = [];
  6807. for (let i = 0; i < topface.length; i++) {
  6808. temp.push(topface[topface.length - i - 1]);
  6809. }
  6810. faces.push(temp);
  6811. super({
  6812. vertices,
  6813. faces,
  6814. axes
  6815. });
  6816. this.type = Shape.types.CYLINDER;
  6817. this.radiusTop = radiusTop;
  6818. this.radiusBottom = radiusBottom;
  6819. this.height = height;
  6820. this.numSegments = numSegments;
  6821. }
  6822. }
  6823. /**
  6824. * Particle shape.
  6825. * @example
  6826. * const particleShape = new CANNON.Particle()
  6827. * const particleBody = new CANNON.Body({ mass: 1, shape: particleShape })
  6828. * world.addBody(particleBody)
  6829. */
  6830. class Particle extends Shape {
  6831. constructor() {
  6832. super({
  6833. type: Shape.types.PARTICLE
  6834. });
  6835. }
  6836. /**
  6837. * calculateLocalInertia
  6838. */
  6839. calculateLocalInertia(mass, target) {
  6840. if (target === void 0) {
  6841. target = new Vec3();
  6842. }
  6843. target.set(0, 0, 0);
  6844. return target;
  6845. }
  6846. volume() {
  6847. return 0;
  6848. }
  6849. updateBoundingSphereRadius() {
  6850. this.boundingSphereRadius = 0;
  6851. }
  6852. calculateWorldAABB(pos, quat, min, max) {
  6853. // Get each axis max
  6854. min.copy(pos);
  6855. max.copy(pos);
  6856. }
  6857. }
  6858. /**
  6859. * 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.
  6860. * @example
  6861. * const planeShape = new CANNON.Plane()
  6862. * const planeBody = new CANNON.Body({ mass: 0, shape: planeShape })
  6863. * planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up
  6864. * world.addBody(planeBody)
  6865. */
  6866. class Plane extends Shape {
  6867. /** worldNormal */
  6868. /** worldNormalNeedsUpdate */
  6869. constructor() {
  6870. super({
  6871. type: Shape.types.PLANE
  6872. }); // World oriented normal
  6873. this.worldNormal = new Vec3();
  6874. this.worldNormalNeedsUpdate = true;
  6875. this.boundingSphereRadius = Number.MAX_VALUE;
  6876. }
  6877. /** computeWorldNormal */
  6878. computeWorldNormal(quat) {
  6879. const n = this.worldNormal;
  6880. n.set(0, 0, 1);
  6881. quat.vmult(n, n);
  6882. this.worldNormalNeedsUpdate = false;
  6883. }
  6884. calculateLocalInertia(mass, target) {
  6885. if (target === void 0) {
  6886. target = new Vec3();
  6887. }
  6888. return target;
  6889. }
  6890. volume() {
  6891. return (// The plane is infinite...
  6892. Number.MAX_VALUE
  6893. );
  6894. }
  6895. calculateWorldAABB(pos, quat, min, max) {
  6896. // The plane AABB is infinite, except if the normal is pointing along any axis
  6897. tempNormal.set(0, 0, 1); // Default plane normal is z
  6898. quat.vmult(tempNormal, tempNormal);
  6899. const maxVal = Number.MAX_VALUE;
  6900. min.set(-maxVal, -maxVal, -maxVal);
  6901. max.set(maxVal, maxVal, maxVal);
  6902. if (tempNormal.x === 1) {
  6903. max.x = pos.x;
  6904. } else if (tempNormal.x === -1) {
  6905. min.x = pos.x;
  6906. }
  6907. if (tempNormal.y === 1) {
  6908. max.y = pos.y;
  6909. } else if (tempNormal.y === -1) {
  6910. min.y = pos.y;
  6911. }
  6912. if (tempNormal.z === 1) {
  6913. max.z = pos.z;
  6914. } else if (tempNormal.z === -1) {
  6915. min.z = pos.z;
  6916. }
  6917. }
  6918. updateBoundingSphereRadius() {
  6919. this.boundingSphereRadius = Number.MAX_VALUE;
  6920. }
  6921. }
  6922. const tempNormal = new Vec3();
  6923. /**
  6924. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  6925. * @todo Should be possible to use along all axes, not just y
  6926. * @todo should be possible to scale along all axes
  6927. * @todo Refactor elementSize to elementSizeX and elementSizeY
  6928. *
  6929. * @example
  6930. * // Generate some height data (y-values).
  6931. * const data = []
  6932. * for (let i = 0; i < 1000; i++) {
  6933. * const y = 0.5 * Math.cos(0.2 * i)
  6934. * data.push(y)
  6935. * }
  6936. *
  6937. * // Create the heightfield shape
  6938. * const heightfieldShape = new CANNON.Heightfield(data, {
  6939. * elementSize: 1 // Distance between the data points in X and Y directions
  6940. * })
  6941. * const heightfieldBody = new CANNON.Body({ shape: heightfieldShape })
  6942. * world.addBody(heightfieldBody)
  6943. */
  6944. class Heightfield extends Shape {
  6945. /**
  6946. * An array of numbers, or height values, that are spread out along the x axis.
  6947. */
  6948. /**
  6949. * Max value of the data points in the data array.
  6950. */
  6951. /**
  6952. * Minimum value of the data points in the data array.
  6953. */
  6954. /**
  6955. * World spacing between the data points in X and Y direction.
  6956. * @todo elementSizeX and Y
  6957. * @default 1
  6958. */
  6959. /**
  6960. * @default true
  6961. */
  6962. /**
  6963. * @param data An array of numbers, or height values, that are spread out along the x axis.
  6964. */
  6965. constructor(data, options) {
  6966. if (options === void 0) {
  6967. options = {};
  6968. }
  6969. options = Utils.defaults(options, {
  6970. maxValue: null,
  6971. minValue: null,
  6972. elementSize: 1
  6973. });
  6974. super({
  6975. type: Shape.types.HEIGHTFIELD
  6976. });
  6977. this.data = data;
  6978. this.maxValue = options.maxValue;
  6979. this.minValue = options.minValue;
  6980. this.elementSize = options.elementSize;
  6981. if (options.minValue === null) {
  6982. this.updateMinValue();
  6983. }
  6984. if (options.maxValue === null) {
  6985. this.updateMaxValue();
  6986. }
  6987. this.cacheEnabled = true;
  6988. this.pillarConvex = new ConvexPolyhedron();
  6989. this.pillarOffset = new Vec3();
  6990. this.updateBoundingSphereRadius(); // "i_j_isUpper" => { convex: ..., offset: ... }
  6991. // for example:
  6992. // _cachedPillars["0_2_1"]
  6993. this._cachedPillars = {};
  6994. }
  6995. /**
  6996. * Call whenever you change the data array.
  6997. */
  6998. update() {
  6999. this._cachedPillars = {};
  7000. }
  7001. /**
  7002. * Update the `minValue` property
  7003. */
  7004. updateMinValue() {
  7005. const data = this.data;
  7006. let minValue = data[0][0];
  7007. for (let i = 0; i !== data.length; i++) {
  7008. for (let j = 0; j !== data[i].length; j++) {
  7009. const v = data[i][j];
  7010. if (v < minValue) {
  7011. minValue = v;
  7012. }
  7013. }
  7014. }
  7015. this.minValue = minValue;
  7016. }
  7017. /**
  7018. * Update the `maxValue` property
  7019. */
  7020. updateMaxValue() {
  7021. const data = this.data;
  7022. let maxValue = data[0][0];
  7023. for (let i = 0; i !== data.length; i++) {
  7024. for (let j = 0; j !== data[i].length; j++) {
  7025. const v = data[i][j];
  7026. if (v > maxValue) {
  7027. maxValue = v;
  7028. }
  7029. }
  7030. }
  7031. this.maxValue = maxValue;
  7032. }
  7033. /**
  7034. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  7035. */
  7036. setHeightValueAtIndex(xi, yi, value) {
  7037. const data = this.data;
  7038. data[xi][yi] = value; // Invalidate cache
  7039. this.clearCachedConvexTrianglePillar(xi, yi, false);
  7040. if (xi > 0) {
  7041. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  7042. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  7043. }
  7044. if (yi > 0) {
  7045. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  7046. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  7047. }
  7048. if (yi > 0 && xi > 0) {
  7049. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  7050. }
  7051. }
  7052. /**
  7053. * Get max/min in a rectangle in the matrix data
  7054. * @param result An array to store the results in.
  7055. * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  7056. */
  7057. getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result) {
  7058. if (result === void 0) {
  7059. result = [];
  7060. }
  7061. // Get max and min of the data
  7062. const data = this.data; // Set first value
  7063. let max = this.minValue;
  7064. for (let i = iMinX; i <= iMaxX; i++) {
  7065. for (let j = iMinY; j <= iMaxY; j++) {
  7066. const height = data[i][j];
  7067. if (height > max) {
  7068. max = height;
  7069. }
  7070. }
  7071. }
  7072. result[0] = this.minValue;
  7073. result[1] = max;
  7074. }
  7075. /**
  7076. * 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.
  7077. * @param result Two-element array
  7078. * @param clamp If the position should be clamped to the heightfield edge.
  7079. */
  7080. getIndexOfPosition(x, y, result, clamp) {
  7081. // Get the index of the data points to test against
  7082. const w = this.elementSize;
  7083. const data = this.data;
  7084. let xi = Math.floor(x / w);
  7085. let yi = Math.floor(y / w);
  7086. result[0] = xi;
  7087. result[1] = yi;
  7088. if (clamp) {
  7089. // Clamp index to edges
  7090. if (xi < 0) {
  7091. xi = 0;
  7092. }
  7093. if (yi < 0) {
  7094. yi = 0;
  7095. }
  7096. if (xi >= data.length - 1) {
  7097. xi = data.length - 1;
  7098. }
  7099. if (yi >= data[0].length - 1) {
  7100. yi = data[0].length - 1;
  7101. }
  7102. } // Bail out if we are out of the terrain
  7103. if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) {
  7104. return false;
  7105. }
  7106. return true;
  7107. }
  7108. getTriangleAt(x, y, edgeClamp, a, b, c) {
  7109. const idx = getHeightAt_idx;
  7110. this.getIndexOfPosition(x, y, idx, edgeClamp);
  7111. let xi = idx[0];
  7112. let yi = idx[1];
  7113. const data = this.data;
  7114. if (edgeClamp) {
  7115. xi = Math.min(data.length - 2, Math.max(0, xi));
  7116. yi = Math.min(data[0].length - 2, Math.max(0, yi));
  7117. }
  7118. const elementSize = this.elementSize;
  7119. const lowerDist2 = (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2;
  7120. const upperDist2 = (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2;
  7121. const upper = lowerDist2 > upperDist2;
  7122. this.getTriangle(xi, yi, upper, a, b, c);
  7123. return upper;
  7124. }
  7125. getNormalAt(x, y, edgeClamp, result) {
  7126. const a = getNormalAt_a;
  7127. const b = getNormalAt_b;
  7128. const c = getNormalAt_c;
  7129. const e0 = getNormalAt_e0;
  7130. const e1 = getNormalAt_e1;
  7131. this.getTriangleAt(x, y, edgeClamp, a, b, c);
  7132. b.vsub(a, e0);
  7133. c.vsub(a, e1);
  7134. e0.cross(e1, result);
  7135. result.normalize();
  7136. }
  7137. /**
  7138. * Get an AABB of a square in the heightfield
  7139. * @param xi
  7140. * @param yi
  7141. * @param result
  7142. */
  7143. getAabbAtIndex(xi, yi, _ref) {
  7144. let {
  7145. lowerBound,
  7146. upperBound
  7147. } = _ref;
  7148. const data = this.data;
  7149. const elementSize = this.elementSize;
  7150. lowerBound.set(xi * elementSize, yi * elementSize, data[xi][yi]);
  7151. upperBound.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);
  7152. }
  7153. /**
  7154. * Get the height in the heightfield at a given position
  7155. */
  7156. getHeightAt(x, y, edgeClamp) {
  7157. const data = this.data;
  7158. const a = getHeightAt_a;
  7159. const b = getHeightAt_b;
  7160. const c = getHeightAt_c;
  7161. const idx = getHeightAt_idx;
  7162. this.getIndexOfPosition(x, y, idx, edgeClamp);
  7163. let xi = idx[0];
  7164. let yi = idx[1];
  7165. if (edgeClamp) {
  7166. xi = Math.min(data.length - 2, Math.max(0, xi));
  7167. yi = Math.min(data[0].length - 2, Math.max(0, yi));
  7168. }
  7169. const upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);
  7170. barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);
  7171. const w = getHeightAt_weights;
  7172. if (upper) {
  7173. // Top triangle verts
  7174. return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;
  7175. } else {
  7176. // Top triangle verts
  7177. return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;
  7178. }
  7179. }
  7180. getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) {
  7181. return `${xi}_${yi}_${getUpperTriangle ? 1 : 0}`;
  7182. }
  7183. getCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7184. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  7185. }
  7186. setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, convex, offset) {
  7187. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  7188. convex,
  7189. offset
  7190. };
  7191. }
  7192. clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7193. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  7194. }
  7195. /**
  7196. * Get a triangle from the heightfield
  7197. */
  7198. getTriangle(xi, yi, upper, a, b, c) {
  7199. const data = this.data;
  7200. const elementSize = this.elementSize;
  7201. if (upper) {
  7202. // Top triangle verts
  7203. a.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);
  7204. b.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);
  7205. c.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);
  7206. } else {
  7207. // Top triangle verts
  7208. a.set(xi * elementSize, yi * elementSize, data[xi][yi]);
  7209. b.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);
  7210. c.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);
  7211. }
  7212. }
  7213. /**
  7214. * Get a triangle in the terrain in the form of a triangular convex shape.
  7215. */
  7216. getConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7217. let result = this.pillarConvex;
  7218. let offsetResult = this.pillarOffset;
  7219. if (this.cacheEnabled) {
  7220. const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  7221. if (data) {
  7222. this.pillarConvex = data.convex;
  7223. this.pillarOffset = data.offset;
  7224. return;
  7225. }
  7226. result = new ConvexPolyhedron();
  7227. offsetResult = new Vec3();
  7228. this.pillarConvex = result;
  7229. this.pillarOffset = offsetResult;
  7230. }
  7231. const data = this.data;
  7232. const elementSize = this.elementSize;
  7233. const faces = result.faces; // Reuse verts if possible
  7234. result.vertices.length = 6;
  7235. for (let i = 0; i < 6; i++) {
  7236. if (!result.vertices[i]) {
  7237. result.vertices[i] = new Vec3();
  7238. }
  7239. } // Reuse faces if possible
  7240. faces.length = 5;
  7241. for (let i = 0; i < 5; i++) {
  7242. if (!faces[i]) {
  7243. faces[i] = [];
  7244. }
  7245. }
  7246. const verts = result.vertices;
  7247. 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;
  7248. if (!getUpperTriangle) {
  7249. // Center of the triangle pillar - all polygons are given relative to this one
  7250. offsetResult.set((xi + 0.25) * elementSize, // sort of center of a triangle
  7251. (yi + 0.25) * elementSize, h // vertical center
  7252. ); // Top triangle verts
  7253. verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h);
  7254. verts[1].set(0.75 * elementSize, -0.25 * elementSize, data[xi + 1][yi] - h);
  7255. verts[2].set(-0.25 * elementSize, 0.75 * elementSize, data[xi][yi + 1] - h); // bottom triangle verts
  7256. verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
  7257. verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
  7258. verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle
  7259. faces[0][0] = 0;
  7260. faces[0][1] = 1;
  7261. faces[0][2] = 2; // bottom triangle
  7262. faces[1][0] = 5;
  7263. faces[1][1] = 4;
  7264. faces[1][2] = 3; // -x facing quad
  7265. faces[2][0] = 0;
  7266. faces[2][1] = 2;
  7267. faces[2][2] = 5;
  7268. faces[2][3] = 3; // -y facing quad
  7269. faces[3][0] = 1;
  7270. faces[3][1] = 0;
  7271. faces[3][2] = 3;
  7272. faces[3][3] = 4; // +xy facing quad
  7273. faces[4][0] = 4;
  7274. faces[4][1] = 5;
  7275. faces[4][2] = 2;
  7276. faces[4][3] = 1;
  7277. } else {
  7278. // Center of the triangle pillar - all polygons are given relative to this one
  7279. offsetResult.set((xi + 0.75) * elementSize, // sort of center of a triangle
  7280. (yi + 0.75) * elementSize, h // vertical center
  7281. ); // Top triangle verts
  7282. verts[0].set(0.25 * elementSize, 0.25 * elementSize, data[xi + 1][yi + 1] - h);
  7283. verts[1].set(-0.75 * elementSize, 0.25 * elementSize, data[xi][yi + 1] - h);
  7284. verts[2].set(0.25 * elementSize, -0.75 * elementSize, data[xi + 1][yi] - h); // bottom triangle verts
  7285. verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
  7286. verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
  7287. verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle
  7288. faces[0][0] = 0;
  7289. faces[0][1] = 1;
  7290. faces[0][2] = 2; // bottom triangle
  7291. faces[1][0] = 5;
  7292. faces[1][1] = 4;
  7293. faces[1][2] = 3; // +x facing quad
  7294. faces[2][0] = 2;
  7295. faces[2][1] = 5;
  7296. faces[2][2] = 3;
  7297. faces[2][3] = 0; // +y facing quad
  7298. faces[3][0] = 3;
  7299. faces[3][1] = 4;
  7300. faces[3][2] = 1;
  7301. faces[3][3] = 0; // -xy facing quad
  7302. faces[4][0] = 1;
  7303. faces[4][1] = 4;
  7304. faces[4][2] = 5;
  7305. faces[4][3] = 2;
  7306. }
  7307. result.computeNormals();
  7308. result.computeEdges();
  7309. result.updateBoundingSphereRadius();
  7310. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  7311. }
  7312. calculateLocalInertia(mass, target) {
  7313. if (target === void 0) {
  7314. target = new Vec3();
  7315. }
  7316. target.set(0, 0, 0);
  7317. return target;
  7318. }
  7319. volume() {
  7320. return (// The terrain is infinite
  7321. Number.MAX_VALUE
  7322. );
  7323. }
  7324. calculateWorldAABB(pos, quat, min, max) {
  7325. /** @TODO do it properly */
  7326. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7327. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7328. }
  7329. updateBoundingSphereRadius() {
  7330. // Use the bounding box of the min/max values
  7331. const data = this.data;
  7332. const s = this.elementSize;
  7333. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).length();
  7334. }
  7335. /**
  7336. * Sets the height values from an image. Currently only supported in browser.
  7337. */
  7338. setHeightsFromImage(image, scale) {
  7339. const {
  7340. x,
  7341. z,
  7342. y
  7343. } = scale;
  7344. const canvas = document.createElement('canvas');
  7345. canvas.width = image.width;
  7346. canvas.height = image.height;
  7347. const context = canvas.getContext('2d');
  7348. context.drawImage(image, 0, 0);
  7349. const imageData = context.getImageData(0, 0, image.width, image.height);
  7350. const matrix = this.data;
  7351. matrix.length = 0;
  7352. this.elementSize = Math.abs(x) / imageData.width;
  7353. for (let i = 0; i < imageData.height; i++) {
  7354. const row = [];
  7355. for (let j = 0; j < imageData.width; j++) {
  7356. const a = imageData.data[(i * imageData.height + j) * 4];
  7357. const b = imageData.data[(i * imageData.height + j) * 4 + 1];
  7358. const c = imageData.data[(i * imageData.height + j) * 4 + 2];
  7359. const height = (a + b + c) / 4 / 255 * z;
  7360. if (x < 0) {
  7361. row.push(height);
  7362. } else {
  7363. row.unshift(height);
  7364. }
  7365. }
  7366. if (y < 0) {
  7367. matrix.unshift(row);
  7368. } else {
  7369. matrix.push(row);
  7370. }
  7371. }
  7372. this.updateMaxValue();
  7373. this.updateMinValue();
  7374. this.update();
  7375. }
  7376. }
  7377. const getHeightAt_idx = [];
  7378. const getHeightAt_weights = new Vec3();
  7379. const getHeightAt_a = new Vec3();
  7380. const getHeightAt_b = new Vec3();
  7381. const getHeightAt_c = new Vec3();
  7382. const getNormalAt_a = new Vec3();
  7383. const getNormalAt_b = new Vec3();
  7384. const getNormalAt_c = new Vec3();
  7385. const getNormalAt_e0 = new Vec3();
  7386. const getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system
  7387. function barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result) {
  7388. result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
  7389. result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
  7390. result.z = 1 - result.x - result.y;
  7391. }
  7392. /**
  7393. * OctreeNode
  7394. */
  7395. class OctreeNode {
  7396. /** The root node */
  7397. /** Boundary of this node */
  7398. /** Contained data at the current node level */
  7399. /** Children to this node */
  7400. constructor(options) {
  7401. if (options === void 0) {
  7402. options = {};
  7403. }
  7404. this.root = options.root || null;
  7405. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  7406. this.data = [];
  7407. this.children = [];
  7408. }
  7409. /**
  7410. * reset
  7411. */
  7412. reset() {
  7413. this.children.length = this.data.length = 0;
  7414. }
  7415. /**
  7416. * Insert data into this node
  7417. * @return True if successful, otherwise false
  7418. */
  7419. insert(aabb, elementData, level) {
  7420. if (level === void 0) {
  7421. level = 0;
  7422. }
  7423. const nodeData = this.data; // Ignore objects that do not belong in this node
  7424. if (!this.aabb.contains(aabb)) {
  7425. return false; // object cannot be added
  7426. }
  7427. const children = this.children;
  7428. const maxDepth = this.maxDepth || this.root.maxDepth;
  7429. if (level < maxDepth) {
  7430. // Subdivide if there are no children yet
  7431. let subdivided = false;
  7432. if (!children.length) {
  7433. this.subdivide();
  7434. subdivided = true;
  7435. } // add to whichever node will accept it
  7436. for (let i = 0; i !== 8; i++) {
  7437. if (children[i].insert(aabb, elementData, level + 1)) {
  7438. return true;
  7439. }
  7440. }
  7441. if (subdivided) {
  7442. // No children accepted! Might as well just remove em since they contain none
  7443. children.length = 0;
  7444. }
  7445. } // Too deep, or children didnt want it. add it in current node
  7446. nodeData.push(elementData);
  7447. return true;
  7448. }
  7449. /**
  7450. * Create 8 equally sized children nodes and put them in the `children` array.
  7451. */
  7452. subdivide() {
  7453. const aabb = this.aabb;
  7454. const l = aabb.lowerBound;
  7455. const u = aabb.upperBound;
  7456. const children = this.children;
  7457. children.push(new OctreeNode({
  7458. aabb: new AABB({
  7459. lowerBound: new Vec3(0, 0, 0)
  7460. })
  7461. }), new OctreeNode({
  7462. aabb: new AABB({
  7463. lowerBound: new Vec3(1, 0, 0)
  7464. })
  7465. }), new OctreeNode({
  7466. aabb: new AABB({
  7467. lowerBound: new Vec3(1, 1, 0)
  7468. })
  7469. }), new OctreeNode({
  7470. aabb: new AABB({
  7471. lowerBound: new Vec3(1, 1, 1)
  7472. })
  7473. }), new OctreeNode({
  7474. aabb: new AABB({
  7475. lowerBound: new Vec3(0, 1, 1)
  7476. })
  7477. }), new OctreeNode({
  7478. aabb: new AABB({
  7479. lowerBound: new Vec3(0, 0, 1)
  7480. })
  7481. }), new OctreeNode({
  7482. aabb: new AABB({
  7483. lowerBound: new Vec3(1, 0, 1)
  7484. })
  7485. }), new OctreeNode({
  7486. aabb: new AABB({
  7487. lowerBound: new Vec3(0, 1, 0)
  7488. })
  7489. }));
  7490. u.vsub(l, halfDiagonal);
  7491. halfDiagonal.scale(0.5, halfDiagonal);
  7492. const root = this.root || this;
  7493. for (let i = 0; i !== 8; i++) {
  7494. const child = children[i]; // Set current node as root
  7495. child.root = root; // Compute bounds
  7496. const lowerBound = child.aabb.lowerBound;
  7497. lowerBound.x *= halfDiagonal.x;
  7498. lowerBound.y *= halfDiagonal.y;
  7499. lowerBound.z *= halfDiagonal.z;
  7500. lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal
  7501. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  7502. }
  7503. }
  7504. /**
  7505. * Get all data, potentially within an AABB
  7506. * @return The "result" object
  7507. */
  7508. aabbQuery(aabb, result) {
  7509. this.data; // abort if the range does not intersect this node
  7510. // if (!this.aabb.overlaps(aabb)){
  7511. // return result;
  7512. // }
  7513. // Add objects at this level
  7514. // Array.prototype.push.apply(result, nodeData);
  7515. // Add child data
  7516. // @todo unwrap recursion into a queue / loop, that's faster in JS
  7517. this.children; // for (let i = 0, N = this.children.length; i !== N; i++) {
  7518. // children[i].aabbQuery(aabb, result);
  7519. // }
  7520. const queue = [this];
  7521. while (queue.length) {
  7522. const node = queue.pop();
  7523. if (node.aabb.overlaps(aabb)) {
  7524. Array.prototype.push.apply(result, node.data);
  7525. }
  7526. Array.prototype.push.apply(queue, node.children);
  7527. }
  7528. return result;
  7529. }
  7530. /**
  7531. * Get all data, potentially intersected by a ray.
  7532. * @return The "result" object
  7533. */
  7534. rayQuery(ray, treeTransform, result) {
  7535. // Use aabb query for now.
  7536. /** @todo implement real ray query which needs less lookups */
  7537. ray.getAABB(tmpAABB);
  7538. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  7539. this.aabbQuery(tmpAABB, result);
  7540. return result;
  7541. }
  7542. /**
  7543. * removeEmptyNodes
  7544. */
  7545. removeEmptyNodes() {
  7546. for (let i = this.children.length - 1; i >= 0; i--) {
  7547. this.children[i].removeEmptyNodes();
  7548. if (!this.children[i].children.length && !this.children[i].data.length) {
  7549. this.children.splice(i, 1);
  7550. }
  7551. }
  7552. }
  7553. }
  7554. /**
  7555. * Octree
  7556. */
  7557. class Octree extends OctreeNode {
  7558. /**
  7559. * Maximum subdivision depth
  7560. * @default 8
  7561. */
  7562. /**
  7563. * @param aabb The total AABB of the tree
  7564. */
  7565. constructor(aabb, options) {
  7566. if (options === void 0) {
  7567. options = {};
  7568. }
  7569. super({
  7570. root: null,
  7571. aabb
  7572. });
  7573. this.maxDepth = typeof options.maxDepth !== 'undefined' ? options.maxDepth : 8;
  7574. }
  7575. }
  7576. const halfDiagonal = new Vec3();
  7577. const tmpAABB = new AABB();
  7578. /**
  7579. * Trimesh.
  7580. * @example
  7581. * // How to make a mesh with a single triangle
  7582. * const vertices = [
  7583. * 0, 0, 0, // vertex 0
  7584. * 1, 0, 0, // vertex 1
  7585. * 0, 1, 0 // vertex 2
  7586. * ]
  7587. * const indices = [
  7588. * 0, 1, 2 // triangle 0
  7589. * ]
  7590. * const trimeshShape = new CANNON.Trimesh(vertices, indices)
  7591. */
  7592. class Trimesh extends Shape {
  7593. /**
  7594. * vertices
  7595. */
  7596. /**
  7597. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  7598. */
  7599. /**
  7600. * The normals data.
  7601. */
  7602. /**
  7603. * The local AABB of the mesh.
  7604. */
  7605. /**
  7606. * References to vertex pairs, making up all unique edges in the trimesh.
  7607. */
  7608. /**
  7609. * Local scaling of the mesh. Use .setScale() to set it.
  7610. */
  7611. /**
  7612. * The indexed triangles. Use .updateTree() to update it.
  7613. */
  7614. constructor(vertices, indices) {
  7615. super({
  7616. type: Shape.types.TRIMESH
  7617. });
  7618. this.vertices = new Float32Array(vertices);
  7619. this.indices = new Int16Array(indices);
  7620. this.normals = new Float32Array(indices.length);
  7621. this.aabb = new AABB();
  7622. this.edges = null;
  7623. this.scale = new Vec3(1, 1, 1);
  7624. this.tree = new Octree();
  7625. this.updateEdges();
  7626. this.updateNormals();
  7627. this.updateAABB();
  7628. this.updateBoundingSphereRadius();
  7629. this.updateTree();
  7630. }
  7631. /**
  7632. * updateTree
  7633. */
  7634. updateTree() {
  7635. const tree = this.tree;
  7636. tree.reset();
  7637. tree.aabb.copy(this.aabb);
  7638. const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  7639. tree.aabb.lowerBound.x *= 1 / scale.x;
  7640. tree.aabb.lowerBound.y *= 1 / scale.y;
  7641. tree.aabb.lowerBound.z *= 1 / scale.z;
  7642. tree.aabb.upperBound.x *= 1 / scale.x;
  7643. tree.aabb.upperBound.y *= 1 / scale.y;
  7644. tree.aabb.upperBound.z *= 1 / scale.z; // Insert all triangles
  7645. const triangleAABB = new AABB();
  7646. const a = new Vec3();
  7647. const b = new Vec3();
  7648. const c = new Vec3();
  7649. const points = [a, b, c];
  7650. for (let i = 0; i < this.indices.length / 3; i++) {
  7651. //this.getTriangleVertices(i, a, b, c);
  7652. // Get unscaled triangle verts
  7653. const i3 = i * 3;
  7654. this._getUnscaledVertex(this.indices[i3], a);
  7655. this._getUnscaledVertex(this.indices[i3 + 1], b);
  7656. this._getUnscaledVertex(this.indices[i3 + 2], c);
  7657. triangleAABB.setFromPoints(points);
  7658. tree.insert(triangleAABB, i);
  7659. }
  7660. tree.removeEmptyNodes();
  7661. }
  7662. /**
  7663. * Get triangles in a local AABB from the trimesh.
  7664. * @param result An array of integers, referencing the queried triangles.
  7665. */
  7666. getTrianglesInAABB(aabb, result) {
  7667. unscaledAABB.copy(aabb); // Scale it to local
  7668. const scale = this.scale;
  7669. const isx = scale.x;
  7670. const isy = scale.y;
  7671. const isz = scale.z;
  7672. const l = unscaledAABB.lowerBound;
  7673. const u = unscaledAABB.upperBound;
  7674. l.x /= isx;
  7675. l.y /= isy;
  7676. l.z /= isz;
  7677. u.x /= isx;
  7678. u.y /= isy;
  7679. u.z /= isz;
  7680. return this.tree.aabbQuery(unscaledAABB, result);
  7681. }
  7682. /**
  7683. * setScale
  7684. */
  7685. setScale(scale) {
  7686. const wasUniform = this.scale.x === this.scale.y && this.scale.y === this.scale.z;
  7687. const isUniform = scale.x === scale.y && scale.y === scale.z;
  7688. if (!(wasUniform && isUniform)) {
  7689. // Non-uniform scaling. Need to update normals.
  7690. this.updateNormals();
  7691. }
  7692. this.scale.copy(scale);
  7693. this.updateAABB();
  7694. this.updateBoundingSphereRadius();
  7695. }
  7696. /**
  7697. * Compute the normals of the faces. Will save in the `.normals` array.
  7698. */
  7699. updateNormals() {
  7700. const n = computeNormals_n; // Generate normals
  7701. const normals = this.normals;
  7702. for (let i = 0; i < this.indices.length / 3; i++) {
  7703. const i3 = i * 3;
  7704. const a = this.indices[i3];
  7705. const b = this.indices[i3 + 1];
  7706. const c = this.indices[i3 + 2];
  7707. this.getVertex(a, va);
  7708. this.getVertex(b, vb);
  7709. this.getVertex(c, vc);
  7710. Trimesh.computeNormal(vb, va, vc, n);
  7711. normals[i3] = n.x;
  7712. normals[i3 + 1] = n.y;
  7713. normals[i3 + 2] = n.z;
  7714. }
  7715. }
  7716. /**
  7717. * Update the `.edges` property
  7718. */
  7719. updateEdges() {
  7720. const edges = {};
  7721. const add = (a, b) => {
  7722. const key = a < b ? `${a}_${b}` : `${b}_${a}`;
  7723. edges[key] = true;
  7724. };
  7725. for (let i = 0; i < this.indices.length / 3; i++) {
  7726. const i3 = i * 3;
  7727. const a = this.indices[i3];
  7728. const b = this.indices[i3 + 1];
  7729. const c = this.indices[i3 + 2];
  7730. add(a, b);
  7731. add(b, c);
  7732. add(c, a);
  7733. }
  7734. const keys = Object.keys(edges);
  7735. this.edges = new Int16Array(keys.length * 2);
  7736. for (let i = 0; i < keys.length; i++) {
  7737. const indices = keys[i].split('_');
  7738. this.edges[2 * i] = parseInt(indices[0], 10);
  7739. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  7740. }
  7741. }
  7742. /**
  7743. * Get an edge vertex
  7744. * @param firstOrSecond 0 or 1, depending on which one of the vertices you need.
  7745. * @param vertexStore Where to store the result
  7746. */
  7747. getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) {
  7748. const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  7749. this.getVertex(vertexIndex, vertexStore);
  7750. }
  7751. /**
  7752. * Get a vector along an edge.
  7753. */
  7754. getEdgeVector(edgeIndex, vectorStore) {
  7755. const va = getEdgeVector_va;
  7756. const vb = getEdgeVector_vb;
  7757. this.getEdgeVertex(edgeIndex, 0, va);
  7758. this.getEdgeVertex(edgeIndex, 1, vb);
  7759. vb.vsub(va, vectorStore);
  7760. }
  7761. /**
  7762. * Get face normal given 3 vertices
  7763. */
  7764. static computeNormal(va, vb, vc, target) {
  7765. vb.vsub(va, ab);
  7766. vc.vsub(vb, cb);
  7767. cb.cross(ab, target);
  7768. if (!target.isZero()) {
  7769. target.normalize();
  7770. }
  7771. }
  7772. /**
  7773. * Get vertex i.
  7774. * @return The "out" vector object
  7775. */
  7776. getVertex(i, out) {
  7777. const scale = this.scale;
  7778. this._getUnscaledVertex(i, out);
  7779. out.x *= scale.x;
  7780. out.y *= scale.y;
  7781. out.z *= scale.z;
  7782. return out;
  7783. }
  7784. /**
  7785. * Get raw vertex i
  7786. * @return The "out" vector object
  7787. */
  7788. _getUnscaledVertex(i, out) {
  7789. const i3 = i * 3;
  7790. const vertices = this.vertices;
  7791. return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]);
  7792. }
  7793. /**
  7794. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  7795. * @return The "out" vector object
  7796. */
  7797. getWorldVertex(i, pos, quat, out) {
  7798. this.getVertex(i, out);
  7799. Transform.pointToWorldFrame(pos, quat, out, out);
  7800. return out;
  7801. }
  7802. /**
  7803. * Get the three vertices for triangle i.
  7804. */
  7805. getTriangleVertices(i, a, b, c) {
  7806. const i3 = i * 3;
  7807. this.getVertex(this.indices[i3], a);
  7808. this.getVertex(this.indices[i3 + 1], b);
  7809. this.getVertex(this.indices[i3 + 2], c);
  7810. }
  7811. /**
  7812. * Compute the normal of triangle i.
  7813. * @return The "target" vector object
  7814. */
  7815. getNormal(i, target) {
  7816. const i3 = i * 3;
  7817. return target.set(this.normals[i3], this.normals[i3 + 1], this.normals[i3 + 2]);
  7818. }
  7819. /**
  7820. * @return The "target" vector object
  7821. */
  7822. calculateLocalInertia(mass, target) {
  7823. // Approximate with box inertia
  7824. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  7825. this.computeLocalAABB(cli_aabb);
  7826. const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x;
  7827. const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y;
  7828. const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  7829. 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));
  7830. }
  7831. /**
  7832. * Compute the local AABB for the trimesh
  7833. */
  7834. computeLocalAABB(aabb) {
  7835. const l = aabb.lowerBound;
  7836. const u = aabb.upperBound;
  7837. const n = this.vertices.length;
  7838. this.vertices;
  7839. const v = computeLocalAABB_worldVert;
  7840. this.getVertex(0, v);
  7841. l.copy(v);
  7842. u.copy(v);
  7843. for (let i = 0; i !== n; i++) {
  7844. this.getVertex(i, v);
  7845. if (v.x < l.x) {
  7846. l.x = v.x;
  7847. } else if (v.x > u.x) {
  7848. u.x = v.x;
  7849. }
  7850. if (v.y < l.y) {
  7851. l.y = v.y;
  7852. } else if (v.y > u.y) {
  7853. u.y = v.y;
  7854. }
  7855. if (v.z < l.z) {
  7856. l.z = v.z;
  7857. } else if (v.z > u.z) {
  7858. u.z = v.z;
  7859. }
  7860. }
  7861. }
  7862. /**
  7863. * Update the `.aabb` property
  7864. */
  7865. updateAABB() {
  7866. this.computeLocalAABB(this.aabb);
  7867. }
  7868. /**
  7869. * Will update the `.boundingSphereRadius` property
  7870. */
  7871. updateBoundingSphereRadius() {
  7872. // Assume points are distributed with local (0,0,0) as center
  7873. let max2 = 0;
  7874. const vertices = this.vertices;
  7875. const v = new Vec3();
  7876. for (let i = 0, N = vertices.length / 3; i !== N; i++) {
  7877. this.getVertex(i, v);
  7878. const norm2 = v.lengthSquared();
  7879. if (norm2 > max2) {
  7880. max2 = norm2;
  7881. }
  7882. }
  7883. this.boundingSphereRadius = Math.sqrt(max2);
  7884. }
  7885. /**
  7886. * calculateWorldAABB
  7887. */
  7888. calculateWorldAABB(pos, quat, min, max) {
  7889. /*
  7890. const n = this.vertices.length / 3,
  7891. verts = this.vertices;
  7892. const minx,miny,minz,maxx,maxy,maxz;
  7893. const v = tempWorldVertex;
  7894. for(let i=0; i<n; i++){
  7895. this.getVertex(i, v);
  7896. quat.vmult(v, v);
  7897. pos.vadd(v, v);
  7898. if (v.x < minx || minx===undefined){
  7899. minx = v.x;
  7900. } else if(v.x > maxx || maxx===undefined){
  7901. maxx = v.x;
  7902. }
  7903. if (v.y < miny || miny===undefined){
  7904. miny = v.y;
  7905. } else if(v.y > maxy || maxy===undefined){
  7906. maxy = v.y;
  7907. }
  7908. if (v.z < minz || minz===undefined){
  7909. minz = v.z;
  7910. } else if(v.z > maxz || maxz===undefined){
  7911. maxz = v.z;
  7912. }
  7913. }
  7914. min.set(minx,miny,minz);
  7915. max.set(maxx,maxy,maxz);
  7916. */
  7917. // Faster approximation using local AABB
  7918. const frame = calculateWorldAABB_frame;
  7919. const result = calculateWorldAABB_aabb;
  7920. frame.position = pos;
  7921. frame.quaternion = quat;
  7922. this.aabb.toWorldFrame(frame, result);
  7923. min.copy(result.lowerBound);
  7924. max.copy(result.upperBound);
  7925. }
  7926. /**
  7927. * Get approximate volume
  7928. */
  7929. volume() {
  7930. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  7931. }
  7932. /**
  7933. * Create a Trimesh instance, shaped as a torus.
  7934. */
  7935. static createTorus(radius, tube, radialSegments, tubularSegments, arc) {
  7936. if (radius === void 0) {
  7937. radius = 1;
  7938. }
  7939. if (tube === void 0) {
  7940. tube = 0.5;
  7941. }
  7942. if (radialSegments === void 0) {
  7943. radialSegments = 8;
  7944. }
  7945. if (tubularSegments === void 0) {
  7946. tubularSegments = 6;
  7947. }
  7948. if (arc === void 0) {
  7949. arc = Math.PI * 2;
  7950. }
  7951. const vertices = [];
  7952. const indices = [];
  7953. for (let j = 0; j <= radialSegments; j++) {
  7954. for (let i = 0; i <= tubularSegments; i++) {
  7955. const u = i / tubularSegments * arc;
  7956. const v = j / radialSegments * Math.PI * 2;
  7957. const x = (radius + tube * Math.cos(v)) * Math.cos(u);
  7958. const y = (radius + tube * Math.cos(v)) * Math.sin(u);
  7959. const z = tube * Math.sin(v);
  7960. vertices.push(x, y, z);
  7961. }
  7962. }
  7963. for (let j = 1; j <= radialSegments; j++) {
  7964. for (let i = 1; i <= tubularSegments; i++) {
  7965. const a = (tubularSegments + 1) * j + i - 1;
  7966. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  7967. const c = (tubularSegments + 1) * (j - 1) + i;
  7968. const d = (tubularSegments + 1) * j + i;
  7969. indices.push(a, b, d);
  7970. indices.push(b, c, d);
  7971. }
  7972. }
  7973. return new Trimesh(vertices, indices);
  7974. }
  7975. }
  7976. const computeNormals_n = new Vec3();
  7977. const unscaledAABB = new AABB();
  7978. const getEdgeVector_va = new Vec3();
  7979. const getEdgeVector_vb = new Vec3();
  7980. const cb = new Vec3();
  7981. const ab = new Vec3();
  7982. const va = new Vec3();
  7983. const vb = new Vec3();
  7984. const vc = new Vec3();
  7985. const cli_aabb = new AABB();
  7986. const computeLocalAABB_worldVert = new Vec3();
  7987. const calculateWorldAABB_frame = new Transform();
  7988. const calculateWorldAABB_aabb = new AABB();
  7989. /**
  7990. * Constraint equation solver base class.
  7991. */
  7992. class Solver {
  7993. /**
  7994. * All equations to be solved
  7995. */
  7996. /**
  7997. * @todo remove useless constructor
  7998. */
  7999. constructor() {
  8000. this.equations = [];
  8001. }
  8002. /**
  8003. * Should be implemented in subclasses!
  8004. * @todo use abstract
  8005. * @return number of iterations performed
  8006. */
  8007. solve(dt, world) {
  8008. return (// Should return the number of iterations done!
  8009. 0
  8010. );
  8011. }
  8012. /**
  8013. * Add an equation
  8014. */
  8015. addEquation(eq) {
  8016. if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) {
  8017. this.equations.push(eq);
  8018. }
  8019. }
  8020. /**
  8021. * Remove an equation
  8022. */
  8023. removeEquation(eq) {
  8024. const eqs = this.equations;
  8025. const i = eqs.indexOf(eq);
  8026. if (i !== -1) {
  8027. eqs.splice(i, 1);
  8028. }
  8029. }
  8030. /**
  8031. * Add all equations
  8032. */
  8033. removeAllEquations() {
  8034. this.equations.length = 0;
  8035. }
  8036. }
  8037. /**
  8038. * Constraint equation Gauss-Seidel solver.
  8039. * @todo The spook parameters should be specified for each constraint, not globally.
  8040. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  8041. */
  8042. class GSSolver extends Solver {
  8043. /**
  8044. * The number of solver iterations determines quality of the constraints in the world.
  8045. * 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.
  8046. */
  8047. /**
  8048. * When tolerance is reached, the system is assumed to be converged.
  8049. */
  8050. /**
  8051. * @todo remove useless constructor
  8052. */
  8053. constructor() {
  8054. super();
  8055. this.iterations = 10;
  8056. this.tolerance = 1e-7;
  8057. }
  8058. /**
  8059. * Solve
  8060. * @return number of iterations performed
  8061. */
  8062. solve(dt, world) {
  8063. let iter = 0;
  8064. const maxIter = this.iterations;
  8065. const tolSquared = this.tolerance * this.tolerance;
  8066. const equations = this.equations;
  8067. const Neq = equations.length;
  8068. const bodies = world.bodies;
  8069. const Nbodies = bodies.length;
  8070. const h = dt;
  8071. let B;
  8072. let invC;
  8073. let deltalambda;
  8074. let deltalambdaTot;
  8075. let GWlambda;
  8076. let lambdaj; // Update solve mass
  8077. if (Neq !== 0) {
  8078. for (let i = 0; i !== Nbodies; i++) {
  8079. bodies[i].updateSolveMassProperties();
  8080. }
  8081. } // Things that do not change during iteration can be computed once
  8082. const invCs = GSSolver_solve_invCs;
  8083. const Bs = GSSolver_solve_Bs;
  8084. const lambda = GSSolver_solve_lambda;
  8085. invCs.length = Neq;
  8086. Bs.length = Neq;
  8087. lambda.length = Neq;
  8088. for (let i = 0; i !== Neq; i++) {
  8089. const c = equations[i];
  8090. lambda[i] = 0.0;
  8091. Bs[i] = c.computeB(h);
  8092. invCs[i] = 1.0 / c.computeC();
  8093. }
  8094. if (Neq !== 0) {
  8095. // Reset vlambda
  8096. for (let i = 0; i !== Nbodies; i++) {
  8097. const b = bodies[i];
  8098. const vlambda = b.vlambda;
  8099. const wlambda = b.wlambda;
  8100. vlambda.set(0, 0, 0);
  8101. wlambda.set(0, 0, 0);
  8102. } // Iterate over equations
  8103. for (iter = 0; iter !== maxIter; iter++) {
  8104. // Accumulate the total error for each iteration.
  8105. deltalambdaTot = 0.0;
  8106. for (let j = 0; j !== Neq; j++) {
  8107. const c = equations[j]; // Compute iteration
  8108. B = Bs[j];
  8109. invC = invCs[j];
  8110. lambdaj = lambda[j];
  8111. GWlambda = c.computeGWlambda();
  8112. deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval
  8113. if (lambdaj + deltalambda < c.minForce) {
  8114. deltalambda = c.minForce - lambdaj;
  8115. } else if (lambdaj + deltalambda > c.maxForce) {
  8116. deltalambda = c.maxForce - lambdaj;
  8117. }
  8118. lambda[j] += deltalambda;
  8119. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  8120. c.addToWlambda(deltalambda);
  8121. } // If the total error is small enough - stop iterate
  8122. if (deltalambdaTot * deltalambdaTot < tolSquared) {
  8123. break;
  8124. }
  8125. } // Add result to velocity
  8126. for (let i = 0; i !== Nbodies; i++) {
  8127. const b = bodies[i];
  8128. const v = b.velocity;
  8129. const w = b.angularVelocity;
  8130. b.vlambda.vmul(b.linearFactor, b.vlambda);
  8131. v.vadd(b.vlambda, v);
  8132. b.wlambda.vmul(b.angularFactor, b.wlambda);
  8133. w.vadd(b.wlambda, w);
  8134. } // Set the `.multiplier` property of each equation
  8135. let l = equations.length;
  8136. const invDt = 1 / h;
  8137. while (l--) {
  8138. equations[l].multiplier = lambda[l] * invDt;
  8139. }
  8140. }
  8141. return iter;
  8142. }
  8143. } // Just temporary number holders that we want to reuse each iteration.
  8144. const GSSolver_solve_lambda = [];
  8145. const GSSolver_solve_invCs = [];
  8146. const GSSolver_solve_Bs = [];
  8147. /**
  8148. * Splits the equations into islands and solves them independently. Can improve performance.
  8149. */
  8150. class SplitSolver extends Solver {
  8151. /**
  8152. * 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.
  8153. */
  8154. /**
  8155. * When tolerance is reached, the system is assumed to be converged.
  8156. */
  8157. /** subsolver */
  8158. constructor(subsolver) {
  8159. super();
  8160. this.iterations = 10;
  8161. this.tolerance = 1e-7;
  8162. this.subsolver = subsolver;
  8163. this.nodes = [];
  8164. this.nodePool = []; // Create needed nodes, reuse if possible
  8165. while (this.nodePool.length < 128) {
  8166. this.nodePool.push(this.createNode());
  8167. }
  8168. }
  8169. /**
  8170. * createNode
  8171. */
  8172. createNode() {
  8173. return {
  8174. body: null,
  8175. children: [],
  8176. eqs: [],
  8177. visited: false
  8178. };
  8179. }
  8180. /**
  8181. * Solve the subsystems
  8182. * @return number of iterations performed
  8183. */
  8184. solve(dt, world) {
  8185. const nodes = SplitSolver_solve_nodes;
  8186. const nodePool = this.nodePool;
  8187. const bodies = world.bodies;
  8188. const equations = this.equations;
  8189. const Neq = equations.length;
  8190. const Nbodies = bodies.length;
  8191. const subsolver = this.subsolver; // Create needed nodes, reuse if possible
  8192. while (nodePool.length < Nbodies) {
  8193. nodePool.push(this.createNode());
  8194. }
  8195. nodes.length = Nbodies;
  8196. for (let i = 0; i < Nbodies; i++) {
  8197. nodes[i] = nodePool[i];
  8198. } // Reset node values
  8199. for (let i = 0; i !== Nbodies; i++) {
  8200. const node = nodes[i];
  8201. node.body = bodies[i];
  8202. node.children.length = 0;
  8203. node.eqs.length = 0;
  8204. node.visited = false;
  8205. }
  8206. for (let k = 0; k !== Neq; k++) {
  8207. const eq = equations[k];
  8208. const i = bodies.indexOf(eq.bi);
  8209. const j = bodies.indexOf(eq.bj);
  8210. const ni = nodes[i];
  8211. const nj = nodes[j];
  8212. ni.children.push(nj);
  8213. ni.eqs.push(eq);
  8214. nj.children.push(ni);
  8215. nj.eqs.push(eq);
  8216. }
  8217. let child;
  8218. let n = 0;
  8219. let eqs = SplitSolver_solve_eqs;
  8220. subsolver.tolerance = this.tolerance;
  8221. subsolver.iterations = this.iterations;
  8222. const dummyWorld = SplitSolver_solve_dummyWorld;
  8223. while (child = getUnvisitedNode(nodes)) {
  8224. eqs.length = 0;
  8225. dummyWorld.bodies.length = 0;
  8226. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  8227. const Neqs = eqs.length;
  8228. eqs = eqs.sort(sortById);
  8229. for (let i = 0; i !== Neqs; i++) {
  8230. subsolver.addEquation(eqs[i]);
  8231. }
  8232. subsolver.solve(dt, dummyWorld);
  8233. subsolver.removeAllEquations();
  8234. n++;
  8235. }
  8236. return n;
  8237. }
  8238. } // Returns the number of subsystems
  8239. const SplitSolver_solve_nodes = []; // All allocated node objects
  8240. const SplitSolver_solve_eqs = []; // Temp array
  8241. const SplitSolver_solve_dummyWorld = {
  8242. bodies: []
  8243. }; // Temp object
  8244. const STATIC = Body.STATIC;
  8245. function getUnvisitedNode(nodes) {
  8246. const Nnodes = nodes.length;
  8247. for (let i = 0; i !== Nnodes; i++) {
  8248. const node = nodes[i];
  8249. if (!node.visited && !(node.body.type & STATIC)) {
  8250. return node;
  8251. }
  8252. }
  8253. return false;
  8254. }
  8255. const queue = [];
  8256. function bfs(root, visitFunc, bds, eqs) {
  8257. queue.push(root);
  8258. root.visited = true;
  8259. visitFunc(root, bds, eqs);
  8260. while (queue.length) {
  8261. const node = queue.pop(); // Loop over unvisited child nodes
  8262. let child;
  8263. while (child = getUnvisitedNode(node.children)) {
  8264. child.visited = true;
  8265. visitFunc(child, bds, eqs);
  8266. queue.push(child);
  8267. }
  8268. }
  8269. }
  8270. function visitFunc(node, bds, eqs) {
  8271. bds.push(node.body);
  8272. const Neqs = node.eqs.length;
  8273. for (let i = 0; i !== Neqs; i++) {
  8274. const eq = node.eqs[i];
  8275. if (!eqs.includes(eq)) {
  8276. eqs.push(eq);
  8277. }
  8278. }
  8279. }
  8280. function sortById(a, b) {
  8281. return b.id - a.id;
  8282. }
  8283. /**
  8284. * For pooling objects that can be reused.
  8285. */
  8286. class Pool {
  8287. constructor() {
  8288. this.objects = [];
  8289. this.type = Object;
  8290. }
  8291. /**
  8292. * Release an object after use
  8293. */
  8294. release() {
  8295. const Nargs = arguments.length;
  8296. for (let i = 0; i !== Nargs; i++) {
  8297. this.objects.push(i < 0 || arguments.length <= i ? undefined : arguments[i]);
  8298. }
  8299. return this;
  8300. }
  8301. /**
  8302. * Get an object
  8303. */
  8304. get() {
  8305. if (this.objects.length === 0) {
  8306. return this.constructObject();
  8307. } else {
  8308. return this.objects.pop();
  8309. }
  8310. }
  8311. /**
  8312. * Construct an object. Should be implemented in each subclass.
  8313. */
  8314. constructObject() {
  8315. throw new Error('constructObject() not implemented in this Pool subclass yet!');
  8316. }
  8317. /**
  8318. * @return Self, for chaining
  8319. */
  8320. resize(size) {
  8321. const objects = this.objects;
  8322. while (objects.length > size) {
  8323. objects.pop();
  8324. }
  8325. while (objects.length < size) {
  8326. objects.push(this.constructObject());
  8327. }
  8328. return this;
  8329. }
  8330. }
  8331. /**
  8332. * Vec3Pool
  8333. */
  8334. class Vec3Pool extends Pool {
  8335. constructor() {
  8336. super(...arguments);
  8337. this.type = Vec3;
  8338. }
  8339. /**
  8340. * Construct a vector
  8341. */
  8342. constructObject() {
  8343. return new Vec3();
  8344. }
  8345. }
  8346. // Naming rule: based of the order in SHAPE_TYPES,
  8347. // the first part of the method is formed by the
  8348. // shape type that comes before, in the second part
  8349. // there is the shape type that comes after in the SHAPE_TYPES list
  8350. const COLLISION_TYPES = {
  8351. sphereSphere: Shape.types.SPHERE,
  8352. spherePlane: Shape.types.SPHERE | Shape.types.PLANE,
  8353. boxBox: Shape.types.BOX | Shape.types.BOX,
  8354. sphereBox: Shape.types.SPHERE | Shape.types.BOX,
  8355. planeBox: Shape.types.PLANE | Shape.types.BOX,
  8356. convexConvex: Shape.types.CONVEXPOLYHEDRON,
  8357. sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON,
  8358. planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON,
  8359. boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON,
  8360. sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD,
  8361. boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD,
  8362. convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD,
  8363. sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE,
  8364. planeParticle: Shape.types.PLANE | Shape.types.PARTICLE,
  8365. boxParticle: Shape.types.BOX | Shape.types.PARTICLE,
  8366. convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON,
  8367. cylinderCylinder: Shape.types.CYLINDER,
  8368. sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER,
  8369. planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER,
  8370. boxCylinder: Shape.types.BOX | Shape.types.CYLINDER,
  8371. convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER,
  8372. heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER,
  8373. particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER,
  8374. sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH,
  8375. planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH
  8376. };
  8377. /**
  8378. * Helper class for the World. Generates ContactEquations.
  8379. * @todo Sphere-ConvexPolyhedron contacts
  8380. * @todo Contact reduction
  8381. * @todo should move methods to prototype
  8382. */
  8383. class Narrowphase {
  8384. /**
  8385. * Internal storage of pooled contact points.
  8386. */
  8387. /**
  8388. * Pooled vectors.
  8389. */
  8390. get [COLLISION_TYPES.sphereSphere]() {
  8391. return this.sphereSphere;
  8392. }
  8393. get [COLLISION_TYPES.spherePlane]() {
  8394. return this.spherePlane;
  8395. }
  8396. get [COLLISION_TYPES.boxBox]() {
  8397. return this.boxBox;
  8398. }
  8399. get [COLLISION_TYPES.sphereBox]() {
  8400. return this.sphereBox;
  8401. }
  8402. get [COLLISION_TYPES.planeBox]() {
  8403. return this.planeBox;
  8404. }
  8405. get [COLLISION_TYPES.convexConvex]() {
  8406. return this.convexConvex;
  8407. }
  8408. get [COLLISION_TYPES.sphereConvex]() {
  8409. return this.sphereConvex;
  8410. }
  8411. get [COLLISION_TYPES.planeConvex]() {
  8412. return this.planeConvex;
  8413. }
  8414. get [COLLISION_TYPES.boxConvex]() {
  8415. return this.boxConvex;
  8416. }
  8417. get [COLLISION_TYPES.sphereHeightfield]() {
  8418. return this.sphereHeightfield;
  8419. }
  8420. get [COLLISION_TYPES.boxHeightfield]() {
  8421. return this.boxHeightfield;
  8422. }
  8423. get [COLLISION_TYPES.convexHeightfield]() {
  8424. return this.convexHeightfield;
  8425. }
  8426. get [COLLISION_TYPES.sphereParticle]() {
  8427. return this.sphereParticle;
  8428. }
  8429. get [COLLISION_TYPES.planeParticle]() {
  8430. return this.planeParticle;
  8431. }
  8432. get [COLLISION_TYPES.boxParticle]() {
  8433. return this.boxParticle;
  8434. }
  8435. get [COLLISION_TYPES.convexParticle]() {
  8436. return this.convexParticle;
  8437. }
  8438. get [COLLISION_TYPES.cylinderCylinder]() {
  8439. return this.convexConvex;
  8440. }
  8441. get [COLLISION_TYPES.sphereCylinder]() {
  8442. return this.sphereConvex;
  8443. }
  8444. get [COLLISION_TYPES.planeCylinder]() {
  8445. return this.planeConvex;
  8446. }
  8447. get [COLLISION_TYPES.boxCylinder]() {
  8448. return this.boxConvex;
  8449. }
  8450. get [COLLISION_TYPES.convexCylinder]() {
  8451. return this.convexConvex;
  8452. }
  8453. get [COLLISION_TYPES.heightfieldCylinder]() {
  8454. return this.heightfieldCylinder;
  8455. }
  8456. get [COLLISION_TYPES.particleCylinder]() {
  8457. return this.particleCylinder;
  8458. }
  8459. get [COLLISION_TYPES.sphereTrimesh]() {
  8460. return this.sphereTrimesh;
  8461. }
  8462. get [COLLISION_TYPES.planeTrimesh]() {
  8463. return this.planeTrimesh;
  8464. } // get [COLLISION_TYPES.convexTrimesh]() {
  8465. // return this.convexTrimesh
  8466. // }
  8467. constructor(world) {
  8468. this.contactPointPool = [];
  8469. this.frictionEquationPool = [];
  8470. this.result = [];
  8471. this.frictionResult = [];
  8472. this.v3pool = new Vec3Pool();
  8473. this.world = world;
  8474. this.currentContactMaterial = world.defaultContactMaterial;
  8475. this.enableFrictionReduction = false;
  8476. }
  8477. /**
  8478. * Make a contact object, by using the internal pool or creating a new one.
  8479. */
  8480. createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) {
  8481. let c;
  8482. if (this.contactPointPool.length) {
  8483. c = this.contactPointPool.pop();
  8484. c.bi = bi;
  8485. c.bj = bj;
  8486. } else {
  8487. c = new ContactEquation(bi, bj);
  8488. }
  8489. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  8490. const cm = this.currentContactMaterial;
  8491. c.restitution = cm.restitution;
  8492. c.setSpookParams(cm.contactEquationStiffness, cm.contactEquationRelaxation, this.world.dt);
  8493. const matA = si.material || bi.material;
  8494. const matB = sj.material || bj.material;
  8495. if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) {
  8496. c.restitution = matA.restitution * matB.restitution;
  8497. }
  8498. c.si = overrideShapeA || si;
  8499. c.sj = overrideShapeB || sj;
  8500. return c;
  8501. }
  8502. createFrictionEquationsFromContact(contactEquation, outArray) {
  8503. const bodyA = contactEquation.bi;
  8504. const bodyB = contactEquation.bj;
  8505. const shapeA = contactEquation.si;
  8506. const shapeB = contactEquation.sj;
  8507. const world = this.world;
  8508. const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them
  8509. let friction = cm.friction;
  8510. const matA = shapeA.material || bodyA.material;
  8511. const matB = shapeB.material || bodyB.material;
  8512. if (matA && matB && matA.friction >= 0 && matB.friction >= 0) {
  8513. friction = matA.friction * matB.friction;
  8514. }
  8515. if (friction > 0) {
  8516. // Create 2 tangent equations
  8517. // Users may provide a force different from global gravity to use when computing contact friction.
  8518. const mug = friction * (world.frictionGravity || world.gravity).length();
  8519. let reducedMass = bodyA.invMass + bodyB.invMass;
  8520. if (reducedMass > 0) {
  8521. reducedMass = 1 / reducedMass;
  8522. }
  8523. const pool = this.frictionEquationPool;
  8524. const c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
  8525. const c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
  8526. c1.bi = c2.bi = bodyA;
  8527. c1.bj = c2.bj = bodyB;
  8528. c1.minForce = c2.minForce = -mug * reducedMass;
  8529. c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors
  8530. c1.ri.copy(contactEquation.ri);
  8531. c1.rj.copy(contactEquation.rj);
  8532. c2.ri.copy(contactEquation.ri);
  8533. c2.rj.copy(contactEquation.rj); // Construct tangents
  8534. contactEquation.ni.tangents(c1.t, c2.t); // Set spook params
  8535. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  8536. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  8537. c1.enabled = c2.enabled = contactEquation.enabled;
  8538. outArray.push(c1, c2);
  8539. return true;
  8540. }
  8541. return false;
  8542. }
  8543. /**
  8544. * Take the average N latest contact point on the plane.
  8545. */
  8546. createFrictionFromAverage(numContacts) {
  8547. // The last contactEquation
  8548. let c = this.result[this.result.length - 1]; // Create the result: two "average" friction equations
  8549. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  8550. return;
  8551. }
  8552. const f1 = this.frictionResult[this.frictionResult.length - 2];
  8553. const f2 = this.frictionResult[this.frictionResult.length - 1];
  8554. averageNormal.setZero();
  8555. averageContactPointA.setZero();
  8556. averageContactPointB.setZero();
  8557. const bodyA = c.bi;
  8558. c.bj;
  8559. for (let i = 0; i !== numContacts; i++) {
  8560. c = this.result[this.result.length - 1 - i];
  8561. if (c.bi !== bodyA) {
  8562. averageNormal.vadd(c.ni, averageNormal);
  8563. averageContactPointA.vadd(c.ri, averageContactPointA);
  8564. averageContactPointB.vadd(c.rj, averageContactPointB);
  8565. } else {
  8566. averageNormal.vsub(c.ni, averageNormal);
  8567. averageContactPointA.vadd(c.rj, averageContactPointA);
  8568. averageContactPointB.vadd(c.ri, averageContactPointB);
  8569. }
  8570. }
  8571. const invNumContacts = 1 / numContacts;
  8572. averageContactPointA.scale(invNumContacts, f1.ri);
  8573. averageContactPointB.scale(invNumContacts, f1.rj);
  8574. f2.ri.copy(f1.ri); // Should be the same
  8575. f2.rj.copy(f1.rj);
  8576. averageNormal.normalize();
  8577. averageNormal.tangents(f1.t, f2.t); // return eq;
  8578. }
  8579. /**
  8580. * Generate all contacts between a list of body pairs
  8581. * @param p1 Array of body indices
  8582. * @param p2 Array of body indices
  8583. * @param result Array to store generated contacts
  8584. * @param oldcontacts Optional. Array of reusable contact objects
  8585. */
  8586. getContacts(p1, p2, world, result, oldcontacts, frictionResult, frictionPool) {
  8587. // Save old contact objects
  8588. this.contactPointPool = oldcontacts;
  8589. this.frictionEquationPool = frictionPool;
  8590. this.result = result;
  8591. this.frictionResult = frictionResult;
  8592. const qi = tmpQuat1;
  8593. const qj = tmpQuat2;
  8594. const xi = tmpVec1;
  8595. const xj = tmpVec2;
  8596. for (let k = 0, N = p1.length; k !== N; k++) {
  8597. // Get current collision bodies
  8598. const bi = p1[k];
  8599. const bj = p2[k]; // Get contact material
  8600. let bodyContactMaterial = null;
  8601. if (bi.material && bj.material) {
  8602. bodyContactMaterial = world.getContactMaterial(bi.material, bj.material) || null;
  8603. }
  8604. 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;
  8605. for (let i = 0; i < bi.shapes.length; i++) {
  8606. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  8607. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  8608. xi.vadd(bi.position, xi);
  8609. const si = bi.shapes[i];
  8610. for (let j = 0; j < bj.shapes.length; j++) {
  8611. // Compute world transform of shapes
  8612. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  8613. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  8614. xj.vadd(bj.position, xj);
  8615. const sj = bj.shapes[j];
  8616. if (!(si.collisionFilterMask & sj.collisionFilterGroup && sj.collisionFilterMask & si.collisionFilterGroup)) {
  8617. continue;
  8618. }
  8619. if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
  8620. continue;
  8621. } // Get collision material
  8622. let shapeContactMaterial = null;
  8623. if (si.material && sj.material) {
  8624. shapeContactMaterial = world.getContactMaterial(si.material, sj.material) || null;
  8625. }
  8626. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial; // Get contacts
  8627. const resolverIndex = si.type | sj.type;
  8628. const resolver = this[resolverIndex];
  8629. if (resolver) {
  8630. let retval = false; // TO DO: investigate why sphereParticle and convexParticle
  8631. // resolvers expect si and sj shapes to be in reverse order
  8632. // (i.e. larger integer value type first instead of smaller first)
  8633. if (si.type < sj.type) {
  8634. retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8635. } else {
  8636. retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);
  8637. }
  8638. if (retval && justTest) {
  8639. // Register overlap
  8640. world.shapeOverlapKeeper.set(si.id, sj.id);
  8641. world.bodyOverlapKeeper.set(bi.id, bj.id);
  8642. }
  8643. }
  8644. }
  8645. }
  8646. }
  8647. }
  8648. sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8649. if (justTest) {
  8650. return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2;
  8651. } // We will have only one contact in this case
  8652. const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal
  8653. xj.vsub(xi, contactEq.ni);
  8654. contactEq.ni.normalize(); // Contact point locations
  8655. contactEq.ri.copy(contactEq.ni);
  8656. contactEq.rj.copy(contactEq.ni);
  8657. contactEq.ri.scale(si.radius, contactEq.ri);
  8658. contactEq.rj.scale(-sj.radius, contactEq.rj);
  8659. contactEq.ri.vadd(xi, contactEq.ri);
  8660. contactEq.ri.vsub(bi.position, contactEq.ri);
  8661. contactEq.rj.vadd(xj, contactEq.rj);
  8662. contactEq.rj.vsub(bj.position, contactEq.rj);
  8663. this.result.push(contactEq);
  8664. this.createFrictionEquationsFromContact(contactEq, this.frictionResult);
  8665. }
  8666. spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8667. // We will have one contact in this case
  8668. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal
  8669. r.ni.set(0, 0, 1);
  8670. qj.vmult(r.ni, r.ni);
  8671. r.ni.negate(r.ni); // body i is the sphere, flip normal
  8672. r.ni.normalize(); // Needed?
  8673. // Vector from sphere center to contact point
  8674. r.ni.scale(si.radius, r.ri); // Project down sphere on plane
  8675. xi.vsub(xj, point_on_plane_to_sphere);
  8676. r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  8677. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane
  8678. if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) {
  8679. if (justTest) {
  8680. return true;
  8681. } // Make it relative to the body
  8682. const ri = r.ri;
  8683. const rj = r.rj;
  8684. ri.vadd(xi, ri);
  8685. ri.vsub(bi.position, ri);
  8686. rj.vadd(xj, rj);
  8687. rj.vsub(bj.position, rj);
  8688. this.result.push(r);
  8689. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8690. }
  8691. }
  8692. boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8693. si.convexPolyhedronRepresentation.material = si.material;
  8694. sj.convexPolyhedronRepresentation.material = sj.material;
  8695. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  8696. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  8697. return this.convexConvex(si.convexPolyhedronRepresentation, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8698. }
  8699. sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8700. const v3pool = this.v3pool; // we refer to the box as body j
  8701. const sides = sphereBox_sides;
  8702. xi.vsub(xj, box_to_sphere);
  8703. sj.getSideNormals(sides, qj);
  8704. const R = si.radius;
  8705. let found = false; // Store the resulting side penetration info
  8706. const side_ns = sphereBox_side_ns;
  8707. const side_ns1 = sphereBox_side_ns1;
  8708. const side_ns2 = sphereBox_side_ns2;
  8709. let side_h = null;
  8710. let side_penetrations = 0;
  8711. let side_dot1 = 0;
  8712. let side_dot2 = 0;
  8713. let side_distance = null;
  8714. for (let idx = 0, nsides = sides.length; idx !== nsides && found === false; idx++) {
  8715. // Get the plane side normal (ns)
  8716. const ns = sphereBox_ns;
  8717. ns.copy(sides[idx]);
  8718. const h = ns.length();
  8719. ns.normalize(); // The normal/distance dot product tells which side of the plane we are
  8720. const dot = box_to_sphere.dot(ns);
  8721. if (dot < h + R && dot > 0) {
  8722. // Intersects plane. Now check the other two dimensions
  8723. const ns1 = sphereBox_ns1;
  8724. const ns2 = sphereBox_ns2;
  8725. ns1.copy(sides[(idx + 1) % 3]);
  8726. ns2.copy(sides[(idx + 2) % 3]);
  8727. const h1 = ns1.length();
  8728. const h2 = ns2.length();
  8729. ns1.normalize();
  8730. ns2.normalize();
  8731. const dot1 = box_to_sphere.dot(ns1);
  8732. const dot2 = box_to_sphere.dot(ns2);
  8733. if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) {
  8734. const dist = Math.abs(dot - h - R);
  8735. if (side_distance === null || dist < side_distance) {
  8736. side_distance = dist;
  8737. side_dot1 = dot1;
  8738. side_dot2 = dot2;
  8739. side_h = h;
  8740. side_ns.copy(ns);
  8741. side_ns1.copy(ns1);
  8742. side_ns2.copy(ns2);
  8743. side_penetrations++;
  8744. if (justTest) {
  8745. return true;
  8746. }
  8747. }
  8748. }
  8749. }
  8750. }
  8751. if (side_penetrations) {
  8752. found = true;
  8753. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8754. side_ns.scale(-R, r.ri); // Sphere r
  8755. r.ni.copy(side_ns);
  8756. r.ni.negate(r.ni); // Normal should be out of sphere
  8757. side_ns.scale(side_h, side_ns);
  8758. side_ns1.scale(side_dot1, side_ns1);
  8759. side_ns.vadd(side_ns1, side_ns);
  8760. side_ns2.scale(side_dot2, side_ns2);
  8761. side_ns.vadd(side_ns2, r.rj); // Make relative to bodies
  8762. r.ri.vadd(xi, r.ri);
  8763. r.ri.vsub(bi.position, r.ri);
  8764. r.rj.vadd(xj, r.rj);
  8765. r.rj.vsub(bj.position, r.rj);
  8766. this.result.push(r);
  8767. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8768. } // Check corners
  8769. let rj = v3pool.get();
  8770. const sphere_to_corner = sphereBox_sphere_to_corner;
  8771. for (let j = 0; j !== 2 && !found; j++) {
  8772. for (let k = 0; k !== 2 && !found; k++) {
  8773. for (let l = 0; l !== 2 && !found; l++) {
  8774. rj.set(0, 0, 0);
  8775. if (j) {
  8776. rj.vadd(sides[0], rj);
  8777. } else {
  8778. rj.vsub(sides[0], rj);
  8779. }
  8780. if (k) {
  8781. rj.vadd(sides[1], rj);
  8782. } else {
  8783. rj.vsub(sides[1], rj);
  8784. }
  8785. if (l) {
  8786. rj.vadd(sides[2], rj);
  8787. } else {
  8788. rj.vsub(sides[2], rj);
  8789. } // World position of corner
  8790. xj.vadd(rj, sphere_to_corner);
  8791. sphere_to_corner.vsub(xi, sphere_to_corner);
  8792. if (sphere_to_corner.lengthSquared() < R * R) {
  8793. if (justTest) {
  8794. return true;
  8795. }
  8796. found = true;
  8797. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8798. r.ri.copy(sphere_to_corner);
  8799. r.ri.normalize();
  8800. r.ni.copy(r.ri);
  8801. r.ri.scale(R, r.ri);
  8802. r.rj.copy(rj); // Make relative to bodies
  8803. r.ri.vadd(xi, r.ri);
  8804. r.ri.vsub(bi.position, r.ri);
  8805. r.rj.vadd(xj, r.rj);
  8806. r.rj.vsub(bj.position, r.rj);
  8807. this.result.push(r);
  8808. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8809. }
  8810. }
  8811. }
  8812. }
  8813. v3pool.release(rj);
  8814. rj = null; // Check edges
  8815. const edgeTangent = v3pool.get();
  8816. const edgeCenter = v3pool.get();
  8817. const r = v3pool.get(); // r = edge center to sphere center
  8818. const orthogonal = v3pool.get();
  8819. const dist = v3pool.get();
  8820. const Nsides = sides.length;
  8821. for (let j = 0; j !== Nsides && !found; j++) {
  8822. for (let k = 0; k !== Nsides && !found; k++) {
  8823. if (j % 3 !== k % 3) {
  8824. // Get edge tangent
  8825. sides[k].cross(sides[j], edgeTangent);
  8826. edgeTangent.normalize();
  8827. sides[j].vadd(sides[k], edgeCenter);
  8828. r.copy(xi);
  8829. r.vsub(edgeCenter, r);
  8830. r.vsub(xj, r);
  8831. const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  8832. edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction
  8833. // Find the third side orthogonal to this one
  8834. let l = 0;
  8835. while (l === j % 3 || l === k % 3) {
  8836. l++;
  8837. } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  8838. dist.copy(xi);
  8839. dist.vsub(orthogonal, dist);
  8840. dist.vsub(edgeCenter, dist);
  8841. dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it
  8842. const tdist = Math.abs(orthonorm);
  8843. const ndist = dist.length();
  8844. if (tdist < sides[l].length() && ndist < R) {
  8845. if (justTest) {
  8846. return true;
  8847. }
  8848. found = true;
  8849. const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8850. edgeCenter.vadd(orthogonal, res.rj); // box rj
  8851. res.rj.copy(res.rj);
  8852. dist.negate(res.ni);
  8853. res.ni.normalize();
  8854. res.ri.copy(res.rj);
  8855. res.ri.vadd(xj, res.ri);
  8856. res.ri.vsub(xi, res.ri);
  8857. res.ri.normalize();
  8858. res.ri.scale(R, res.ri); // Make relative to bodies
  8859. res.ri.vadd(xi, res.ri);
  8860. res.ri.vsub(bi.position, res.ri);
  8861. res.rj.vadd(xj, res.rj);
  8862. res.rj.vsub(bj.position, res.rj);
  8863. this.result.push(res);
  8864. this.createFrictionEquationsFromContact(res, this.frictionResult);
  8865. }
  8866. }
  8867. }
  8868. }
  8869. v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist);
  8870. }
  8871. planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8872. sj.convexPolyhedronRepresentation.material = sj.material;
  8873. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  8874. sj.convexPolyhedronRepresentation.id = sj.id;
  8875. return this.planeConvex(si, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8876. }
  8877. convexConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest, faceListA, faceListB) {
  8878. const sepAxis = convexConvex_sepAxis;
  8879. if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
  8880. return;
  8881. }
  8882. if (si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB)) {
  8883. const res = [];
  8884. const q = convexConvex_q;
  8885. si.clipAgainstHull(xi, qi, sj, xj, qj, sepAxis, -100, 100, res);
  8886. let numContacts = 0;
  8887. for (let j = 0; j !== res.length; j++) {
  8888. if (justTest) {
  8889. return true;
  8890. }
  8891. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8892. const ri = r.ri;
  8893. const rj = r.rj;
  8894. sepAxis.negate(r.ni);
  8895. res[j].normal.negate(q);
  8896. q.scale(res[j].depth, q);
  8897. res[j].point.vadd(q, ri);
  8898. rj.copy(res[j].point); // Contact points are in world coordinates. Transform back to relative
  8899. ri.vsub(xi, ri);
  8900. rj.vsub(xj, rj); // Make relative to bodies
  8901. ri.vadd(xi, ri);
  8902. ri.vsub(bi.position, ri);
  8903. rj.vadd(xj, rj);
  8904. rj.vsub(bj.position, rj);
  8905. this.result.push(r);
  8906. numContacts++;
  8907. if (!this.enableFrictionReduction) {
  8908. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8909. }
  8910. }
  8911. if (this.enableFrictionReduction && numContacts) {
  8912. this.createFrictionFromAverage(numContacts);
  8913. }
  8914. }
  8915. }
  8916. sphereConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8917. const v3pool = this.v3pool;
  8918. xi.vsub(xj, convex_to_sphere);
  8919. const normals = sj.faceNormals;
  8920. const faces = sj.faces;
  8921. const verts = sj.vertices;
  8922. const R = si.radius;
  8923. // return;
  8924. // }
  8925. let found = false; // Check corners
  8926. for (let i = 0; i !== verts.length; i++) {
  8927. const v = verts[i]; // World position of corner
  8928. const worldCorner = sphereConvex_worldCorner;
  8929. qj.vmult(v, worldCorner);
  8930. xj.vadd(worldCorner, worldCorner);
  8931. const sphere_to_corner = sphereConvex_sphereToCorner;
  8932. worldCorner.vsub(xi, sphere_to_corner);
  8933. if (sphere_to_corner.lengthSquared() < R * R) {
  8934. if (justTest) {
  8935. return true;
  8936. }
  8937. found = true;
  8938. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8939. r.ri.copy(sphere_to_corner);
  8940. r.ri.normalize();
  8941. r.ni.copy(r.ri);
  8942. r.ri.scale(R, r.ri);
  8943. worldCorner.vsub(xj, r.rj); // Should be relative to the body.
  8944. r.ri.vadd(xi, r.ri);
  8945. r.ri.vsub(bi.position, r.ri); // Should be relative to the body.
  8946. r.rj.vadd(xj, r.rj);
  8947. r.rj.vsub(bj.position, r.rj);
  8948. this.result.push(r);
  8949. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8950. return;
  8951. }
  8952. } // Check side (plane) intersections
  8953. for (let i = 0, nfaces = faces.length; i !== nfaces && found === false; i++) {
  8954. const normal = normals[i];
  8955. const face = faces[i]; // Get world-transformed normal of the face
  8956. const worldNormal = sphereConvex_worldNormal;
  8957. qj.vmult(normal, worldNormal); // Get a world vertex from the face
  8958. const worldPoint = sphereConvex_worldPoint;
  8959. qj.vmult(verts[face[0]], worldPoint);
  8960. worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal
  8961. const worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  8962. worldNormal.scale(-R, worldSpherePointClosestToPlane);
  8963. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere
  8964. const penetrationVec = sphereConvex_penetrationVec;
  8965. worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap.
  8966. const penetration = penetrationVec.dot(worldNormal);
  8967. const worldPointToSphere = sphereConvex_sphereToWorldPoint;
  8968. xi.vsub(worldPoint, worldPointToSphere);
  8969. if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) {
  8970. // Intersects plane. Now check if the sphere is inside the face polygon
  8971. const faceVerts = []; // Face vertices, in world coords
  8972. for (let j = 0, Nverts = face.length; j !== Nverts; j++) {
  8973. const worldVertex = v3pool.get();
  8974. qj.vmult(verts[face[j]], worldVertex);
  8975. xj.vadd(worldVertex, worldVertex);
  8976. faceVerts.push(worldVertex);
  8977. }
  8978. if (pointInPolygon(faceVerts, worldNormal, xi)) {
  8979. // Is the sphere center in the face polygon?
  8980. if (justTest) {
  8981. return true;
  8982. }
  8983. found = true;
  8984. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8985. worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact
  8986. worldNormal.negate(r.ni); // Normal pointing out of sphere
  8987. const penetrationVec2 = v3pool.get();
  8988. worldNormal.scale(-penetration, penetrationVec2);
  8989. const penetrationSpherePoint = v3pool.get();
  8990. worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  8991. xi.vsub(xj, r.rj);
  8992. r.rj.vadd(penetrationSpherePoint, r.rj);
  8993. r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body.
  8994. r.rj.vadd(xj, r.rj);
  8995. r.rj.vsub(bj.position, r.rj); // Should be relative to the body.
  8996. r.ri.vadd(xi, r.ri);
  8997. r.ri.vsub(bi.position, r.ri);
  8998. v3pool.release(penetrationVec2);
  8999. v3pool.release(penetrationSpherePoint);
  9000. this.result.push(r);
  9001. this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices
  9002. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9003. v3pool.release(faceVerts[j]);
  9004. }
  9005. return; // We only expect *one* face contact
  9006. } else {
  9007. // Edge?
  9008. for (let j = 0; j !== face.length; j++) {
  9009. // Get two world transformed vertices
  9010. const v1 = v3pool.get();
  9011. const v2 = v3pool.get();
  9012. qj.vmult(verts[face[(j + 1) % face.length]], v1);
  9013. qj.vmult(verts[face[(j + 2) % face.length]], v2);
  9014. xj.vadd(v1, v1);
  9015. xj.vadd(v2, v2); // Construct edge vector
  9016. const edge = sphereConvex_edge;
  9017. v2.vsub(v1, edge); // Construct the same vector, but normalized
  9018. const edgeUnit = sphereConvex_edgeUnit;
  9019. edge.unit(edgeUnit); // p is xi projected onto the edge
  9020. const p = v3pool.get();
  9021. const v1_to_xi = v3pool.get();
  9022. xi.vsub(v1, v1_to_xi);
  9023. const dot = v1_to_xi.dot(edgeUnit);
  9024. edgeUnit.scale(dot, p);
  9025. p.vadd(v1, p); // Compute a vector from p to the center of the sphere
  9026. const xi_to_p = v3pool.get();
  9027. p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius
  9028. // AND if p is in between v1 and v2
  9029. if (dot > 0 && dot * dot < edge.lengthSquared() && xi_to_p.lengthSquared() < R * R) {
  9030. // Collision if the edge-sphere distance is less than the radius
  9031. // Edge contact!
  9032. if (justTest) {
  9033. return true;
  9034. }
  9035. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9036. p.vsub(xj, r.rj);
  9037. p.vsub(xi, r.ni);
  9038. r.ni.normalize();
  9039. r.ni.scale(R, r.ri); // Should be relative to the body.
  9040. r.rj.vadd(xj, r.rj);
  9041. r.rj.vsub(bj.position, r.rj); // Should be relative to the body.
  9042. r.ri.vadd(xi, r.ri);
  9043. r.ri.vsub(bi.position, r.ri);
  9044. this.result.push(r);
  9045. this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices
  9046. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9047. v3pool.release(faceVerts[j]);
  9048. }
  9049. v3pool.release(v1);
  9050. v3pool.release(v2);
  9051. v3pool.release(p);
  9052. v3pool.release(xi_to_p);
  9053. v3pool.release(v1_to_xi);
  9054. return;
  9055. }
  9056. v3pool.release(v1);
  9057. v3pool.release(v2);
  9058. v3pool.release(p);
  9059. v3pool.release(xi_to_p);
  9060. v3pool.release(v1_to_xi);
  9061. }
  9062. } // Release world vertices
  9063. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9064. v3pool.release(faceVerts[j]);
  9065. }
  9066. }
  9067. }
  9068. }
  9069. planeConvex(planeShape, convexShape, planePosition, convexPosition, planeQuat, convexQuat, planeBody, convexBody, si, sj, justTest) {
  9070. // Simply return the points behind the plane.
  9071. const worldVertex = planeConvex_v;
  9072. const worldNormal = planeConvex_normal;
  9073. worldNormal.set(0, 0, 1);
  9074. planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation
  9075. let numContacts = 0;
  9076. const relpos = planeConvex_relpos;
  9077. for (let i = 0; i !== convexShape.vertices.length; i++) {
  9078. // Get world convex vertex
  9079. worldVertex.copy(convexShape.vertices[i]);
  9080. convexQuat.vmult(worldVertex, worldVertex);
  9081. convexPosition.vadd(worldVertex, worldVertex);
  9082. worldVertex.vsub(planePosition, relpos);
  9083. const dot = worldNormal.dot(relpos);
  9084. if (dot <= 0.0) {
  9085. if (justTest) {
  9086. return true;
  9087. }
  9088. const r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj); // Get vertex position projected on plane
  9089. const projected = planeConvex_projected;
  9090. worldNormal.scale(worldNormal.dot(relpos), projected);
  9091. worldVertex.vsub(projected, projected);
  9092. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  9093. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  9094. // rj is now just the vector from the convex center to the vertex
  9095. worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body
  9096. r.ri.vadd(planePosition, r.ri);
  9097. r.ri.vsub(planeBody.position, r.ri);
  9098. r.rj.vadd(convexPosition, r.rj);
  9099. r.rj.vsub(convexBody.position, r.rj);
  9100. this.result.push(r);
  9101. numContacts++;
  9102. if (!this.enableFrictionReduction) {
  9103. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9104. }
  9105. }
  9106. }
  9107. if (this.enableFrictionReduction && numContacts) {
  9108. this.createFrictionFromAverage(numContacts);
  9109. }
  9110. }
  9111. boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9112. si.convexPolyhedronRepresentation.material = si.material;
  9113. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9114. return this.convexConvex(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9115. }
  9116. sphereHeightfield(sphereShape, hfShape, spherePos, hfPos, sphereQuat, hfQuat, sphereBody, hfBody, rsi, rsj, justTest) {
  9117. const data = hfShape.data;
  9118. const radius = sphereShape.radius;
  9119. const w = hfShape.elementSize;
  9120. const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local!
  9121. const localSpherePos = sphereHeightfield_tmp1;
  9122. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against
  9123. let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1;
  9124. let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1;
  9125. let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1;
  9126. let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain
  9127. if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
  9128. return;
  9129. } // Clamp index to edges
  9130. if (iMinX < 0) {
  9131. iMinX = 0;
  9132. }
  9133. if (iMaxX < 0) {
  9134. iMaxX = 0;
  9135. }
  9136. if (iMinY < 0) {
  9137. iMinY = 0;
  9138. }
  9139. if (iMaxY < 0) {
  9140. iMaxY = 0;
  9141. }
  9142. if (iMinX >= data.length) {
  9143. iMinX = data.length - 1;
  9144. }
  9145. if (iMaxX >= data.length) {
  9146. iMaxX = data.length - 1;
  9147. }
  9148. if (iMaxY >= data[0].length) {
  9149. iMaxY = data[0].length - 1;
  9150. }
  9151. if (iMinY >= data[0].length) {
  9152. iMinY = data[0].length - 1;
  9153. }
  9154. const minMax = [];
  9155. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  9156. const min = minMax[0];
  9157. const max = minMax[1]; // Bail out if we can't touch the bounding height box
  9158. if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) {
  9159. return;
  9160. }
  9161. const result = this.result;
  9162. for (let i = iMinX; i < iMaxX; i++) {
  9163. for (let j = iMinY; j < iMaxY; j++) {
  9164. const numContactsBefore = result.length;
  9165. let intersecting = false; // Lower triangle
  9166. hfShape.getConvexTrianglePillar(i, j, false);
  9167. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9168. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  9169. intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
  9170. }
  9171. if (justTest && intersecting) {
  9172. return true;
  9173. } // Upper triangle
  9174. hfShape.getConvexTrianglePillar(i, j, true);
  9175. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9176. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  9177. intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
  9178. }
  9179. if (justTest && intersecting) {
  9180. return true;
  9181. }
  9182. const numContacts = result.length - numContactsBefore;
  9183. if (numContacts > 2) {
  9184. return;
  9185. }
  9186. /*
  9187. // Skip all but 1
  9188. for (let k = 0; k < numContacts - 1; k++) {
  9189. result.pop();
  9190. }
  9191. */
  9192. }
  9193. }
  9194. }
  9195. boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9196. si.convexPolyhedronRepresentation.material = si.material;
  9197. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9198. return this.convexHeightfield(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9199. }
  9200. convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest) {
  9201. const data = hfShape.data;
  9202. const w = hfShape.elementSize;
  9203. const radius = convexShape.boundingSphereRadius;
  9204. const worldPillarOffset = convexHeightfield_tmp2;
  9205. const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local!
  9206. const localConvexPos = convexHeightfield_tmp1;
  9207. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against
  9208. let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1;
  9209. let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1;
  9210. let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1;
  9211. let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain
  9212. if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
  9213. return;
  9214. } // Clamp index to edges
  9215. if (iMinX < 0) {
  9216. iMinX = 0;
  9217. }
  9218. if (iMaxX < 0) {
  9219. iMaxX = 0;
  9220. }
  9221. if (iMinY < 0) {
  9222. iMinY = 0;
  9223. }
  9224. if (iMaxY < 0) {
  9225. iMaxY = 0;
  9226. }
  9227. if (iMinX >= data.length) {
  9228. iMinX = data.length - 1;
  9229. }
  9230. if (iMaxX >= data.length) {
  9231. iMaxX = data.length - 1;
  9232. }
  9233. if (iMaxY >= data[0].length) {
  9234. iMaxY = data[0].length - 1;
  9235. }
  9236. if (iMinY >= data[0].length) {
  9237. iMinY = data[0].length - 1;
  9238. }
  9239. const minMax = [];
  9240. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  9241. const min = minMax[0];
  9242. const max = minMax[1]; // Bail out if we're cant touch the bounding height box
  9243. if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) {
  9244. return;
  9245. }
  9246. for (let i = iMinX; i < iMaxX; i++) {
  9247. for (let j = iMinY; j < iMaxY; j++) {
  9248. let intersecting = false; // Lower triangle
  9249. hfShape.getConvexTrianglePillar(i, j, false);
  9250. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9251. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  9252. intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
  9253. }
  9254. if (justTest && intersecting) {
  9255. return true;
  9256. } // Upper triangle
  9257. hfShape.getConvexTrianglePillar(i, j, true);
  9258. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9259. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  9260. intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
  9261. }
  9262. if (justTest && intersecting) {
  9263. return true;
  9264. }
  9265. }
  9266. }
  9267. }
  9268. sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9269. // The normal is the unit vector from sphere center to particle center
  9270. const normal = particleSphere_normal;
  9271. normal.set(0, 0, 1);
  9272. xi.vsub(xj, normal);
  9273. const lengthSquared = normal.lengthSquared();
  9274. if (lengthSquared <= sj.radius * sj.radius) {
  9275. if (justTest) {
  9276. return true;
  9277. }
  9278. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9279. normal.normalize();
  9280. r.rj.copy(normal);
  9281. r.rj.scale(sj.radius, r.rj);
  9282. r.ni.copy(normal); // Contact normal
  9283. r.ni.negate(r.ni);
  9284. r.ri.set(0, 0, 0); // Center of particle
  9285. this.result.push(r);
  9286. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9287. }
  9288. }
  9289. planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9290. const normal = particlePlane_normal;
  9291. normal.set(0, 0, 1);
  9292. bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation
  9293. const relpos = particlePlane_relpos;
  9294. xi.vsub(bj.position, relpos);
  9295. const dot = normal.dot(relpos);
  9296. if (dot <= 0.0) {
  9297. if (justTest) {
  9298. return true;
  9299. }
  9300. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9301. r.ni.copy(normal); // Contact normal is the plane normal
  9302. r.ni.negate(r.ni);
  9303. r.ri.set(0, 0, 0); // Center of particle
  9304. // Get particle position projected on plane
  9305. const projected = particlePlane_projected;
  9306. normal.scale(normal.dot(xi), projected);
  9307. xi.vsub(projected, projected); //projected.vadd(bj.position,projected);
  9308. // rj is now the projected world position minus plane position
  9309. r.rj.copy(projected);
  9310. this.result.push(r);
  9311. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9312. }
  9313. }
  9314. boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9315. si.convexPolyhedronRepresentation.material = si.material;
  9316. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9317. return this.convexParticle(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9318. }
  9319. convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9320. let penetratedFaceIndex = -1;
  9321. const penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  9322. const worldPenetrationVec = convexParticle_worldPenetrationVec;
  9323. let minPenetration = null;
  9324. const local = convexParticle_local;
  9325. local.copy(xi);
  9326. local.vsub(xj, local); // Convert position to relative the convex origin
  9327. qj.conjugate(cqj);
  9328. cqj.vmult(local, local);
  9329. if (sj.pointIsInside(local)) {
  9330. if (sj.worldVerticesNeedsUpdate) {
  9331. sj.computeWorldVertices(xj, qj);
  9332. }
  9333. if (sj.worldFaceNormalsNeedsUpdate) {
  9334. sj.computeWorldFaceNormals(qj);
  9335. } // For each world polygon in the polyhedra
  9336. for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) {
  9337. // Construct world face vertices
  9338. const verts = [sj.worldVertices[sj.faces[i][0]]];
  9339. const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane.
  9340. xi.vsub(verts[0], convexParticle_vertexToParticle);
  9341. const penetration = -normal.dot(convexParticle_vertexToParticle);
  9342. if (minPenetration === null || Math.abs(penetration) < Math.abs(minPenetration)) {
  9343. if (justTest) {
  9344. return true;
  9345. }
  9346. minPenetration = penetration;
  9347. penetratedFaceIndex = i;
  9348. penetratedFaceNormal.copy(normal);
  9349. }
  9350. }
  9351. if (penetratedFaceIndex !== -1) {
  9352. // Setup contact
  9353. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9354. penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face
  9355. worldPenetrationVec.vadd(xi, worldPenetrationVec);
  9356. worldPenetrationVec.vsub(xj, worldPenetrationVec);
  9357. r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  9358. //projectedToFace.copy(r.rj);
  9359. //qj.vmult(r.rj,r.rj);
  9360. penetratedFaceNormal.negate(r.ni); // Contact normal
  9361. r.ri.set(0, 0, 0); // Center of particle
  9362. const ri = r.ri;
  9363. const rj = r.rj; // Make relative to bodies
  9364. ri.vadd(xi, ri);
  9365. ri.vsub(bi.position, ri);
  9366. rj.vadd(xj, rj);
  9367. rj.vsub(bj.position, rj);
  9368. this.result.push(r);
  9369. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9370. } else {
  9371. console.warn('Point found inside convex, but did not find penetrating face!');
  9372. }
  9373. }
  9374. }
  9375. heightfieldCylinder(hfShape, convexShape, hfPos, convexPos, hfQuat, convexQuat, hfBody, convexBody, rsi, rsj, justTest) {
  9376. return this.convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest);
  9377. }
  9378. particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9379. return this.convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest);
  9380. }
  9381. sphereTrimesh(sphereShape, trimeshShape, spherePos, trimeshPos, sphereQuat, trimeshQuat, sphereBody, trimeshBody, rsi, rsj, justTest) {
  9382. const edgeVertexA = sphereTrimesh_edgeVertexA;
  9383. const edgeVertexB = sphereTrimesh_edgeVertexB;
  9384. const edgeVector = sphereTrimesh_edgeVector;
  9385. const edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  9386. const localSpherePos = sphereTrimesh_localSpherePos;
  9387. const tmp = sphereTrimesh_tmp;
  9388. const localSphereAABB = sphereTrimesh_localSphereAABB;
  9389. const v2 = sphereTrimesh_v2;
  9390. const relpos = sphereTrimesh_relpos;
  9391. const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh
  9392. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos); // Get the aabb of the sphere locally in the trimesh
  9393. const sphereRadius = sphereShape.radius;
  9394. localSphereAABB.lowerBound.set(localSpherePos.x - sphereRadius, localSpherePos.y - sphereRadius, localSpherePos.z - sphereRadius);
  9395. localSphereAABB.upperBound.set(localSpherePos.x + sphereRadius, localSpherePos.y + sphereRadius, localSpherePos.z + sphereRadius);
  9396. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  9397. // Vertices
  9398. const v = sphereTrimesh_v;
  9399. const radiusSquared = sphereShape.radius * sphereShape.radius;
  9400. for (let i = 0; i < triangles.length; i++) {
  9401. for (let j = 0; j < 3; j++) {
  9402. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere
  9403. v.vsub(localSpherePos, relpos);
  9404. if (relpos.lengthSquared() <= radiusSquared) {
  9405. // Safe up
  9406. v2.copy(v);
  9407. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  9408. v.vsub(spherePos, relpos);
  9409. if (justTest) {
  9410. return true;
  9411. }
  9412. let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9413. r.ni.copy(relpos);
  9414. r.ni.normalize(); // ri is the vector from sphere center to the sphere surface
  9415. r.ri.copy(r.ni);
  9416. r.ri.scale(sphereShape.radius, r.ri);
  9417. r.ri.vadd(spherePos, r.ri);
  9418. r.ri.vsub(sphereBody.position, r.ri);
  9419. r.rj.copy(v);
  9420. r.rj.vsub(trimeshBody.position, r.rj); // Store result
  9421. this.result.push(r);
  9422. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9423. }
  9424. }
  9425. } // Check all edges
  9426. for (let i = 0; i < triangles.length; i++) {
  9427. for (let j = 0; j < 3; j++) {
  9428. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  9429. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + (j + 1) % 3], edgeVertexB);
  9430. edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge
  9431. localSpherePos.vsub(edgeVertexB, tmp);
  9432. const positionAlongEdgeB = tmp.dot(edgeVector);
  9433. localSpherePos.vsub(edgeVertexA, tmp);
  9434. let positionAlongEdgeA = tmp.dot(edgeVector);
  9435. if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) {
  9436. // Now check the orthogonal distance from edge to sphere center
  9437. localSpherePos.vsub(edgeVertexA, tmp);
  9438. edgeVectorUnit.copy(edgeVector);
  9439. edgeVectorUnit.normalize();
  9440. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  9441. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  9442. tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  9443. const dist = tmp.distanceTo(localSpherePos);
  9444. if (dist < sphereShape.radius) {
  9445. if (justTest) {
  9446. return true;
  9447. }
  9448. const r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9449. tmp.vsub(localSpherePos, r.ni);
  9450. r.ni.normalize();
  9451. r.ni.scale(sphereShape.radius, r.ri);
  9452. r.ri.vadd(spherePos, r.ri);
  9453. r.ri.vsub(sphereBody.position, r.ri);
  9454. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  9455. tmp.vsub(trimeshBody.position, r.rj);
  9456. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  9457. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  9458. this.result.push(r);
  9459. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9460. }
  9461. }
  9462. }
  9463. } // Triangle faces
  9464. const va = sphereTrimesh_va;
  9465. const vb = sphereTrimesh_vb;
  9466. const vc = sphereTrimesh_vc;
  9467. const normal = sphereTrimesh_normal;
  9468. for (let i = 0, N = triangles.length; i !== N; i++) {
  9469. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  9470. trimeshShape.getNormal(triangles[i], normal);
  9471. localSpherePos.vsub(va, tmp);
  9472. let dist = tmp.dot(normal);
  9473. normal.scale(dist, tmp);
  9474. localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane
  9475. dist = tmp.distanceTo(localSpherePos);
  9476. if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) {
  9477. if (justTest) {
  9478. return true;
  9479. }
  9480. let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9481. tmp.vsub(localSpherePos, r.ni);
  9482. r.ni.normalize();
  9483. r.ni.scale(sphereShape.radius, r.ri);
  9484. r.ri.vadd(spherePos, r.ri);
  9485. r.ri.vsub(sphereBody.position, r.ri);
  9486. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  9487. tmp.vsub(trimeshBody.position, r.rj);
  9488. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  9489. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  9490. this.result.push(r);
  9491. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9492. }
  9493. }
  9494. triangles.length = 0;
  9495. }
  9496. planeTrimesh(planeShape, trimeshShape, planePos, trimeshPos, planeQuat, trimeshQuat, planeBody, trimeshBody, rsi, rsj, justTest) {
  9497. // Make contacts!
  9498. const v = new Vec3();
  9499. const normal = planeTrimesh_normal;
  9500. normal.set(0, 0, 1);
  9501. planeQuat.vmult(normal, normal); // Turn normal according to plane
  9502. for (let i = 0; i < trimeshShape.vertices.length / 3; i++) {
  9503. // Get world vertex from trimesh
  9504. trimeshShape.getVertex(i, v); // Safe up
  9505. const v2 = new Vec3();
  9506. v2.copy(v);
  9507. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side
  9508. const relpos = planeTrimesh_relpos;
  9509. v.vsub(planePos, relpos);
  9510. const dot = normal.dot(relpos);
  9511. if (dot <= 0.0) {
  9512. if (justTest) {
  9513. return true;
  9514. }
  9515. const r = this.createContactEquation(planeBody, trimeshBody, planeShape, trimeshShape, rsi, rsj);
  9516. r.ni.copy(normal); // Contact normal is the plane normal
  9517. // Get vertex position projected on plane
  9518. const projected = planeTrimesh_projected;
  9519. normal.scale(relpos.dot(normal), projected);
  9520. v.vsub(projected, projected); // ri is the projected world position minus plane position
  9521. r.ri.copy(projected);
  9522. r.ri.vsub(planeBody.position, r.ri);
  9523. r.rj.copy(v);
  9524. r.rj.vsub(trimeshBody.position, r.rj); // Store result
  9525. this.result.push(r);
  9526. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9527. }
  9528. }
  9529. } // convexTrimesh(
  9530. // si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion,
  9531. // bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null,
  9532. // faceListA?: number[] | null, faceListB?: number[] | null,
  9533. // ) {
  9534. // const sepAxis = convexConvex_sepAxis;
  9535. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  9536. // return;
  9537. // }
  9538. // // Construct a temp hull for each triangle
  9539. // const hullB = new ConvexPolyhedron();
  9540. // hullB.faces = [[0,1,2]];
  9541. // const va = new Vec3();
  9542. // const vb = new Vec3();
  9543. // const vc = new Vec3();
  9544. // hullB.vertices = [
  9545. // va,
  9546. // vb,
  9547. // vc
  9548. // ];
  9549. // for (let i = 0; i < sj.indices.length / 3; i++) {
  9550. // const triangleNormal = new Vec3();
  9551. // sj.getNormal(i, triangleNormal);
  9552. // hullB.faceNormals = [triangleNormal];
  9553. // sj.getTriangleVertices(i, va, vb, vc);
  9554. // let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  9555. // if(!d){
  9556. // triangleNormal.scale(-1, triangleNormal);
  9557. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  9558. // if(!d){
  9559. // continue;
  9560. // }
  9561. // }
  9562. // const res: ConvexPolyhedronContactPoint[] = [];
  9563. // const q = convexConvex_q;
  9564. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  9565. // for(let j = 0; j !== res.length; j++){
  9566. // const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  9567. // ri = r.ri,
  9568. // rj = r.rj;
  9569. // r.ni.copy(triangleNormal);
  9570. // r.ni.negate(r.ni);
  9571. // res[j].normal.negate(q);
  9572. // q.mult(res[j].depth, q);
  9573. // res[j].point.vadd(q, ri);
  9574. // rj.copy(res[j].point);
  9575. // // Contact points are in world coordinates. Transform back to relative
  9576. // ri.vsub(xi,ri);
  9577. // rj.vsub(xj,rj);
  9578. // // Make relative to bodies
  9579. // ri.vadd(xi, ri);
  9580. // ri.vsub(bi.position, ri);
  9581. // rj.vadd(xj, rj);
  9582. // rj.vsub(bj.position, rj);
  9583. // result.push(r);
  9584. // }
  9585. // }
  9586. // }
  9587. }
  9588. const averageNormal = new Vec3();
  9589. const averageContactPointA = new Vec3();
  9590. const averageContactPointB = new Vec3();
  9591. const tmpVec1 = new Vec3();
  9592. const tmpVec2 = new Vec3();
  9593. const tmpQuat1 = new Quaternion();
  9594. const tmpQuat2 = new Quaternion();
  9595. const planeTrimesh_normal = new Vec3();
  9596. const planeTrimesh_relpos = new Vec3();
  9597. const planeTrimesh_projected = new Vec3();
  9598. const sphereTrimesh_normal = new Vec3();
  9599. const sphereTrimesh_relpos = new Vec3();
  9600. new Vec3();
  9601. const sphereTrimesh_v = new Vec3();
  9602. const sphereTrimesh_v2 = new Vec3();
  9603. const sphereTrimesh_edgeVertexA = new Vec3();
  9604. const sphereTrimesh_edgeVertexB = new Vec3();
  9605. const sphereTrimesh_edgeVector = new Vec3();
  9606. const sphereTrimesh_edgeVectorUnit = new Vec3();
  9607. const sphereTrimesh_localSpherePos = new Vec3();
  9608. const sphereTrimesh_tmp = new Vec3();
  9609. const sphereTrimesh_va = new Vec3();
  9610. const sphereTrimesh_vb = new Vec3();
  9611. const sphereTrimesh_vc = new Vec3();
  9612. const sphereTrimesh_localSphereAABB = new AABB();
  9613. const sphereTrimesh_triangles = [];
  9614. const point_on_plane_to_sphere = new Vec3();
  9615. const plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  9616. const pointInPolygon_edge = new Vec3();
  9617. const pointInPolygon_edge_x_normal = new Vec3();
  9618. const pointInPolygon_vtp = new Vec3();
  9619. function pointInPolygon(verts, normal, p) {
  9620. let positiveResult = null;
  9621. const N = verts.length;
  9622. for (let i = 0; i !== N; i++) {
  9623. const v = verts[i]; // Get edge to the next vertex
  9624. const edge = pointInPolygon_edge;
  9625. verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge
  9626. const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3();
  9627. edge.cross(normal, edge_x_normal); // Get vector between point and current vertex
  9628. const vertex_to_p = pointInPolygon_vtp;
  9629. p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is
  9630. const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon.
  9631. if (positiveResult === null || r > 0 && positiveResult === true || r <= 0 && positiveResult === false) {
  9632. if (positiveResult === null) {
  9633. positiveResult = r > 0;
  9634. }
  9635. continue;
  9636. } else {
  9637. return false; // Encountered some other sign. Exit.
  9638. }
  9639. } // If we got here, all dot products were of the same sign.
  9640. return true;
  9641. }
  9642. const box_to_sphere = new Vec3();
  9643. const sphereBox_ns = new Vec3();
  9644. const sphereBox_ns1 = new Vec3();
  9645. const sphereBox_ns2 = new Vec3();
  9646. const sphereBox_sides = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  9647. const sphereBox_sphere_to_corner = new Vec3();
  9648. const sphereBox_side_ns = new Vec3();
  9649. const sphereBox_side_ns1 = new Vec3();
  9650. const sphereBox_side_ns2 = new Vec3();
  9651. const convex_to_sphere = new Vec3();
  9652. const sphereConvex_edge = new Vec3();
  9653. const sphereConvex_edgeUnit = new Vec3();
  9654. const sphereConvex_sphereToCorner = new Vec3();
  9655. const sphereConvex_worldCorner = new Vec3();
  9656. const sphereConvex_worldNormal = new Vec3();
  9657. const sphereConvex_worldPoint = new Vec3();
  9658. const sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  9659. const sphereConvex_penetrationVec = new Vec3();
  9660. const sphereConvex_sphereToWorldPoint = new Vec3();
  9661. new Vec3();
  9662. new Vec3();
  9663. const planeConvex_v = new Vec3();
  9664. const planeConvex_normal = new Vec3();
  9665. const planeConvex_relpos = new Vec3();
  9666. const planeConvex_projected = new Vec3();
  9667. const convexConvex_sepAxis = new Vec3();
  9668. const convexConvex_q = new Vec3();
  9669. const particlePlane_normal = new Vec3();
  9670. const particlePlane_relpos = new Vec3();
  9671. const particlePlane_projected = new Vec3();
  9672. const particleSphere_normal = new Vec3(); // WIP
  9673. const cqj = new Quaternion();
  9674. const convexParticle_local = new Vec3();
  9675. new Vec3();
  9676. const convexParticle_penetratedFaceNormal = new Vec3();
  9677. const convexParticle_vertexToParticle = new Vec3();
  9678. const convexParticle_worldPenetrationVec = new Vec3();
  9679. const convexHeightfield_tmp1 = new Vec3();
  9680. const convexHeightfield_tmp2 = new Vec3();
  9681. const convexHeightfield_faceList = [0];
  9682. const sphereHeightfield_tmp1 = new Vec3();
  9683. const sphereHeightfield_tmp2 = new Vec3();
  9684. class OverlapKeeper {
  9685. /**
  9686. * @todo Remove useless constructor
  9687. */
  9688. constructor() {
  9689. this.current = [];
  9690. this.previous = [];
  9691. }
  9692. /**
  9693. * getKey
  9694. */
  9695. getKey(i, j) {
  9696. if (j < i) {
  9697. const temp = j;
  9698. j = i;
  9699. i = temp;
  9700. }
  9701. return i << 16 | j;
  9702. }
  9703. /**
  9704. * set
  9705. */
  9706. set(i, j) {
  9707. // Insertion sort. This way the diff will have linear complexity.
  9708. const key = this.getKey(i, j);
  9709. const current = this.current;
  9710. let index = 0;
  9711. while (key > current[index]) {
  9712. index++;
  9713. }
  9714. if (key === current[index]) {
  9715. return; // Pair was already added
  9716. }
  9717. for (let j = current.length - 1; j >= index; j--) {
  9718. current[j + 1] = current[j];
  9719. }
  9720. current[index] = key;
  9721. }
  9722. /**
  9723. * tick
  9724. */
  9725. tick() {
  9726. const tmp = this.current;
  9727. this.current = this.previous;
  9728. this.previous = tmp;
  9729. this.current.length = 0;
  9730. }
  9731. /**
  9732. * getDiff
  9733. */
  9734. getDiff(additions, removals) {
  9735. const a = this.current;
  9736. const b = this.previous;
  9737. const al = a.length;
  9738. const bl = b.length;
  9739. let j = 0;
  9740. for (let i = 0; i < al; i++) {
  9741. let found = false;
  9742. const keyA = a[i];
  9743. while (keyA > b[j]) {
  9744. j++;
  9745. }
  9746. found = keyA === b[j];
  9747. if (!found) {
  9748. unpackAndPush(additions, keyA);
  9749. }
  9750. }
  9751. j = 0;
  9752. for (let i = 0; i < bl; i++) {
  9753. let found = false;
  9754. const keyB = b[i];
  9755. while (keyB > a[j]) {
  9756. j++;
  9757. }
  9758. found = a[j] === keyB;
  9759. if (!found) {
  9760. unpackAndPush(removals, keyB);
  9761. }
  9762. }
  9763. }
  9764. }
  9765. function unpackAndPush(array, key) {
  9766. array.push((key & 0xffff0000) >> 16, key & 0x0000ffff);
  9767. }
  9768. const getKey = (i, j) => i < j ? `${i}-${j}` : `${j}-${i}`;
  9769. /**
  9770. * TupleDictionary
  9771. */
  9772. class TupleDictionary {
  9773. constructor() {
  9774. this.data = {
  9775. keys: []
  9776. };
  9777. }
  9778. /** get */
  9779. get(i, j) {
  9780. const key = getKey(i, j);
  9781. return this.data[key];
  9782. }
  9783. /** set */
  9784. set(i, j, value) {
  9785. const key = getKey(i, j); // Check if key already exists
  9786. if (!this.get(i, j)) {
  9787. this.data.keys.push(key);
  9788. }
  9789. this.data[key] = value;
  9790. }
  9791. /** delete */
  9792. delete(i, j) {
  9793. const key = getKey(i, j);
  9794. const index = this.data.keys.indexOf(key);
  9795. if (index !== -1) {
  9796. this.data.keys.splice(index, 1);
  9797. }
  9798. delete this.data[key];
  9799. }
  9800. /** reset */
  9801. reset() {
  9802. const data = this.data;
  9803. const keys = data.keys;
  9804. while (keys.length > 0) {
  9805. const key = keys.pop();
  9806. delete data[key];
  9807. }
  9808. }
  9809. }
  9810. /**
  9811. * The physics world
  9812. */
  9813. class World extends EventTarget {
  9814. /**
  9815. * 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.
  9816. */
  9817. /**
  9818. * Makes bodies go to sleep when they've been inactive.
  9819. * @default false
  9820. */
  9821. /**
  9822. * All the current contacts (instances of ContactEquation) in the world.
  9823. */
  9824. /**
  9825. * 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).
  9826. * @default 0
  9827. */
  9828. /**
  9829. * Set to true to use fast quaternion normalization. It is often enough accurate to use.
  9830. * If bodies tend to explode, set to false.
  9831. * @default false
  9832. */
  9833. /**
  9834. * The wall-clock time since simulation start.
  9835. */
  9836. /**
  9837. * Number of timesteps taken since start.
  9838. */
  9839. /**
  9840. * Default and last timestep sizes.
  9841. */
  9842. /**
  9843. * The gravity of the world.
  9844. */
  9845. /**
  9846. * Gravity to use when approximating the friction max force (mu*mass*gravity).
  9847. * If undefined, global gravity will be used.
  9848. * Use to enable friction in a World with a null gravity vector (no gravity).
  9849. */
  9850. /**
  9851. * The broadphase algorithm to use.
  9852. * @default NaiveBroadphase
  9853. */
  9854. /**
  9855. * All bodies in this world
  9856. */
  9857. /**
  9858. * True if any bodies are not sleeping, false if every body is sleeping.
  9859. */
  9860. /**
  9861. * The solver algorithm to use.
  9862. * @default GSSolver
  9863. */
  9864. /**
  9865. * collisionMatrix
  9866. */
  9867. /**
  9868. * CollisionMatrix from the previous step.
  9869. */
  9870. /**
  9871. * All added contactmaterials.
  9872. */
  9873. /**
  9874. * Used to look up a ContactMaterial given two instances of Material.
  9875. */
  9876. /**
  9877. * The default material of the bodies.
  9878. */
  9879. /**
  9880. * This contact material is used if no suitable contactmaterial is found for a contact.
  9881. */
  9882. /**
  9883. * Time accumulator for interpolation.
  9884. * @see https://gafferongames.com/game-physics/fix-your-timestep/
  9885. */
  9886. /**
  9887. * Dispatched after a body has been added to the world.
  9888. */
  9889. /**
  9890. * Dispatched after a body has been removed from the world.
  9891. */
  9892. constructor(options) {
  9893. if (options === void 0) {
  9894. options = {};
  9895. }
  9896. super();
  9897. this.dt = -1;
  9898. this.allowSleep = !!options.allowSleep;
  9899. this.contacts = [];
  9900. this.frictionEquations = [];
  9901. this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;
  9902. this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;
  9903. this.time = 0.0;
  9904. this.stepnumber = 0;
  9905. this.default_dt = 1 / 60;
  9906. this.nextId = 0;
  9907. this.gravity = new Vec3();
  9908. if (options.gravity) {
  9909. this.gravity.copy(options.gravity);
  9910. }
  9911. if (options.frictionGravity) {
  9912. this.frictionGravity = new Vec3();
  9913. this.frictionGravity.copy(options.frictionGravity);
  9914. }
  9915. this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();
  9916. this.bodies = [];
  9917. this.hasActiveBodies = false;
  9918. this.solver = options.solver !== undefined ? options.solver : new GSSolver();
  9919. this.constraints = [];
  9920. this.narrowphase = new Narrowphase(this);
  9921. this.collisionMatrix = new ArrayCollisionMatrix();
  9922. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  9923. this.bodyOverlapKeeper = new OverlapKeeper();
  9924. this.shapeOverlapKeeper = new OverlapKeeper();
  9925. this.contactmaterials = [];
  9926. this.contactMaterialTable = new TupleDictionary();
  9927. this.defaultMaterial = new Material('default');
  9928. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, {
  9929. friction: 0.3,
  9930. restitution: 0.0
  9931. });
  9932. this.doProfiling = false;
  9933. this.profile = {
  9934. solve: 0,
  9935. makeContactConstraints: 0,
  9936. broadphase: 0,
  9937. integrate: 0,
  9938. narrowphase: 0
  9939. };
  9940. this.accumulator = 0;
  9941. this.subsystems = [];
  9942. this.addBodyEvent = {
  9943. type: 'addBody',
  9944. body: null
  9945. };
  9946. this.removeBodyEvent = {
  9947. type: 'removeBody',
  9948. body: null
  9949. };
  9950. this.idToBodyMap = {};
  9951. this.broadphase.setWorld(this);
  9952. }
  9953. /**
  9954. * Get the contact material between materials m1 and m2
  9955. * @return The contact material if it was found.
  9956. */
  9957. getContactMaterial(m1, m2) {
  9958. return this.contactMaterialTable.get(m1.id, m2.id);
  9959. }
  9960. /**
  9961. * Store old collision state info
  9962. */
  9963. collisionMatrixTick() {
  9964. const temp = this.collisionMatrixPrevious;
  9965. this.collisionMatrixPrevious = this.collisionMatrix;
  9966. this.collisionMatrix = temp;
  9967. this.collisionMatrix.reset();
  9968. this.bodyOverlapKeeper.tick();
  9969. this.shapeOverlapKeeper.tick();
  9970. }
  9971. /**
  9972. * Add a constraint to the simulation.
  9973. */
  9974. addConstraint(c) {
  9975. this.constraints.push(c);
  9976. }
  9977. /**
  9978. * Removes a constraint
  9979. */
  9980. removeConstraint(c) {
  9981. const idx = this.constraints.indexOf(c);
  9982. if (idx !== -1) {
  9983. this.constraints.splice(idx, 1);
  9984. }
  9985. }
  9986. /**
  9987. * Raycast test
  9988. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  9989. */
  9990. rayTest(from, to, result) {
  9991. if (result instanceof RaycastResult) {
  9992. // Do raycastClosest
  9993. this.raycastClosest(from, to, {
  9994. skipBackfaces: true
  9995. }, result);
  9996. } else {
  9997. // Do raycastAll
  9998. this.raycastAll(from, to, {
  9999. skipBackfaces: true
  10000. }, result);
  10001. }
  10002. }
  10003. /**
  10004. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  10005. * @return True if any body was hit.
  10006. */
  10007. raycastAll(from, to, options, callback) {
  10008. if (options === void 0) {
  10009. options = {};
  10010. }
  10011. options.mode = Ray.ALL;
  10012. options.from = from;
  10013. options.to = to;
  10014. options.callback = callback;
  10015. return tmpRay.intersectWorld(this, options);
  10016. }
  10017. /**
  10018. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  10019. * @return True if any body was hit.
  10020. */
  10021. raycastAny(from, to, options, result) {
  10022. if (options === void 0) {
  10023. options = {};
  10024. }
  10025. options.mode = Ray.ANY;
  10026. options.from = from;
  10027. options.to = to;
  10028. options.result = result;
  10029. return tmpRay.intersectWorld(this, options);
  10030. }
  10031. /**
  10032. * Ray cast, and return information of the closest hit.
  10033. * @return True if any body was hit.
  10034. */
  10035. raycastClosest(from, to, options, result) {
  10036. if (options === void 0) {
  10037. options = {};
  10038. }
  10039. options.mode = Ray.CLOSEST;
  10040. options.from = from;
  10041. options.to = to;
  10042. options.result = result;
  10043. return tmpRay.intersectWorld(this, options);
  10044. }
  10045. /**
  10046. * Add a rigid body to the simulation.
  10047. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  10048. * @todo Adding an array of bodies should be possible. This would save some loops too
  10049. */
  10050. addBody(body) {
  10051. if (this.bodies.includes(body)) {
  10052. return;
  10053. }
  10054. body.index = this.bodies.length;
  10055. this.bodies.push(body);
  10056. body.world = this;
  10057. body.initPosition.copy(body.position);
  10058. body.initVelocity.copy(body.velocity);
  10059. body.timeLastSleepy = this.time;
  10060. if (body instanceof Body) {
  10061. body.initAngularVelocity.copy(body.angularVelocity);
  10062. body.initQuaternion.copy(body.quaternion);
  10063. }
  10064. this.collisionMatrix.setNumObjects(this.bodies.length);
  10065. this.addBodyEvent.body = body;
  10066. this.idToBodyMap[body.id] = body;
  10067. this.dispatchEvent(this.addBodyEvent);
  10068. }
  10069. /**
  10070. * Remove a rigid body from the simulation.
  10071. */
  10072. removeBody(body) {
  10073. body.world = null;
  10074. const n = this.bodies.length - 1;
  10075. const bodies = this.bodies;
  10076. const idx = bodies.indexOf(body);
  10077. if (idx !== -1) {
  10078. bodies.splice(idx, 1); // Todo: should use a garbage free method
  10079. // Recompute index
  10080. for (let i = 0; i !== bodies.length; i++) {
  10081. bodies[i].index = i;
  10082. }
  10083. this.collisionMatrix.setNumObjects(n);
  10084. this.removeBodyEvent.body = body;
  10085. delete this.idToBodyMap[body.id];
  10086. this.dispatchEvent(this.removeBodyEvent);
  10087. }
  10088. }
  10089. getBodyById(id) {
  10090. return this.idToBodyMap[id];
  10091. }
  10092. /**
  10093. * @todo Make a faster map
  10094. */
  10095. getShapeById(id) {
  10096. const bodies = this.bodies;
  10097. for (let i = 0; i < bodies.length; i++) {
  10098. const shapes = bodies[i].shapes;
  10099. for (let j = 0; j < shapes.length; j++) {
  10100. const shape = shapes[j];
  10101. if (shape.id === id) {
  10102. return shape;
  10103. }
  10104. }
  10105. }
  10106. return null;
  10107. }
  10108. /**
  10109. * Adds a contact material to the World
  10110. */
  10111. addContactMaterial(cmat) {
  10112. // Add contact material
  10113. this.contactmaterials.push(cmat); // Add current contact material to the material table
  10114. this.contactMaterialTable.set(cmat.materials[0].id, cmat.materials[1].id, cmat);
  10115. }
  10116. /**
  10117. * Removes a contact material from the World.
  10118. */
  10119. removeContactMaterial(cmat) {
  10120. const idx = this.contactmaterials.indexOf(cmat);
  10121. if (idx === -1) {
  10122. return;
  10123. }
  10124. this.contactmaterials.splice(idx, 1);
  10125. this.contactMaterialTable.delete(cmat.materials[0].id, cmat.materials[1].id);
  10126. }
  10127. /**
  10128. * Step the simulation forward keeping track of last called time
  10129. * to be able to step the world at a fixed rate, independently of framerate.
  10130. *
  10131. * @param dt The fixed time step size to use (default: 1 / 60).
  10132. * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).
  10133. * @see https://gafferongames.com/post/fix_your_timestep/
  10134. * @example
  10135. * // Run the simulation independently of framerate every 1 / 60 ms
  10136. * world.fixedStep()
  10137. */
  10138. fixedStep(dt, maxSubSteps) {
  10139. if (dt === void 0) {
  10140. dt = 1 / 60;
  10141. }
  10142. if (maxSubSteps === void 0) {
  10143. maxSubSteps = 10;
  10144. }
  10145. const time = performance.now() / 1000; // seconds
  10146. if (!this.lastCallTime) {
  10147. this.step(dt, undefined, maxSubSteps);
  10148. } else {
  10149. const timeSinceLastCalled = time - this.lastCallTime;
  10150. this.step(dt, timeSinceLastCalled, maxSubSteps);
  10151. }
  10152. this.lastCallTime = time;
  10153. }
  10154. /**
  10155. * Step the physics world forward in time.
  10156. *
  10157. * 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.
  10158. *
  10159. * @param dt The fixed time step size to use.
  10160. * @param timeSinceLastCalled The time elapsed since the function was last called.
  10161. * @param maxSubSteps Maximum number of fixed steps to take per function call (default: 10).
  10162. * @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
  10163. * @example
  10164. * // fixed timestepping without interpolation
  10165. * world.step(1 / 60)
  10166. */
  10167. step(dt, timeSinceLastCalled, maxSubSteps) {
  10168. if (maxSubSteps === void 0) {
  10169. maxSubSteps = 10;
  10170. }
  10171. if (timeSinceLastCalled === undefined) {
  10172. // Fixed, simple stepping
  10173. this.internalStep(dt); // Increment time
  10174. this.time += dt;
  10175. } else {
  10176. this.accumulator += timeSinceLastCalled;
  10177. const t0 = performance.now();
  10178. let substeps = 0;
  10179. while (this.accumulator >= dt && substeps < maxSubSteps) {
  10180. // Do fixed steps to catch up
  10181. this.internalStep(dt);
  10182. this.accumulator -= dt;
  10183. substeps++;
  10184. if (performance.now() - t0 > dt * 1000) {
  10185. // The framerate is not interactive anymore.
  10186. // We are below the target framerate.
  10187. // Better bail out.
  10188. break;
  10189. }
  10190. } // Remove the excess accumulator, since we may not
  10191. // have had enough substeps available to catch up
  10192. this.accumulator = this.accumulator % dt;
  10193. const t = this.accumulator / dt;
  10194. for (let j = 0; j !== this.bodies.length; j++) {
  10195. const b = this.bodies[j];
  10196. b.previousPosition.lerp(b.position, t, b.interpolatedPosition);
  10197. b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);
  10198. b.previousQuaternion.normalize();
  10199. }
  10200. this.time += timeSinceLastCalled;
  10201. }
  10202. }
  10203. internalStep(dt) {
  10204. this.dt = dt;
  10205. const contacts = this.contacts;
  10206. const p1 = World_step_p1;
  10207. const p2 = World_step_p2;
  10208. const N = this.bodies.length;
  10209. const bodies = this.bodies;
  10210. const solver = this.solver;
  10211. const gravity = this.gravity;
  10212. const doProfiling = this.doProfiling;
  10213. const profile = this.profile;
  10214. const DYNAMIC = Body.DYNAMIC;
  10215. let profilingStart = -Infinity;
  10216. const constraints = this.constraints;
  10217. const frictionEquationPool = World_step_frictionEquationPool;
  10218. gravity.length();
  10219. const gx = gravity.x;
  10220. const gy = gravity.y;
  10221. const gz = gravity.z;
  10222. let i = 0;
  10223. if (doProfiling) {
  10224. profilingStart = performance.now();
  10225. } // Add gravity to all objects
  10226. for (i = 0; i !== N; i++) {
  10227. const bi = bodies[i];
  10228. if (bi.type === DYNAMIC) {
  10229. // Only for dynamic bodies
  10230. const f = bi.force;
  10231. const m = bi.mass;
  10232. f.x += m * gx;
  10233. f.y += m * gy;
  10234. f.z += m * gz;
  10235. }
  10236. } // Update subsystems
  10237. for (let i = 0, Nsubsystems = this.subsystems.length; i !== Nsubsystems; i++) {
  10238. this.subsystems[i].update();
  10239. } // Collision detection
  10240. if (doProfiling) {
  10241. profilingStart = performance.now();
  10242. }
  10243. p1.length = 0; // Clean up pair arrays from last step
  10244. p2.length = 0;
  10245. this.broadphase.collisionPairs(this, p1, p2);
  10246. if (doProfiling) {
  10247. profile.broadphase = performance.now() - profilingStart;
  10248. } // Remove constrained pairs with collideConnected == false
  10249. let Nconstraints = constraints.length;
  10250. for (i = 0; i !== Nconstraints; i++) {
  10251. const c = constraints[i];
  10252. if (!c.collideConnected) {
  10253. for (let j = p1.length - 1; j >= 0; j -= 1) {
  10254. if (c.bodyA === p1[j] && c.bodyB === p2[j] || c.bodyB === p1[j] && c.bodyA === p2[j]) {
  10255. p1.splice(j, 1);
  10256. p2.splice(j, 1);
  10257. }
  10258. }
  10259. }
  10260. }
  10261. this.collisionMatrixTick(); // Generate contacts
  10262. if (doProfiling) {
  10263. profilingStart = performance.now();
  10264. }
  10265. const oldcontacts = World_step_oldContacts;
  10266. const NoldContacts = contacts.length;
  10267. for (i = 0; i !== NoldContacts; i++) {
  10268. oldcontacts.push(contacts[i]);
  10269. }
  10270. contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse
  10271. const NoldFrictionEquations = this.frictionEquations.length;
  10272. for (i = 0; i !== NoldFrictionEquations; i++) {
  10273. frictionEquationPool.push(this.frictionEquations[i]);
  10274. }
  10275. this.frictionEquations.length = 0;
  10276. this.narrowphase.getContacts(p1, p2, this, contacts, oldcontacts, // To be reused
  10277. this.frictionEquations, frictionEquationPool);
  10278. if (doProfiling) {
  10279. profile.narrowphase = performance.now() - profilingStart;
  10280. } // Loop over all collisions
  10281. if (doProfiling) {
  10282. profilingStart = performance.now();
  10283. } // Add all friction eqs
  10284. for (i = 0; i < this.frictionEquations.length; i++) {
  10285. solver.addEquation(this.frictionEquations[i]);
  10286. }
  10287. const ncontacts = contacts.length;
  10288. for (let k = 0; k !== ncontacts; k++) {
  10289. // Current contact
  10290. const c = contacts[k]; // Get current collision indeces
  10291. const bi = c.bi;
  10292. const bj = c.bj;
  10293. const si = c.si;
  10294. const sj = c.sj; // Get collision properties
  10295. let cm;
  10296. if (bi.material && bj.material) {
  10297. cm = this.getContactMaterial(bi.material, bj.material) || this.defaultContactMaterial;
  10298. } else {
  10299. cm = this.defaultContactMaterial;
  10300. } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  10301. cm.friction; // c.restitution = cm.restitution;
  10302. // If friction or restitution were specified in the material, use them
  10303. if (bi.material && bj.material) {
  10304. if (bi.material.friction >= 0 && bj.material.friction >= 0) {
  10305. bi.material.friction * bj.material.friction;
  10306. }
  10307. if (bi.material.restitution >= 0 && bj.material.restitution >= 0) {
  10308. c.restitution = bi.material.restitution * bj.material.restitution;
  10309. }
  10310. } // c.setSpookParams(
  10311. // cm.contactEquationStiffness,
  10312. // cm.contactEquationRelaxation,
  10313. // dt
  10314. // );
  10315. solver.addEquation(c); // // Add friction constraint equation
  10316. // if(mu > 0){
  10317. // // Create 2 tangent equations
  10318. // const mug = mu * gnorm;
  10319. // const reducedMass = (bi.invMass + bj.invMass);
  10320. // if(reducedMass > 0){
  10321. // reducedMass = 1/reducedMass;
  10322. // }
  10323. // const pool = frictionEquationPool;
  10324. // const c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  10325. // const c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  10326. // this.frictionEquations.push(c1, c2);
  10327. // c1.bi = c2.bi = bi;
  10328. // c1.bj = c2.bj = bj;
  10329. // c1.minForce = c2.minForce = -mug*reducedMass;
  10330. // c1.maxForce = c2.maxForce = mug*reducedMass;
  10331. // // Copy over the relative vectors
  10332. // c1.ri.copy(c.ri);
  10333. // c1.rj.copy(c.rj);
  10334. // c2.ri.copy(c.ri);
  10335. // c2.rj.copy(c.rj);
  10336. // // Construct tangents
  10337. // c.ni.tangents(c1.t, c2.t);
  10338. // // Set spook params
  10339. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  10340. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  10341. // c1.enabled = c2.enabled = c.enabled;
  10342. // // Add equations to solver
  10343. // solver.addEquation(c1);
  10344. // solver.addEquation(c2);
  10345. // }
  10346. if (bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC) {
  10347. const speedSquaredB = bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared();
  10348. const speedLimitSquaredB = bj.sleepSpeedLimit ** 2;
  10349. if (speedSquaredB >= speedLimitSquaredB * 2) {
  10350. bi.wakeUpAfterNarrowphase = true;
  10351. }
  10352. }
  10353. if (bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC) {
  10354. const speedSquaredA = bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared();
  10355. const speedLimitSquaredA = bi.sleepSpeedLimit ** 2;
  10356. if (speedSquaredA >= speedLimitSquaredA * 2) {
  10357. bj.wakeUpAfterNarrowphase = true;
  10358. }
  10359. } // Now we know that i and j are in contact. Set collision matrix state
  10360. this.collisionMatrix.set(bi, bj, true);
  10361. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  10362. // First contact!
  10363. // 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.
  10364. World_step_collideEvent.body = bj;
  10365. World_step_collideEvent.contact = c;
  10366. bi.dispatchEvent(World_step_collideEvent);
  10367. World_step_collideEvent.body = bi;
  10368. bj.dispatchEvent(World_step_collideEvent);
  10369. }
  10370. this.bodyOverlapKeeper.set(bi.id, bj.id);
  10371. this.shapeOverlapKeeper.set(si.id, sj.id);
  10372. }
  10373. this.emitContactEvents();
  10374. if (doProfiling) {
  10375. profile.makeContactConstraints = performance.now() - profilingStart;
  10376. profilingStart = performance.now();
  10377. } // Wake up bodies
  10378. for (i = 0; i !== N; i++) {
  10379. const bi = bodies[i];
  10380. if (bi.wakeUpAfterNarrowphase) {
  10381. bi.wakeUp();
  10382. bi.wakeUpAfterNarrowphase = false;
  10383. }
  10384. } // Add user-added constraints
  10385. Nconstraints = constraints.length;
  10386. for (i = 0; i !== Nconstraints; i++) {
  10387. const c = constraints[i];
  10388. c.update();
  10389. for (let j = 0, Neq = c.equations.length; j !== Neq; j++) {
  10390. const eq = c.equations[j];
  10391. solver.addEquation(eq);
  10392. }
  10393. } // Solve the constrained system
  10394. solver.solve(dt, this);
  10395. if (doProfiling) {
  10396. profile.solve = performance.now() - profilingStart;
  10397. } // Remove all contacts from solver
  10398. solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  10399. const pow = Math.pow;
  10400. for (i = 0; i !== N; i++) {
  10401. const bi = bodies[i];
  10402. if (bi.type & DYNAMIC) {
  10403. // Only for dynamic bodies
  10404. const ld = pow(1.0 - bi.linearDamping, dt);
  10405. const v = bi.velocity;
  10406. v.scale(ld, v);
  10407. const av = bi.angularVelocity;
  10408. if (av) {
  10409. const ad = pow(1.0 - bi.angularDamping, dt);
  10410. av.scale(ad, av);
  10411. }
  10412. }
  10413. }
  10414. this.dispatchEvent(World_step_preStepEvent); // Leap frog
  10415. // vnew = v + h*f/m
  10416. // xnew = x + h*vnew
  10417. if (doProfiling) {
  10418. profilingStart = performance.now();
  10419. }
  10420. const stepnumber = this.stepnumber;
  10421. const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;
  10422. const quatNormalizeFast = this.quatNormalizeFast;
  10423. for (i = 0; i !== N; i++) {
  10424. bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);
  10425. }
  10426. this.clearForces();
  10427. this.broadphase.dirty = true;
  10428. if (doProfiling) {
  10429. profile.integrate = performance.now() - profilingStart;
  10430. } // Update step number
  10431. this.stepnumber += 1;
  10432. this.dispatchEvent(World_step_postStepEvent); // Sleeping update
  10433. let hasActiveBodies = true;
  10434. if (this.allowSleep) {
  10435. hasActiveBodies = false;
  10436. for (i = 0; i !== N; i++) {
  10437. const bi = bodies[i];
  10438. bi.sleepTick(this.time);
  10439. if (bi.sleepState !== Body.SLEEPING) {
  10440. hasActiveBodies = true;
  10441. }
  10442. }
  10443. }
  10444. this.hasActiveBodies = hasActiveBodies;
  10445. }
  10446. emitContactEvents() {
  10447. const hasBeginContact = this.hasAnyEventListener('beginContact');
  10448. const hasEndContact = this.hasAnyEventListener('endContact');
  10449. if (hasBeginContact || hasEndContact) {
  10450. this.bodyOverlapKeeper.getDiff(additions, removals);
  10451. }
  10452. if (hasBeginContact) {
  10453. for (let i = 0, l = additions.length; i < l; i += 2) {
  10454. beginContactEvent.bodyA = this.getBodyById(additions[i]);
  10455. beginContactEvent.bodyB = this.getBodyById(additions[i + 1]);
  10456. this.dispatchEvent(beginContactEvent);
  10457. }
  10458. beginContactEvent.bodyA = beginContactEvent.bodyB = null;
  10459. }
  10460. if (hasEndContact) {
  10461. for (let i = 0, l = removals.length; i < l; i += 2) {
  10462. endContactEvent.bodyA = this.getBodyById(removals[i]);
  10463. endContactEvent.bodyB = this.getBodyById(removals[i + 1]);
  10464. this.dispatchEvent(endContactEvent);
  10465. }
  10466. endContactEvent.bodyA = endContactEvent.bodyB = null;
  10467. }
  10468. additions.length = removals.length = 0;
  10469. const hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');
  10470. const hasEndShapeContact = this.hasAnyEventListener('endShapeContact');
  10471. if (hasBeginShapeContact || hasEndShapeContact) {
  10472. this.shapeOverlapKeeper.getDiff(additions, removals);
  10473. }
  10474. if (hasBeginShapeContact) {
  10475. for (let i = 0, l = additions.length; i < l; i += 2) {
  10476. const shapeA = this.getShapeById(additions[i]);
  10477. const shapeB = this.getShapeById(additions[i + 1]);
  10478. beginShapeContactEvent.shapeA = shapeA;
  10479. beginShapeContactEvent.shapeB = shapeB;
  10480. if (shapeA) beginShapeContactEvent.bodyA = shapeA.body;
  10481. if (shapeB) beginShapeContactEvent.bodyB = shapeB.body;
  10482. this.dispatchEvent(beginShapeContactEvent);
  10483. }
  10484. beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;
  10485. }
  10486. if (hasEndShapeContact) {
  10487. for (let i = 0, l = removals.length; i < l; i += 2) {
  10488. const shapeA = this.getShapeById(removals[i]);
  10489. const shapeB = this.getShapeById(removals[i + 1]);
  10490. endShapeContactEvent.shapeA = shapeA;
  10491. endShapeContactEvent.shapeB = shapeB;
  10492. if (shapeA) endShapeContactEvent.bodyA = shapeA.body;
  10493. if (shapeB) endShapeContactEvent.bodyB = shapeB.body;
  10494. this.dispatchEvent(endShapeContactEvent);
  10495. }
  10496. endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;
  10497. }
  10498. }
  10499. /**
  10500. * Sets all body forces in the world to zero.
  10501. */
  10502. clearForces() {
  10503. const bodies = this.bodies;
  10504. const N = bodies.length;
  10505. for (let i = 0; i !== N; i++) {
  10506. const b = bodies[i];
  10507. b.force;
  10508. b.torque;
  10509. b.force.set(0, 0, 0);
  10510. b.torque.set(0, 0, 0);
  10511. }
  10512. }
  10513. } // Temp stuff
  10514. new AABB();
  10515. const tmpRay = new Ray(); // performance.now() fallback on Date.now()
  10516. const performance = require('perf_hooks') && require('perf_hooks').performance || {};
  10517. if (!performance.now) {
  10518. let nowOffset = Date.now();
  10519. if (performance.timing && performance.timing.navigationStart) {
  10520. nowOffset = performance.timing.navigationStart;
  10521. }
  10522. performance.now = () => Date.now() - nowOffset;
  10523. }
  10524. new Vec3(); // Dispatched after the world has stepped forward in time.
  10525. // Reusable event objects to save memory.
  10526. const World_step_postStepEvent = {
  10527. type: 'postStep'
  10528. }; // Dispatched before the world steps forward in time.
  10529. const World_step_preStepEvent = {
  10530. type: 'preStep'
  10531. };
  10532. const World_step_collideEvent = {
  10533. type: Body.COLLIDE_EVENT_NAME,
  10534. body: null,
  10535. contact: null
  10536. }; // Pools for unused objects
  10537. const World_step_oldContacts = [];
  10538. const World_step_frictionEquationPool = []; // Reusable arrays for collision pairs
  10539. const World_step_p1 = [];
  10540. const World_step_p2 = []; // Stuff for emitContactEvents
  10541. const additions = [];
  10542. const removals = [];
  10543. const beginContactEvent = {
  10544. type: 'beginContact',
  10545. bodyA: null,
  10546. bodyB: null
  10547. };
  10548. const endContactEvent = {
  10549. type: 'endContact',
  10550. bodyA: null,
  10551. bodyB: null
  10552. };
  10553. const beginShapeContactEvent = {
  10554. type: 'beginShapeContact',
  10555. bodyA: null,
  10556. bodyB: null,
  10557. shapeA: null,
  10558. shapeB: null
  10559. };
  10560. const endShapeContactEvent = {
  10561. type: 'endShapeContact',
  10562. bodyA: null,
  10563. bodyB: null,
  10564. shapeA: null,
  10565. shapeB: null
  10566. };
  10567. exports.AABB = AABB;
  10568. exports.ArrayCollisionMatrix = ArrayCollisionMatrix;
  10569. exports.BODY_SLEEP_STATES = BODY_SLEEP_STATES;
  10570. exports.BODY_TYPES = BODY_TYPES;
  10571. exports.Body = Body;
  10572. exports.Box = Box;
  10573. exports.Broadphase = Broadphase;
  10574. exports.COLLISION_TYPES = COLLISION_TYPES;
  10575. exports.ConeTwistConstraint = ConeTwistConstraint;
  10576. exports.Constraint = Constraint;
  10577. exports.ContactEquation = ContactEquation;
  10578. exports.ContactMaterial = ContactMaterial;
  10579. exports.ConvexPolyhedron = ConvexPolyhedron;
  10580. exports.Cylinder = Cylinder;
  10581. exports.DistanceConstraint = DistanceConstraint;
  10582. exports.Equation = Equation;
  10583. exports.EventTarget = EventTarget;
  10584. exports.FrictionEquation = FrictionEquation;
  10585. exports.GSSolver = GSSolver;
  10586. exports.GridBroadphase = GridBroadphase;
  10587. exports.Heightfield = Heightfield;
  10588. exports.HingeConstraint = HingeConstraint;
  10589. exports.JacobianElement = JacobianElement;
  10590. exports.LockConstraint = LockConstraint;
  10591. exports.Mat3 = Mat3;
  10592. exports.Material = Material;
  10593. exports.NaiveBroadphase = NaiveBroadphase;
  10594. exports.Narrowphase = Narrowphase;
  10595. exports.ObjectCollisionMatrix = ObjectCollisionMatrix;
  10596. exports.Particle = Particle;
  10597. exports.Plane = Plane;
  10598. exports.PointToPointConstraint = PointToPointConstraint;
  10599. exports.Pool = Pool;
  10600. exports.Quaternion = Quaternion;
  10601. exports.RAY_MODES = RAY_MODES;
  10602. exports.Ray = Ray;
  10603. exports.RaycastResult = RaycastResult;
  10604. exports.RaycastVehicle = RaycastVehicle;
  10605. exports.RigidVehicle = RigidVehicle;
  10606. exports.RotationalEquation = RotationalEquation;
  10607. exports.RotationalMotorEquation = RotationalMotorEquation;
  10608. exports.SAPBroadphase = SAPBroadphase;
  10609. exports.SHAPE_TYPES = SHAPE_TYPES;
  10610. exports.SPHSystem = SPHSystem;
  10611. exports.Shape = Shape;
  10612. exports.Solver = Solver;
  10613. exports.Sphere = Sphere;
  10614. exports.SplitSolver = SplitSolver;
  10615. exports.Spring = Spring;
  10616. exports.Transform = Transform;
  10617. exports.Trimesh = Trimesh;
  10618. exports.Vec3 = Vec3;
  10619. exports.Vec3Pool = Vec3Pool;
  10620. exports.WheelInfo = WheelInfo;
  10621. exports.World = World;