math.ts 296 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353
  1. import { Tools } from "Tools";
  2. import { Nullable, FloatArray, float } from "types";
  3. import { Scalar, ISize } from "Math";
  4. import { Engine } from "Engine";
  5. import { Ray } from "Culling";
  6. /**
  7. * Constant used to convert a value to gamma space
  8. * @ignorenaming
  9. */
  10. export const ToGammaSpace = 1 / 2.2;
  11. /**
  12. * Constant used to convert a value to linear space
  13. * @ignorenaming
  14. */
  15. export const ToLinearSpace = 2.2;
  16. /**
  17. * Constant used to define the minimal number value in Babylon.js
  18. * @ignorenaming
  19. */
  20. export const Epsilon = 0.001;
  21. /**
  22. * Class used to hold a RBG color
  23. */
  24. export class Color3 {
  25. /**
  26. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  27. * @param r defines the red component (between 0 and 1, default is 0)
  28. * @param g defines the green component (between 0 and 1, default is 0)
  29. * @param b defines the blue component (between 0 and 1, default is 0)
  30. */
  31. constructor(
  32. /**
  33. * Defines the red component (between 0 and 1, default is 0)
  34. */
  35. public r: number = 0,
  36. /**
  37. * Defines the green component (between 0 and 1, default is 0)
  38. */
  39. public g: number = 0,
  40. /**
  41. * Defines the blue component (between 0 and 1, default is 0)
  42. */
  43. public b: number = 0) {
  44. }
  45. /**
  46. * Creates a string with the Color3 current values
  47. * @returns the string representation of the Color3 object
  48. */
  49. public toString(): string {
  50. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  51. }
  52. /**
  53. * Returns the string "Color3"
  54. * @returns "Color3"
  55. */
  56. public getClassName(): string {
  57. return "Color3";
  58. }
  59. /**
  60. * Compute the Color3 hash code
  61. * @returns an unique number that can be used to hash Color3 objects
  62. */
  63. public getHashCode(): number {
  64. let hash = this.r || 0;
  65. hash = (hash * 397) ^ (this.g || 0);
  66. hash = (hash * 397) ^ (this.b || 0);
  67. return hash;
  68. }
  69. // Operators
  70. /**
  71. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  72. * @param array defines the array where to store the r,g,b components
  73. * @param index defines an optional index in the target array to define where to start storing values
  74. * @returns the current Color3 object
  75. */
  76. public toArray(array: FloatArray, index: number = 0): Color3 {
  77. array[index] = this.r;
  78. array[index + 1] = this.g;
  79. array[index + 2] = this.b;
  80. return this;
  81. }
  82. /**
  83. * Returns a new Color4 object from the current Color3 and the given alpha
  84. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  85. * @returns a new Color4 object
  86. */
  87. public toColor4(alpha: number = 1): Color4 {
  88. return new Color4(this.r, this.g, this.b, alpha);
  89. }
  90. /**
  91. * Returns a new array populated with 3 numeric elements : red, green and blue values
  92. * @returns the new array
  93. */
  94. public asArray(): number[] {
  95. var result = new Array<number>();
  96. this.toArray(result, 0);
  97. return result;
  98. }
  99. /**
  100. * Returns the luminance value
  101. * @returns a float value
  102. */
  103. public toLuminance(): number {
  104. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  105. }
  106. /**
  107. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  108. * @param otherColor defines the second operand
  109. * @returns the new Color3 object
  110. */
  111. public multiply(otherColor: Color3): Color3 {
  112. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  113. }
  114. /**
  115. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  116. * @param otherColor defines the second operand
  117. * @param result defines the Color3 object where to store the result
  118. * @returns the current Color3
  119. */
  120. public multiplyToRef(otherColor: Color3, result: Color3): Color3 {
  121. result.r = this.r * otherColor.r;
  122. result.g = this.g * otherColor.g;
  123. result.b = this.b * otherColor.b;
  124. return this;
  125. }
  126. /**
  127. * Determines equality between Color3 objects
  128. * @param otherColor defines the second operand
  129. * @returns true if the rgb values are equal to the given ones
  130. */
  131. public equals(otherColor: Color3): boolean {
  132. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  133. }
  134. /**
  135. * Determines equality between the current Color3 object and a set of r,b,g values
  136. * @param r defines the red component to check
  137. * @param g defines the green component to check
  138. * @param b defines the blue component to check
  139. * @returns true if the rgb values are equal to the given ones
  140. */
  141. public equalsFloats(r: number, g: number, b: number): boolean {
  142. return this.r === r && this.g === g && this.b === b;
  143. }
  144. /**
  145. * Multiplies in place each rgb value by scale
  146. * @param scale defines the scaling factor
  147. * @returns the updated Color3
  148. */
  149. public scale(scale: number): Color3 {
  150. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  151. }
  152. /**
  153. * Multiplies the rgb values by scale and stores the result into "result"
  154. * @param scale defines the scaling factor
  155. * @param result defines the Color3 object where to store the result
  156. * @returns the unmodified current Color3
  157. */
  158. public scaleToRef(scale: number, result: Color3): Color3 {
  159. result.r = this.r * scale;
  160. result.g = this.g * scale;
  161. result.b = this.b * scale;
  162. return this;
  163. }
  164. /**
  165. * Scale the current Color3 values by a factor and add the result to a given Color3
  166. * @param scale defines the scale factor
  167. * @param result defines color to store the result into
  168. * @returns the unmodified current Color3
  169. */
  170. public scaleAndAddToRef(scale: number, result: Color3): Color3 {
  171. result.r += this.r * scale;
  172. result.g += this.g * scale;
  173. result.b += this.b * scale;
  174. return this;
  175. }
  176. /**
  177. * Clamps the rgb values by the min and max values and stores the result into "result"
  178. * @param min defines minimum clamping value (default is 0)
  179. * @param max defines maximum clamping value (default is 1)
  180. * @param result defines color to store the result into
  181. * @returns the original Color3
  182. */
  183. public clampToRef(min: number = 0, max: number = 1, result: Color3): Color3 {
  184. result.r = Scalar.Clamp(this.r, min, max);
  185. result.g = Scalar.Clamp(this.g, min, max);
  186. result.b = Scalar.Clamp(this.b, min, max);
  187. return this;
  188. }
  189. /**
  190. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  191. * @param otherColor defines the second operand
  192. * @returns the new Color3
  193. */
  194. public add(otherColor: Color3): Color3 {
  195. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  196. }
  197. /**
  198. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  199. * @param otherColor defines the second operand
  200. * @param result defines Color3 object to store the result into
  201. * @returns the unmodified current Color3
  202. */
  203. public addToRef(otherColor: Color3, result: Color3): Color3 {
  204. result.r = this.r + otherColor.r;
  205. result.g = this.g + otherColor.g;
  206. result.b = this.b + otherColor.b;
  207. return this;
  208. }
  209. /**
  210. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  211. * @param otherColor defines the second operand
  212. * @returns the new Color3
  213. */
  214. public subtract(otherColor: Color3): Color3 {
  215. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  216. }
  217. /**
  218. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  219. * @param otherColor defines the second operand
  220. * @param result defines Color3 object to store the result into
  221. * @returns the unmodified current Color3
  222. */
  223. public subtractToRef(otherColor: Color3, result: Color3): Color3 {
  224. result.r = this.r - otherColor.r;
  225. result.g = this.g - otherColor.g;
  226. result.b = this.b - otherColor.b;
  227. return this;
  228. }
  229. /**
  230. * Copy the current object
  231. * @returns a new Color3 copied the current one
  232. */
  233. public clone(): Color3 {
  234. return new Color3(this.r, this.g, this.b);
  235. }
  236. /**
  237. * Copies the rgb values from the source in the current Color3
  238. * @param source defines the source Color3 object
  239. * @returns the updated Color3 object
  240. */
  241. public copyFrom(source: Color3): Color3 {
  242. this.r = source.r;
  243. this.g = source.g;
  244. this.b = source.b;
  245. return this;
  246. }
  247. /**
  248. * Updates the Color3 rgb values from the given floats
  249. * @param r defines the red component to read from
  250. * @param g defines the green component to read from
  251. * @param b defines the blue component to read from
  252. * @returns the current Color3 object
  253. */
  254. public copyFromFloats(r: number, g: number, b: number): Color3 {
  255. this.r = r;
  256. this.g = g;
  257. this.b = b;
  258. return this;
  259. }
  260. /**
  261. * Updates the Color3 rgb values from the given floats
  262. * @param r defines the red component to read from
  263. * @param g defines the green component to read from
  264. * @param b defines the blue component to read from
  265. * @returns the current Color3 object
  266. */
  267. public set(r: number, g: number, b: number): Color3 {
  268. return this.copyFromFloats(r, g, b);
  269. }
  270. /**
  271. * Compute the Color3 hexadecimal code as a string
  272. * @returns a string containing the hexadecimal representation of the Color3 object
  273. */
  274. public toHexString(): string {
  275. var intR = (this.r * 255) | 0;
  276. var intG = (this.g * 255) | 0;
  277. var intB = (this.b * 255) | 0;
  278. return "#" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB);
  279. }
  280. /**
  281. * Computes a new Color3 converted from the current one to linear space
  282. * @returns a new Color3 object
  283. */
  284. public toLinearSpace(): Color3 {
  285. var convertedColor = new Color3();
  286. this.toLinearSpaceToRef(convertedColor);
  287. return convertedColor;
  288. }
  289. /**
  290. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  291. * @param convertedColor defines the Color3 object where to store the linear space version
  292. * @returns the unmodified Color3
  293. */
  294. public toLinearSpaceToRef(convertedColor: Color3): Color3 {
  295. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  296. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  297. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  298. return this;
  299. }
  300. /**
  301. * Computes a new Color3 converted from the current one to gamma space
  302. * @returns a new Color3 object
  303. */
  304. public toGammaSpace(): Color3 {
  305. var convertedColor = new Color3();
  306. this.toGammaSpaceToRef(convertedColor);
  307. return convertedColor;
  308. }
  309. /**
  310. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  311. * @param convertedColor defines the Color3 object where to store the gamma space version
  312. * @returns the unmodified Color3
  313. */
  314. public toGammaSpaceToRef(convertedColor: Color3): Color3 {
  315. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  316. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  317. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  318. return this;
  319. }
  320. // Statics
  321. /**
  322. * Creates a new Color3 from the string containing valid hexadecimal values
  323. * @param hex defines a string containing valid hexadecimal values
  324. * @returns a new Color3 object
  325. */
  326. public static FromHexString(hex: string): Color3 {
  327. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  328. return new Color3(0, 0, 0);
  329. }
  330. var r = parseInt(hex.substring(1, 3), 16);
  331. var g = parseInt(hex.substring(3, 5), 16);
  332. var b = parseInt(hex.substring(5, 7), 16);
  333. return Color3.FromInts(r, g, b);
  334. }
  335. /**
  336. * Creates a new Vector3 from the starting index of the given array
  337. * @param array defines the source array
  338. * @param offset defines an offset in the source array
  339. * @returns a new Color3 object
  340. */
  341. public static FromArray(array: ArrayLike<number>, offset: number = 0): Color3 {
  342. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  343. }
  344. /**
  345. * Creates a new Color3 from integer values (< 256)
  346. * @param r defines the red component to read from (value between 0 and 255)
  347. * @param g defines the green component to read from (value between 0 and 255)
  348. * @param b defines the blue component to read from (value between 0 and 255)
  349. * @returns a new Color3 object
  350. */
  351. public static FromInts(r: number, g: number, b: number): Color3 {
  352. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  353. }
  354. /**
  355. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  356. * @param start defines the start Color3 value
  357. * @param end defines the end Color3 value
  358. * @param amount defines the gradient value between start and end
  359. * @returns a new Color3 object
  360. */
  361. public static Lerp(start: Color3, end: Color3, amount: number): Color3 {
  362. var result = new Color3(0.0, 0.0, 0.0);
  363. Color3.LerpToRef(start, end, amount, result);
  364. return result;
  365. }
  366. /**
  367. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  368. * @param left defines the start value
  369. * @param right defines the end value
  370. * @param amount defines the gradient factor
  371. * @param result defines the Color3 object where to store the result
  372. */
  373. public static LerpToRef(left: Color3, right: Color3, amount: number, result: Color3): void {
  374. result.r = left.r + ((right.r - left.r) * amount);
  375. result.g = left.g + ((right.g - left.g) * amount);
  376. result.b = left.b + ((right.b - left.b) * amount);
  377. }
  378. /**
  379. * Returns a Color3 value containing a red color
  380. * @returns a new Color3 object
  381. */
  382. public static Red(): Color3 { return new Color3(1, 0, 0); }
  383. /**
  384. * Returns a Color3 value containing a green color
  385. * @returns a new Color3 object
  386. */
  387. public static Green(): Color3 { return new Color3(0, 1, 0); }
  388. /**
  389. * Returns a Color3 value containing a blue color
  390. * @returns a new Color3 object
  391. */
  392. public static Blue(): Color3 { return new Color3(0, 0, 1); }
  393. /**
  394. * Returns a Color3 value containing a black color
  395. * @returns a new Color3 object
  396. */
  397. public static Black(): Color3 { return new Color3(0, 0, 0); }
  398. /**
  399. * Returns a Color3 value containing a white color
  400. * @returns a new Color3 object
  401. */
  402. public static White(): Color3 { return new Color3(1, 1, 1); }
  403. /**
  404. * Returns a Color3 value containing a purple color
  405. * @returns a new Color3 object
  406. */
  407. public static Purple(): Color3 { return new Color3(0.5, 0, 0.5); }
  408. /**
  409. * Returns a Color3 value containing a magenta color
  410. * @returns a new Color3 object
  411. */
  412. public static Magenta(): Color3 { return new Color3(1, 0, 1); }
  413. /**
  414. * Returns a Color3 value containing a yellow color
  415. * @returns a new Color3 object
  416. */
  417. public static Yellow(): Color3 { return new Color3(1, 1, 0); }
  418. /**
  419. * Returns a Color3 value containing a gray color
  420. * @returns a new Color3 object
  421. */
  422. public static Gray(): Color3 { return new Color3(0.5, 0.5, 0.5); }
  423. /**
  424. * Returns a Color3 value containing a teal color
  425. * @returns a new Color3 object
  426. */
  427. public static Teal(): Color3 { return new Color3(0, 1.0, 1.0); }
  428. /**
  429. * Returns a Color3 value containing a random color
  430. * @returns a new Color3 object
  431. */
  432. public static Random(): Color3 { return new Color3(Math.random(), Math.random(), Math.random()); }
  433. }
  434. /**
  435. * Class used to hold a RBGA color
  436. */
  437. export class Color4 {
  438. /**
  439. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  440. * @param r defines the red component (between 0 and 1, default is 0)
  441. * @param g defines the green component (between 0 and 1, default is 0)
  442. * @param b defines the blue component (between 0 and 1, default is 0)
  443. * @param a defines the alpha component (between 0 and 1, default is 1)
  444. */
  445. constructor(
  446. /**
  447. * Defines the red component (between 0 and 1, default is 0)
  448. */
  449. public r: number = 0,
  450. /**
  451. * Defines the green component (between 0 and 1, default is 0)
  452. */
  453. public g: number = 0,
  454. /**
  455. * Defines the blue component (between 0 and 1, default is 0)
  456. */
  457. public b: number = 0,
  458. /**
  459. * Defines the alpha component (between 0 and 1, default is 1)
  460. */
  461. public a: number = 1) {
  462. }
  463. // Operators
  464. /**
  465. * Adds in place the given Color4 values to the current Color4 object
  466. * @param right defines the second operand
  467. * @returns the current updated Color4 object
  468. */
  469. public addInPlace(right: Color4): Color4 {
  470. this.r += right.r;
  471. this.g += right.g;
  472. this.b += right.b;
  473. this.a += right.a;
  474. return this;
  475. }
  476. /**
  477. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  478. * @returns the new array
  479. */
  480. public asArray(): number[] {
  481. var result = new Array<number>();
  482. this.toArray(result, 0);
  483. return result;
  484. }
  485. /**
  486. * Stores from the starting index in the given array the Color4 successive values
  487. * @param array defines the array where to store the r,g,b components
  488. * @param index defines an optional index in the target array to define where to start storing values
  489. * @returns the current Color4 object
  490. */
  491. public toArray(array: number[], index: number = 0): Color4 {
  492. array[index] = this.r;
  493. array[index + 1] = this.g;
  494. array[index + 2] = this.b;
  495. array[index + 3] = this.a;
  496. return this;
  497. }
  498. /**
  499. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  500. * @param right defines the second operand
  501. * @returns a new Color4 object
  502. */
  503. public add(right: Color4): Color4 {
  504. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  505. }
  506. /**
  507. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  508. * @param right defines the second operand
  509. * @returns a new Color4 object
  510. */
  511. public subtract(right: Color4): Color4 {
  512. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  513. }
  514. /**
  515. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  516. * @param right defines the second operand
  517. * @param result defines the Color4 object where to store the result
  518. * @returns the current Color4 object
  519. */
  520. public subtractToRef(right: Color4, result: Color4): Color4 {
  521. result.r = this.r - right.r;
  522. result.g = this.g - right.g;
  523. result.b = this.b - right.b;
  524. result.a = this.a - right.a;
  525. return this;
  526. }
  527. /**
  528. * Creates a new Color4 with the current Color4 values multiplied by scale
  529. * @param scale defines the scaling factor to apply
  530. * @returns a new Color4 object
  531. */
  532. public scale(scale: number): Color4 {
  533. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  534. }
  535. /**
  536. * Multiplies the current Color4 values by scale and stores the result in "result"
  537. * @param scale defines the scaling factor to apply
  538. * @param result defines the Color4 object where to store the result
  539. * @returns the current unmodified Color4
  540. */
  541. public scaleToRef(scale: number, result: Color4): Color4 {
  542. result.r = this.r * scale;
  543. result.g = this.g * scale;
  544. result.b = this.b * scale;
  545. result.a = this.a * scale;
  546. return this;
  547. }
  548. /**
  549. * Scale the current Color4 values by a factor and add the result to a given Color4
  550. * @param scale defines the scale factor
  551. * @param result defines the Color4 object where to store the result
  552. * @returns the unmodified current Color4
  553. */
  554. public scaleAndAddToRef(scale: number, result: Color4): Color4 {
  555. result.r += this.r * scale;
  556. result.g += this.g * scale;
  557. result.b += this.b * scale;
  558. result.a += this.a * scale;
  559. return this;
  560. }
  561. /**
  562. * Clamps the rgb values by the min and max values and stores the result into "result"
  563. * @param min defines minimum clamping value (default is 0)
  564. * @param max defines maximum clamping value (default is 1)
  565. * @param result defines color to store the result into.
  566. * @returns the cuurent Color4
  567. */
  568. public clampToRef(min: number = 0, max: number = 1, result: Color4): Color4 {
  569. result.r = Scalar.Clamp(this.r, min, max);
  570. result.g = Scalar.Clamp(this.g, min, max);
  571. result.b = Scalar.Clamp(this.b, min, max);
  572. result.a = Scalar.Clamp(this.a, min, max);
  573. return this;
  574. }
  575. /**
  576. * Multipy an Color4 value by another and return a new Color4 object
  577. * @param color defines the Color4 value to multiply by
  578. * @returns a new Color4 object
  579. */
  580. public multiply(color: Color4): Color4 {
  581. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  582. }
  583. /**
  584. * Multipy a Color4 value by another and push the result in a reference value
  585. * @param color defines the Color4 value to multiply by
  586. * @param result defines the Color4 to fill the result in
  587. * @returns the result Color4
  588. */
  589. public multiplyToRef(color: Color4, result: Color4): Color4 {
  590. result.r = this.r * color.r;
  591. result.g = this.g * color.g;
  592. result.b = this.b * color.b;
  593. result.a = this.a * color.a;
  594. return result;
  595. }
  596. /**
  597. * Creates a string with the Color4 current values
  598. * @returns the string representation of the Color4 object
  599. */
  600. public toString(): string {
  601. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  602. }
  603. /**
  604. * Returns the string "Color4"
  605. * @returns "Color4"
  606. */
  607. public getClassName(): string {
  608. return "Color4";
  609. }
  610. /**
  611. * Compute the Color4 hash code
  612. * @returns an unique number that can be used to hash Color4 objects
  613. */
  614. public getHashCode(): number {
  615. let hash = this.r || 0;
  616. hash = (hash * 397) ^ (this.g || 0);
  617. hash = (hash * 397) ^ (this.b || 0);
  618. hash = (hash * 397) ^ (this.a || 0);
  619. return hash;
  620. }
  621. /**
  622. * Creates a new Color4 copied from the current one
  623. * @returns a new Color4 object
  624. */
  625. public clone(): Color4 {
  626. return new Color4(this.r, this.g, this.b, this.a);
  627. }
  628. /**
  629. * Copies the given Color4 values into the current one
  630. * @param source defines the source Color4 object
  631. * @returns the current updated Color4 object
  632. */
  633. public copyFrom(source: Color4): Color4 {
  634. this.r = source.r;
  635. this.g = source.g;
  636. this.b = source.b;
  637. this.a = source.a;
  638. return this;
  639. }
  640. /**
  641. * Copies the given float values into the current one
  642. * @param r defines the red component to read from
  643. * @param g defines the green component to read from
  644. * @param b defines the blue component to read from
  645. * @param a defines the alpha component to read from
  646. * @returns the current updated Color4 object
  647. */
  648. public copyFromFloats(r: number, g: number, b: number, a: number): Color4 {
  649. this.r = r;
  650. this.g = g;
  651. this.b = b;
  652. this.a = a;
  653. return this;
  654. }
  655. /**
  656. * Copies the given float values into the current one
  657. * @param r defines the red component to read from
  658. * @param g defines the green component to read from
  659. * @param b defines the blue component to read from
  660. * @param a defines the alpha component to read from
  661. * @returns the current updated Color4 object
  662. */
  663. public set(r: number, g: number, b: number, a: number): Color4 {
  664. return this.copyFromFloats(r, g, b, a);
  665. }
  666. /**
  667. * Compute the Color4 hexadecimal code as a string
  668. * @returns a string containing the hexadecimal representation of the Color4 object
  669. */
  670. public toHexString(): string {
  671. var intR = (this.r * 255) | 0;
  672. var intG = (this.g * 255) | 0;
  673. var intB = (this.b * 255) | 0;
  674. var intA = (this.a * 255) | 0;
  675. return "#" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB) + Scalar.ToHex(intA);
  676. }
  677. /**
  678. * Computes a new Color4 converted from the current one to linear space
  679. * @returns a new Color4 object
  680. */
  681. public toLinearSpace(): Color4 {
  682. var convertedColor = new Color4();
  683. this.toLinearSpaceToRef(convertedColor);
  684. return convertedColor;
  685. }
  686. /**
  687. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  688. * @param convertedColor defines the Color4 object where to store the linear space version
  689. * @returns the unmodified Color4
  690. */
  691. public toLinearSpaceToRef(convertedColor: Color4): Color4 {
  692. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  693. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  694. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  695. convertedColor.a = this.a;
  696. return this;
  697. }
  698. /**
  699. * Computes a new Color4 converted from the current one to gamma space
  700. * @returns a new Color4 object
  701. */
  702. public toGammaSpace(): Color4 {
  703. var convertedColor = new Color4();
  704. this.toGammaSpaceToRef(convertedColor);
  705. return convertedColor;
  706. }
  707. /**
  708. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  709. * @param convertedColor defines the Color4 object where to store the gamma space version
  710. * @returns the unmodified Color4
  711. */
  712. public toGammaSpaceToRef(convertedColor: Color4): Color4 {
  713. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  714. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  715. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  716. convertedColor.a = this.a;
  717. return this;
  718. }
  719. // Statics
  720. /**
  721. * Creates a new Color4 from the string containing valid hexadecimal values
  722. * @param hex defines a string containing valid hexadecimal values
  723. * @returns a new Color4 object
  724. */
  725. public static FromHexString(hex: string): Color4 {
  726. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  727. return new Color4(0.0, 0.0, 0.0, 0.0);
  728. }
  729. var r = parseInt(hex.substring(1, 3), 16);
  730. var g = parseInt(hex.substring(3, 5), 16);
  731. var b = parseInt(hex.substring(5, 7), 16);
  732. var a = parseInt(hex.substring(7, 9), 16);
  733. return Color4.FromInts(r, g, b, a);
  734. }
  735. /**
  736. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  737. * @param left defines the start value
  738. * @param right defines the end value
  739. * @param amount defines the gradient factor
  740. * @returns a new Color4 object
  741. */
  742. public static Lerp(left: Color4, right: Color4, amount: number): Color4 {
  743. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  744. Color4.LerpToRef(left, right, amount, result);
  745. return result;
  746. }
  747. /**
  748. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  749. * @param left defines the start value
  750. * @param right defines the end value
  751. * @param amount defines the gradient factor
  752. * @param result defines the Color4 object where to store data
  753. */
  754. public static LerpToRef(left: Color4, right: Color4, amount: number, result: Color4): void {
  755. result.r = left.r + (right.r - left.r) * amount;
  756. result.g = left.g + (right.g - left.g) * amount;
  757. result.b = left.b + (right.b - left.b) * amount;
  758. result.a = left.a + (right.a - left.a) * amount;
  759. }
  760. /**
  761. * Creates a new Color4 from a Color3 and an alpha value
  762. * @param color3 defines the source Color3 to read from
  763. * @param alpha defines the alpha component (1.0 by default)
  764. * @returns a new Color4 object
  765. */
  766. public static FromColor3(color3: Color3, alpha: number = 1.0): Color4 {
  767. return new Color4(color3.r, color3.g, color3.b, alpha);
  768. }
  769. /**
  770. * Creates a new Color4 from the starting index element of the given array
  771. * @param array defines the source array to read from
  772. * @param offset defines the offset in the source array
  773. * @returns a new Color4 object
  774. */
  775. public static FromArray(array: ArrayLike<number>, offset: number = 0): Color4 {
  776. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  777. }
  778. /**
  779. * Creates a new Color3 from integer values (< 256)
  780. * @param r defines the red component to read from (value between 0 and 255)
  781. * @param g defines the green component to read from (value between 0 and 255)
  782. * @param b defines the blue component to read from (value between 0 and 255)
  783. * @param a defines the alpha component to read from (value between 0 and 255)
  784. * @returns a new Color3 object
  785. */
  786. public static FromInts(r: number, g: number, b: number, a: number): Color4 {
  787. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  788. }
  789. /**
  790. * Check the content of a given array and convert it to an array containing RGBA data
  791. * If the original array was already containing count * 4 values then it is returned directly
  792. * @param colors defines the array to check
  793. * @param count defines the number of RGBA data to expect
  794. * @returns an array containing count * 4 values (RGBA)
  795. */
  796. public static CheckColors4(colors: number[], count: number): number[] {
  797. // Check if color3 was used
  798. if (colors.length === count * 3) {
  799. var colors4 = [];
  800. for (var index = 0; index < colors.length; index += 3) {
  801. var newIndex = (index / 3) * 4;
  802. colors4[newIndex] = colors[index];
  803. colors4[newIndex + 1] = colors[index + 1];
  804. colors4[newIndex + 2] = colors[index + 2];
  805. colors4[newIndex + 3] = 1.0;
  806. }
  807. return colors4;
  808. }
  809. return colors;
  810. }
  811. }
  812. /**
  813. * Class representing a vector containing 2 coordinates
  814. */
  815. export class Vector2 {
  816. /**
  817. * Creates a new Vector2 from the given x and y coordinates
  818. * @param x defines the first coordinate
  819. * @param y defines the second coordinate
  820. */
  821. constructor(
  822. /** defines the first coordinate */
  823. public x: number = 0,
  824. /** defines the second coordinate */
  825. public y: number = 0) {
  826. }
  827. /**
  828. * Gets a string with the Vector2 coordinates
  829. * @returns a string with the Vector2 coordinates
  830. */
  831. public toString(): string {
  832. return "{X: " + this.x + " Y:" + this.y + "}";
  833. }
  834. /**
  835. * Gets class name
  836. * @returns the string "Vector2"
  837. */
  838. public getClassName(): string {
  839. return "Vector2";
  840. }
  841. /**
  842. * Gets current vector hash code
  843. * @returns the Vector2 hash code as a number
  844. */
  845. public getHashCode(): number {
  846. let hash = this.x || 0;
  847. hash = (hash * 397) ^ (this.y || 0);
  848. return hash;
  849. }
  850. // Operators
  851. /**
  852. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  853. * @param array defines the source array
  854. * @param index defines the offset in source array
  855. * @returns the current Vector2
  856. */
  857. public toArray(array: FloatArray, index: number = 0): Vector2 {
  858. array[index] = this.x;
  859. array[index + 1] = this.y;
  860. return this;
  861. }
  862. /**
  863. * Copy the current vector to an array
  864. * @returns a new array with 2 elements: the Vector2 coordinates.
  865. */
  866. public asArray(): number[] {
  867. var result = new Array<number>();
  868. this.toArray(result, 0);
  869. return result;
  870. }
  871. /**
  872. * Sets the Vector2 coordinates with the given Vector2 coordinates
  873. * @param source defines the source Vector2
  874. * @returns the current updated Vector2
  875. */
  876. public copyFrom(source: Vector2): Vector2 {
  877. this.x = source.x;
  878. this.y = source.y;
  879. return this;
  880. }
  881. /**
  882. * Sets the Vector2 coordinates with the given floats
  883. * @param x defines the first coordinate
  884. * @param y defines the second coordinate
  885. * @returns the current updated Vector2
  886. */
  887. public copyFromFloats(x: number, y: number): Vector2 {
  888. this.x = x;
  889. this.y = y;
  890. return this;
  891. }
  892. /**
  893. * Sets the Vector2 coordinates with the given floats
  894. * @param x defines the first coordinate
  895. * @param y defines the second coordinate
  896. * @returns the current updated Vector2
  897. */
  898. public set(x: number, y: number): Vector2 {
  899. return this.copyFromFloats(x, y);
  900. }
  901. /**
  902. * Add another vector with the current one
  903. * @param otherVector defines the other vector
  904. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  905. */
  906. public add(otherVector: Vector2): Vector2 {
  907. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  908. }
  909. /**
  910. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  911. * @param otherVector defines the other vector
  912. * @param result defines the target vector
  913. * @returns the unmodified current Vector2
  914. */
  915. public addToRef(otherVector: Vector2, result: Vector2): Vector2 {
  916. result.x = this.x + otherVector.x;
  917. result.y = this.y + otherVector.y;
  918. return this;
  919. }
  920. /**
  921. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  922. * @param otherVector defines the other vector
  923. * @returns the current updated Vector2
  924. */
  925. public addInPlace(otherVector: Vector2): Vector2 {
  926. this.x += otherVector.x;
  927. this.y += otherVector.y;
  928. return this;
  929. }
  930. /**
  931. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  932. * @param otherVector defines the other vector
  933. * @returns a new Vector2
  934. */
  935. public addVector3(otherVector: Vector3): Vector2 {
  936. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  937. }
  938. /**
  939. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  940. * @param otherVector defines the other vector
  941. * @returns a new Vector2
  942. */
  943. public subtract(otherVector: Vector2): Vector2 {
  944. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  945. }
  946. /**
  947. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  948. * @param otherVector defines the other vector
  949. * @param result defines the target vector
  950. * @returns the unmodified current Vector2
  951. */
  952. public subtractToRef(otherVector: Vector2, result: Vector2): Vector2 {
  953. result.x = this.x - otherVector.x;
  954. result.y = this.y - otherVector.y;
  955. return this;
  956. }
  957. /**
  958. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  959. * @param otherVector defines the other vector
  960. * @returns the current updated Vector2
  961. */
  962. public subtractInPlace(otherVector: Vector2): Vector2 {
  963. this.x -= otherVector.x;
  964. this.y -= otherVector.y;
  965. return this;
  966. }
  967. /**
  968. * Multiplies in place the current Vector2 coordinates by the given ones
  969. * @param otherVector defines the other vector
  970. * @returns the current updated Vector2
  971. */
  972. public multiplyInPlace(otherVector: Vector2): Vector2 {
  973. this.x *= otherVector.x;
  974. this.y *= otherVector.y;
  975. return this;
  976. }
  977. /**
  978. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  979. * @param otherVector defines the other vector
  980. * @returns a new Vector2
  981. */
  982. public multiply(otherVector: Vector2): Vector2 {
  983. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  984. }
  985. /**
  986. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  987. * @param otherVector defines the other vector
  988. * @param result defines the target vector
  989. * @returns the unmodified current Vector2
  990. */
  991. public multiplyToRef(otherVector: Vector2, result: Vector2): Vector2 {
  992. result.x = this.x * otherVector.x;
  993. result.y = this.y * otherVector.y;
  994. return this;
  995. }
  996. /**
  997. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  998. * @param x defines the first coordinate
  999. * @param y defines the second coordinate
  1000. * @returns a new Vector2
  1001. */
  1002. public multiplyByFloats(x: number, y: number): Vector2 {
  1003. return new Vector2(this.x * x, this.y * y);
  1004. }
  1005. /**
  1006. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  1007. * @param otherVector defines the other vector
  1008. * @returns a new Vector2
  1009. */
  1010. public divide(otherVector: Vector2): Vector2 {
  1011. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1012. }
  1013. /**
  1014. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  1015. * @param otherVector defines the other vector
  1016. * @param result defines the target vector
  1017. * @returns the unmodified current Vector2
  1018. */
  1019. public divideToRef(otherVector: Vector2, result: Vector2): Vector2 {
  1020. result.x = this.x / otherVector.x;
  1021. result.y = this.y / otherVector.y;
  1022. return this;
  1023. }
  1024. /**
  1025. * Divides the current Vector2 coordinates by the given ones
  1026. * @param otherVector defines the other vector
  1027. * @returns the current updated Vector2
  1028. */
  1029. public divideInPlace(otherVector: Vector2): Vector2 {
  1030. return this.divideToRef(otherVector, this);
  1031. }
  1032. /**
  1033. * Gets a new Vector2 with current Vector2 negated coordinates
  1034. * @returns a new Vector2
  1035. */
  1036. public negate(): Vector2 {
  1037. return new Vector2(-this.x, -this.y);
  1038. }
  1039. /**
  1040. * Multiply the Vector2 coordinates by scale
  1041. * @param scale defines the scaling factor
  1042. * @returns the current updated Vector2
  1043. */
  1044. public scaleInPlace(scale: number): Vector2 {
  1045. this.x *= scale;
  1046. this.y *= scale;
  1047. return this;
  1048. }
  1049. /**
  1050. * Returns a new Vector2 scaled by "scale" from the current Vector2
  1051. * @param scale defines the scaling factor
  1052. * @returns a new Vector2
  1053. */
  1054. public scale(scale: number): Vector2 {
  1055. let result = new Vector2(0, 0);
  1056. this.scaleToRef(scale, result);
  1057. return result;
  1058. }
  1059. /**
  1060. * Scale the current Vector2 values by a factor to a given Vector2
  1061. * @param scale defines the scale factor
  1062. * @param result defines the Vector2 object where to store the result
  1063. * @returns the unmodified current Vector2
  1064. */
  1065. public scaleToRef(scale: number, result: Vector2): Vector2 {
  1066. result.x = this.x * scale;
  1067. result.y = this.y * scale;
  1068. return this;
  1069. }
  1070. /**
  1071. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  1072. * @param scale defines the scale factor
  1073. * @param result defines the Vector2 object where to store the result
  1074. * @returns the unmodified current Vector2
  1075. */
  1076. public scaleAndAddToRef(scale: number, result: Vector2): Vector2 {
  1077. result.x += this.x * scale;
  1078. result.y += this.y * scale;
  1079. return this;
  1080. }
  1081. /**
  1082. * Gets a boolean if two vectors are equals
  1083. * @param otherVector defines the other vector
  1084. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  1085. */
  1086. public equals(otherVector: Vector2): boolean {
  1087. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1088. }
  1089. /**
  1090. * Gets a boolean if two vectors are equals (using an epsilon value)
  1091. * @param otherVector defines the other vector
  1092. * @param epsilon defines the minimal distance to consider equality
  1093. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  1094. */
  1095. public equalsWithEpsilon(otherVector: Vector2, epsilon: number = Epsilon): boolean {
  1096. return otherVector && Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1097. }
  1098. /**
  1099. * Gets a new Vector2 from current Vector2 floored values
  1100. * @returns a new Vector2
  1101. */
  1102. public floor(): Vector2 {
  1103. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  1104. }
  1105. /**
  1106. * Gets a new Vector2 from current Vector2 floored values
  1107. * @returns a new Vector2
  1108. */
  1109. public fract(): Vector2 {
  1110. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  1111. }
  1112. // Properties
  1113. /**
  1114. * Gets the length of the vector
  1115. * @returns the vector length (float)
  1116. */
  1117. public length(): number {
  1118. return Math.sqrt(this.x * this.x + this.y * this.y);
  1119. }
  1120. /**
  1121. * Gets the vector squared length
  1122. * @returns the vector squared length (float)
  1123. */
  1124. public lengthSquared(): number {
  1125. return (this.x * this.x + this.y * this.y);
  1126. }
  1127. // Methods
  1128. /**
  1129. * Normalize the vector
  1130. * @returns the current updated Vector2
  1131. */
  1132. public normalize(): Vector2 {
  1133. var len = this.length();
  1134. if (len === 0) {
  1135. return this;
  1136. }
  1137. var num = 1.0 / len;
  1138. this.x *= num;
  1139. this.y *= num;
  1140. return this;
  1141. }
  1142. /**
  1143. * Gets a new Vector2 copied from the Vector2
  1144. * @returns a new Vector2
  1145. */
  1146. public clone(): Vector2 {
  1147. return new Vector2(this.x, this.y);
  1148. }
  1149. // Statics
  1150. /**
  1151. * Gets a new Vector2(0, 0)
  1152. * @returns a new Vector2
  1153. */
  1154. public static Zero(): Vector2 {
  1155. return new Vector2(0, 0);
  1156. }
  1157. /**
  1158. * Gets a new Vector2(1, 1)
  1159. * @returns a new Vector2
  1160. */
  1161. public static One(): Vector2 {
  1162. return new Vector2(1, 1);
  1163. }
  1164. /**
  1165. * Gets a new Vector2 set from the given index element of the given array
  1166. * @param array defines the data source
  1167. * @param offset defines the offset in the data source
  1168. * @returns a new Vector2
  1169. */
  1170. public static FromArray(array: ArrayLike<number>, offset: number = 0): Vector2 {
  1171. return new Vector2(array[offset], array[offset + 1]);
  1172. }
  1173. /**
  1174. * Sets "result" from the given index element of the given array
  1175. * @param array defines the data source
  1176. * @param offset defines the offset in the data source
  1177. * @param result defines the target vector
  1178. */
  1179. public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. }
  1183. /**
  1184. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  1185. * @param value1 defines 1st point of control
  1186. * @param value2 defines 2nd point of control
  1187. * @param value3 defines 3rd point of control
  1188. * @param value4 defines 4th point of control
  1189. * @param amount defines the interpolation factor
  1190. * @returns a new Vector2
  1191. */
  1192. public static CatmullRom(value1: Vector2, value2: Vector2, value3: Vector2, value4: Vector2, amount: number): Vector2 {
  1193. var squared = amount * amount;
  1194. var cubed = amount * squared;
  1195. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1196. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1197. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1198. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1199. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1200. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1201. return new Vector2(x, y);
  1202. }
  1203. /**
  1204. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1205. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1206. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  1207. * @param value defines the value to clamp
  1208. * @param min defines the lower limit
  1209. * @param max defines the upper limit
  1210. * @returns a new Vector2
  1211. */
  1212. public static Clamp(value: Vector2, min: Vector2, max: Vector2): Vector2 {
  1213. var x = value.x;
  1214. x = (x > max.x) ? max.x : x;
  1215. x = (x < min.x) ? min.x : x;
  1216. var y = value.y;
  1217. y = (y > max.y) ? max.y : y;
  1218. y = (y < min.y) ? min.y : y;
  1219. return new Vector2(x, y);
  1220. }
  1221. /**
  1222. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  1223. * @param value1 defines the 1st control point
  1224. * @param tangent1 defines the outgoing tangent
  1225. * @param value2 defines the 2nd control point
  1226. * @param tangent2 defines the incoming tangent
  1227. * @param amount defines the interpolation factor
  1228. * @returns a new Vector2
  1229. */
  1230. public static Hermite(value1: Vector2, tangent1: Vector2, value2: Vector2, tangent2: Vector2, amount: number): Vector2 {
  1231. var squared = amount * amount;
  1232. var cubed = amount * squared;
  1233. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1234. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1235. var part3 = (cubed - (2.0 * squared)) + amount;
  1236. var part4 = cubed - squared;
  1237. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1238. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1239. return new Vector2(x, y);
  1240. }
  1241. /**
  1242. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1243. * @param start defines the start vector
  1244. * @param end defines the end vector
  1245. * @param amount defines the interpolation factor
  1246. * @returns a new Vector2
  1247. */
  1248. public static Lerp(start: Vector2, end: Vector2, amount: number): Vector2 {
  1249. var x = start.x + ((end.x - start.x) * amount);
  1250. var y = start.y + ((end.y - start.y) * amount);
  1251. return new Vector2(x, y);
  1252. }
  1253. /**
  1254. * Gets the dot product of the vector "left" and the vector "right"
  1255. * @param left defines first vector
  1256. * @param right defines second vector
  1257. * @returns the dot product (float)
  1258. */
  1259. public static Dot(left: Vector2, right: Vector2): number {
  1260. return left.x * right.x + left.y * right.y;
  1261. }
  1262. /**
  1263. * Returns a new Vector2 equal to the normalized given vector
  1264. * @param vector defines the vector to normalize
  1265. * @returns a new Vector2
  1266. */
  1267. public static Normalize(vector: Vector2): Vector2 {
  1268. var newVector = vector.clone();
  1269. newVector.normalize();
  1270. return newVector;
  1271. }
  1272. /**
  1273. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  1274. * @param left defines 1st vector
  1275. * @param right defines 2nd vector
  1276. * @returns a new Vector2
  1277. */
  1278. public static Minimize(left: Vector2, right: Vector2): Vector2 {
  1279. var x = (left.x < right.x) ? left.x : right.x;
  1280. var y = (left.y < right.y) ? left.y : right.y;
  1281. return new Vector2(x, y);
  1282. }
  1283. /**
  1284. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  1285. * @param left defines 1st vector
  1286. * @param right defines 2nd vector
  1287. * @returns a new Vector2
  1288. */
  1289. public static Maximize(left: Vector2, right: Vector2): Vector2 {
  1290. var x = (left.x > right.x) ? left.x : right.x;
  1291. var y = (left.y > right.y) ? left.y : right.y;
  1292. return new Vector2(x, y);
  1293. }
  1294. /**
  1295. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  1296. * @param vector defines the vector to transform
  1297. * @param transformation defines the matrix to apply
  1298. * @returns a new Vector2
  1299. */
  1300. public static Transform(vector: Vector2, transformation: Matrix): Vector2 {
  1301. let r = Vector2.Zero();
  1302. Vector2.TransformToRef(vector, transformation, r);
  1303. return r;
  1304. }
  1305. /**
  1306. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  1307. * @param vector defines the vector to transform
  1308. * @param transformation defines the matrix to apply
  1309. * @param result defines the target vector
  1310. */
  1311. public static TransformToRef(vector: Vector2, transformation: Matrix, result: Vector2) {
  1312. const m = transformation.m;
  1313. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  1314. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  1315. result.x = x;
  1316. result.y = y;
  1317. }
  1318. /**
  1319. * Determines if a given vector is included in a triangle
  1320. * @param p defines the vector to test
  1321. * @param p0 defines 1st triangle point
  1322. * @param p1 defines 2nd triangle point
  1323. * @param p2 defines 3rd triangle point
  1324. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1325. */
  1326. public static PointInTriangle(p: Vector2, p0: Vector2, p1: Vector2, p2: Vector2) {
  1327. let a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1328. let sign = a < 0 ? -1 : 1;
  1329. let s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1330. let t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1331. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1332. }
  1333. /**
  1334. * Gets the distance between the vectors "value1" and "value2"
  1335. * @param value1 defines first vector
  1336. * @param value2 defines second vector
  1337. * @returns the distance between vectors
  1338. */
  1339. public static Distance(value1: Vector2, value2: Vector2): number {
  1340. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1341. }
  1342. /**
  1343. * Returns the squared distance between the vectors "value1" and "value2"
  1344. * @param value1 defines first vector
  1345. * @param value2 defines second vector
  1346. * @returns the squared distance between vectors
  1347. */
  1348. public static DistanceSquared(value1: Vector2, value2: Vector2): number {
  1349. var x = value1.x - value2.x;
  1350. var y = value1.y - value2.y;
  1351. return (x * x) + (y * y);
  1352. }
  1353. /**
  1354. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  1355. * @param value1 defines first vector
  1356. * @param value2 defines second vector
  1357. * @returns a new Vector2
  1358. */
  1359. public static Center(value1: Vector2, value2: Vector2): Vector2 {
  1360. var center = value1.add(value2);
  1361. center.scaleInPlace(0.5);
  1362. return center;
  1363. }
  1364. /**
  1365. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1366. * @param p defines the middle point
  1367. * @param segA defines one point of the segment
  1368. * @param segB defines the other point of the segment
  1369. * @returns the shortest distance
  1370. */
  1371. public static DistanceOfPointFromSegment(p: Vector2, segA: Vector2, segB: Vector2): number {
  1372. let l2 = Vector2.DistanceSquared(segA, segB);
  1373. if (l2 === 0.0) {
  1374. return Vector2.Distance(p, segA);
  1375. }
  1376. let v = segB.subtract(segA);
  1377. let t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1378. let proj = segA.add(v.multiplyByFloats(t, t));
  1379. return Vector2.Distance(p, proj);
  1380. }
  1381. }
  1382. /**
  1383. * Classed used to store (x,y,z) vector representation
  1384. * A Vector3 is the main object used in 3D geometry
  1385. * It can represent etiher the coordinates of a point the space, either a direction
  1386. * Reminder: js uses a left handed forward facing system
  1387. */
  1388. export class Vector3 {
  1389. /**
  1390. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  1391. * @param x defines the first coordinates (on X axis)
  1392. * @param y defines the second coordinates (on Y axis)
  1393. * @param z defines the third coordinates (on Z axis)
  1394. */
  1395. constructor(
  1396. /**
  1397. * Defines the first coordinates (on X axis)
  1398. */
  1399. public x: number = 0,
  1400. /**
  1401. * Defines the second coordinates (on Y axis)
  1402. */
  1403. public y: number = 0,
  1404. /**
  1405. * Defines the third coordinates (on Z axis)
  1406. */
  1407. public z: number = 0
  1408. ) {
  1409. }
  1410. /**
  1411. * Creates a string representation of the Vector3
  1412. * @returns a string with the Vector3 coordinates.
  1413. */
  1414. public toString(): string {
  1415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1416. }
  1417. /**
  1418. * Gets the class name
  1419. * @returns the string "Vector3"
  1420. */
  1421. public getClassName(): string {
  1422. return "Vector3";
  1423. }
  1424. /**
  1425. * Creates the Vector3 hash code
  1426. * @returns a number which tends to be unique between Vector3 instances
  1427. */
  1428. public getHashCode(): number {
  1429. let hash = this.x || 0;
  1430. hash = (hash * 397) ^ (this.y || 0);
  1431. hash = (hash * 397) ^ (this.z || 0);
  1432. return hash;
  1433. }
  1434. // Operators
  1435. /**
  1436. * Creates an array containing three elements : the coordinates of the Vector3
  1437. * @returns a new array of numbers
  1438. */
  1439. public asArray(): number[] {
  1440. var result: number[] = [];
  1441. this.toArray(result, 0);
  1442. return result;
  1443. }
  1444. /**
  1445. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  1446. * @param array defines the destination array
  1447. * @param index defines the offset in the destination array
  1448. * @returns the current Vector3
  1449. */
  1450. public toArray(array: FloatArray, index: number = 0): Vector3 {
  1451. array[index] = this.x;
  1452. array[index + 1] = this.y;
  1453. array[index + 2] = this.z;
  1454. return this;
  1455. }
  1456. /**
  1457. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  1458. * @returns a new Quaternion object, computed from the Vector3 coordinates
  1459. */
  1460. public toQuaternion(): Quaternion {
  1461. return Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  1462. }
  1463. /**
  1464. * Adds the given vector to the current Vector3
  1465. * @param otherVector defines the second operand
  1466. * @returns the current updated Vector3
  1467. */
  1468. public addInPlace(otherVector: Vector3): Vector3 {
  1469. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  1470. }
  1471. /**
  1472. * Adds the given coordinates to the current Vector3
  1473. * @param x defines the x coordinate of the operand
  1474. * @param y defines the y coordinate of the operand
  1475. * @param z defines the z coordinate of the operand
  1476. * @returns the current updated Vector3
  1477. */
  1478. public addInPlaceFromFloats(x: number, y: number, z: number): Vector3 {
  1479. this.x += x;
  1480. this.y += y;
  1481. this.z += z;
  1482. return this;
  1483. }
  1484. /**
  1485. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  1486. * @param otherVector defines the second operand
  1487. * @returns the resulting Vector3
  1488. */
  1489. public add(otherVector: Vector3): Vector3 {
  1490. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1491. }
  1492. /**
  1493. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  1494. * @param otherVector defines the second operand
  1495. * @param result defines the Vector3 object where to store the result
  1496. * @returns the current Vector3
  1497. */
  1498. public addToRef(otherVector: Vector3, result: Vector3): Vector3 {
  1499. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1500. }
  1501. /**
  1502. * Subtract the given vector from the current Vector3
  1503. * @param otherVector defines the second operand
  1504. * @returns the current updated Vector3
  1505. */
  1506. public subtractInPlace(otherVector: Vector3): Vector3 {
  1507. this.x -= otherVector.x;
  1508. this.y -= otherVector.y;
  1509. this.z -= otherVector.z;
  1510. return this;
  1511. }
  1512. /**
  1513. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  1514. * @param otherVector defines the second operand
  1515. * @returns the resulting Vector3
  1516. */
  1517. public subtract(otherVector: Vector3): Vector3 {
  1518. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1519. }
  1520. /**
  1521. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  1522. * @param otherVector defines the second operand
  1523. * @param result defines the Vector3 object where to store the result
  1524. * @returns the current Vector3
  1525. */
  1526. public subtractToRef(otherVector: Vector3, result: Vector3): Vector3 {
  1527. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  1528. }
  1529. /**
  1530. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  1531. * @param x defines the x coordinate of the operand
  1532. * @param y defines the y coordinate of the operand
  1533. * @param z defines the z coordinate of the operand
  1534. * @returns the resulting Vector3
  1535. */
  1536. public subtractFromFloats(x: number, y: number, z: number): Vector3 {
  1537. return new Vector3(this.x - x, this.y - y, this.z - z);
  1538. }
  1539. /**
  1540. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  1541. * @param x defines the x coordinate of the operand
  1542. * @param y defines the y coordinate of the operand
  1543. * @param z defines the z coordinate of the operand
  1544. * @param result defines the Vector3 object where to store the result
  1545. * @returns the current Vector3
  1546. */
  1547. public subtractFromFloatsToRef(x: number, y: number, z: number, result: Vector3): Vector3 {
  1548. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  1549. }
  1550. /**
  1551. * Gets a new Vector3 set with the current Vector3 negated coordinates
  1552. * @returns a new Vector3
  1553. */
  1554. public negate(): Vector3 {
  1555. return new Vector3(-this.x, -this.y, -this.z);
  1556. }
  1557. /**
  1558. * Multiplies the Vector3 coordinates by the float "scale"
  1559. * @param scale defines the multiplier factor
  1560. * @returns the current updated Vector3
  1561. */
  1562. public scaleInPlace(scale: number): Vector3 {
  1563. this.x *= scale;
  1564. this.y *= scale;
  1565. this.z *= scale;
  1566. return this;
  1567. }
  1568. /**
  1569. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  1570. * @param scale defines the multiplier factor
  1571. * @returns a new Vector3
  1572. */
  1573. public scale(scale: number): Vector3 {
  1574. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1575. }
  1576. /**
  1577. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  1578. * @param scale defines the multiplier factor
  1579. * @param result defines the Vector3 object where to store the result
  1580. * @returns the current Vector3
  1581. */
  1582. public scaleToRef(scale: number, result: Vector3): Vector3 {
  1583. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  1584. }
  1585. /**
  1586. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  1587. * @param scale defines the scale factor
  1588. * @param result defines the Vector3 object where to store the result
  1589. * @returns the unmodified current Vector3
  1590. */
  1591. public scaleAndAddToRef(scale: number, result: Vector3): Vector3 {
  1592. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  1593. }
  1594. /**
  1595. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  1596. * @param otherVector defines the second operand
  1597. * @returns true if both vectors are equals
  1598. */
  1599. public equals(otherVector: Vector3): boolean {
  1600. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1601. }
  1602. /**
  1603. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  1604. * @param otherVector defines the second operand
  1605. * @param epsilon defines the minimal distance to define values as equals
  1606. * @returns true if both vectors are distant less than epsilon
  1607. */
  1608. public equalsWithEpsilon(otherVector: Vector3, epsilon: number = Epsilon): boolean {
  1609. return otherVector && Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1610. }
  1611. /**
  1612. * Returns true if the current Vector3 coordinates equals the given floats
  1613. * @param x defines the x coordinate of the operand
  1614. * @param y defines the y coordinate of the operand
  1615. * @param z defines the z coordinate of the operand
  1616. * @returns true if both vectors are equals
  1617. */
  1618. public equalsToFloats(x: number, y: number, z: number): boolean {
  1619. return this.x === x && this.y === y && this.z === z;
  1620. }
  1621. /**
  1622. * Multiplies the current Vector3 coordinates by the given ones
  1623. * @param otherVector defines the second operand
  1624. * @returns the current updated Vector3
  1625. */
  1626. public multiplyInPlace(otherVector: Vector3): Vector3 {
  1627. this.x *= otherVector.x;
  1628. this.y *= otherVector.y;
  1629. this.z *= otherVector.z;
  1630. return this;
  1631. }
  1632. /**
  1633. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  1634. * @param otherVector defines the second operand
  1635. * @returns the new Vector3
  1636. */
  1637. public multiply(otherVector: Vector3): Vector3 {
  1638. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  1639. }
  1640. /**
  1641. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  1642. * @param otherVector defines the second operand
  1643. * @param result defines the Vector3 object where to store the result
  1644. * @returns the current Vector3
  1645. */
  1646. public multiplyToRef(otherVector: Vector3, result: Vector3): Vector3 {
  1647. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1648. }
  1649. /**
  1650. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  1651. * @param x defines the x coordinate of the operand
  1652. * @param y defines the y coordinate of the operand
  1653. * @param z defines the z coordinate of the operand
  1654. * @returns the new Vector3
  1655. */
  1656. public multiplyByFloats(x: number, y: number, z: number): Vector3 {
  1657. return new Vector3(this.x * x, this.y * y, this.z * z);
  1658. }
  1659. /**
  1660. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  1661. * @param otherVector defines the second operand
  1662. * @returns the new Vector3
  1663. */
  1664. public divide(otherVector: Vector3): Vector3 {
  1665. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1666. }
  1667. /**
  1668. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  1669. * @param otherVector defines the second operand
  1670. * @param result defines the Vector3 object where to store the result
  1671. * @returns the current Vector3
  1672. */
  1673. public divideToRef(otherVector: Vector3, result: Vector3): Vector3 {
  1674. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1675. }
  1676. /**
  1677. * Divides the current Vector3 coordinates by the given ones.
  1678. * @param otherVector defines the second operand
  1679. * @returns the current updated Vector3
  1680. */
  1681. public divideInPlace(otherVector: Vector3): Vector3 {
  1682. return this.divideToRef(otherVector, this);
  1683. }
  1684. /**
  1685. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  1686. * @param other defines the second operand
  1687. * @returns the current updated Vector3
  1688. */
  1689. public minimizeInPlace(other: Vector3): Vector3 {
  1690. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  1691. }
  1692. /**
  1693. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  1694. * @param other defines the second operand
  1695. * @returns the current updated Vector3
  1696. */
  1697. public maximizeInPlace(other: Vector3): Vector3 {
  1698. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  1699. }
  1700. /**
  1701. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  1702. * @param x defines the x coordinate of the operand
  1703. * @param y defines the y coordinate of the operand
  1704. * @param z defines the z coordinate of the operand
  1705. * @returns the current updated Vector3
  1706. */
  1707. public minimizeInPlaceFromFloats(x: number, y: number, z: number): Vector3 {
  1708. if (x < this.x) { this.x = x; }
  1709. if (y < this.y) { this.y = y; }
  1710. if (z < this.z) { this.z = z; }
  1711. return this;
  1712. }
  1713. /**
  1714. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  1715. * @param x defines the x coordinate of the operand
  1716. * @param y defines the y coordinate of the operand
  1717. * @param z defines the z coordinate of the operand
  1718. * @returns the current updated Vector3
  1719. */
  1720. public maximizeInPlaceFromFloats(x: number, y: number, z: number): Vector3 {
  1721. if (x > this.x) { this.x = x; }
  1722. if (y > this.y) { this.y = y; }
  1723. if (z > this.z) { this.z = z; }
  1724. return this;
  1725. }
  1726. /**
  1727. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  1728. */
  1729. public get isNonUniform(): boolean {
  1730. let absX = Math.abs(this.x);
  1731. let absY = Math.abs(this.y);
  1732. if (absX !== absY) {
  1733. return true;
  1734. }
  1735. let absZ = Math.abs(this.z);
  1736. if (absX !== absZ) {
  1737. return true;
  1738. }
  1739. if (absY !== absZ) {
  1740. return true;
  1741. }
  1742. return false;
  1743. }
  1744. /**
  1745. * Gets a new Vector3 from current Vector3 floored values
  1746. * @returns a new Vector3
  1747. */
  1748. public floor(): Vector3 {
  1749. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  1750. }
  1751. /**
  1752. * Gets a new Vector3 from current Vector3 floored values
  1753. * @returns a new Vector3
  1754. */
  1755. public fract(): Vector3 {
  1756. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  1757. }
  1758. // Properties
  1759. /**
  1760. * Gets the length of the Vector3
  1761. * @returns the length of the Vecto3
  1762. */
  1763. public length(): number {
  1764. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1765. }
  1766. /**
  1767. * Gets the squared length of the Vector3
  1768. * @returns squared length of the Vector3
  1769. */
  1770. public lengthSquared(): number {
  1771. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1772. }
  1773. /**
  1774. * Normalize the current Vector3.
  1775. * Please note that this is an in place operation.
  1776. * @returns the current updated Vector3
  1777. */
  1778. public normalize(): Vector3 {
  1779. return this.normalizeFromLength(this.length());
  1780. }
  1781. /**
  1782. * Reorders the x y z properties of the vector in place
  1783. * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1)
  1784. * @returns the current updated vector
  1785. */
  1786. public reorderInPlace(order: string) {
  1787. order = order.toLowerCase();
  1788. if (order === "xyz") {
  1789. return this;
  1790. }
  1791. MathTmp.Vector3[0].copyFrom(this);
  1792. ["x", "y", "z"].forEach((val, i) => {
  1793. (<any>this)[val] = (<any>MathTmp.Vector3[0])[order[i]];
  1794. });
  1795. return this;
  1796. }
  1797. /**
  1798. * Rotates the vector around 0,0,0 by a quaternion
  1799. * @param quaternion the rotation quaternion
  1800. * @param result vector to store the result
  1801. * @returns the resulting vector
  1802. */
  1803. public rotateByQuaternionToRef(quaternion: Quaternion, result: Vector3) {
  1804. quaternion.toRotationMatrix(MathTmp.Matrix[0]);
  1805. Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result);
  1806. return result;
  1807. }
  1808. /**
  1809. * Rotates a vector around a given point
  1810. * @param quaternion the rotation quaternion
  1811. * @param point the point to rotate around
  1812. * @param result vector to store the result
  1813. * @returns the resulting vector
  1814. */
  1815. public rotateByQuaternionAroundPointToRef(quaternion: Quaternion, point: Vector3, result: Vector3) {
  1816. this.subtractToRef(point, MathTmp.Vector3[0]);
  1817. MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]);
  1818. point.addToRef(MathTmp.Vector3[0], result);
  1819. return result;
  1820. }
  1821. /**
  1822. * Normalize the current Vector3 with the given input length.
  1823. * Please note that this is an in place operation.
  1824. * @param len the length of the vector
  1825. * @returns the current updated Vector3
  1826. */
  1827. public normalizeFromLength(len: number): Vector3 {
  1828. if (len === 0 || len === 1.0) {
  1829. return this;
  1830. }
  1831. return this.scaleInPlace(1.0 / len);
  1832. }
  1833. /**
  1834. * Normalize the current Vector3 to a new vector
  1835. * @returns the new Vector3
  1836. */
  1837. public normalizeToNew(): Vector3 {
  1838. const normalized = new Vector3(0, 0, 0);
  1839. this.normalizeToRef(normalized);
  1840. return normalized;
  1841. }
  1842. /**
  1843. * Normalize the current Vector3 to the reference
  1844. * @param reference define the Vector3 to update
  1845. * @returns the updated Vector3
  1846. */
  1847. public normalizeToRef(reference: Vector3): Vector3 {
  1848. var len = this.length();
  1849. if (len === 0 || len === 1.0) {
  1850. return reference.copyFromFloats(this.x, this.y, this.z);
  1851. }
  1852. return this.scaleToRef(1.0 / len, reference);
  1853. }
  1854. /**
  1855. * Creates a new Vector3 copied from the current Vector3
  1856. * @returns the new Vector3
  1857. */
  1858. public clone(): Vector3 {
  1859. return new Vector3(this.x, this.y, this.z);
  1860. }
  1861. /**
  1862. * Copies the given vector coordinates to the current Vector3 ones
  1863. * @param source defines the source Vector3
  1864. * @returns the current updated Vector3
  1865. */
  1866. public copyFrom(source: Vector3): Vector3 {
  1867. return this.copyFromFloats(source.x, source.y, source.z);
  1868. }
  1869. /**
  1870. * Copies the given floats to the current Vector3 coordinates
  1871. * @param x defines the x coordinate of the operand
  1872. * @param y defines the y coordinate of the operand
  1873. * @param z defines the z coordinate of the operand
  1874. * @returns the current updated Vector3
  1875. */
  1876. public copyFromFloats(x: number, y: number, z: number): Vector3 {
  1877. this.x = x;
  1878. this.y = y;
  1879. this.z = z;
  1880. return this;
  1881. }
  1882. /**
  1883. * Copies the given floats to the current Vector3 coordinates
  1884. * @param x defines the x coordinate of the operand
  1885. * @param y defines the y coordinate of the operand
  1886. * @param z defines the z coordinate of the operand
  1887. * @returns the current updated Vector3
  1888. */
  1889. public set(x: number, y: number, z: number): Vector3 {
  1890. return this.copyFromFloats(x, y, z);
  1891. }
  1892. /**
  1893. * Copies the given float to the current Vector3 coordinates
  1894. * @param v defines the x, y and z coordinates of the operand
  1895. * @returns the current updated Vector3
  1896. */
  1897. public setAll(v: number): Vector3 {
  1898. this.x = this.y = this.z = v;
  1899. return this;
  1900. }
  1901. // Statics
  1902. /**
  1903. * Get the clip factor between two vectors
  1904. * @param vector0 defines the first operand
  1905. * @param vector1 defines the second operand
  1906. * @param axis defines the axis to use
  1907. * @param size defines the size along the axis
  1908. * @returns the clip factor
  1909. */
  1910. public static GetClipFactor(vector0: Vector3, vector1: Vector3, axis: Vector3, size: number) {
  1911. var d0 = Vector3.Dot(vector0, axis) - size;
  1912. var d1 = Vector3.Dot(vector1, axis) - size;
  1913. var s = d0 / (d0 - d1);
  1914. return s;
  1915. }
  1916. /**
  1917. * Get angle between two vectors
  1918. * @param vector0 angle between vector0 and vector1
  1919. * @param vector1 angle between vector0 and vector1
  1920. * @param normal direction of the normal
  1921. * @return the angle between vector0 and vector1
  1922. */
  1923. public static GetAngleBetweenVectors(vector0: Vector3, vector1: Vector3, normal: Vector3): number {
  1924. const v0: Vector3 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  1925. const v1: Vector3 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  1926. const dot: number = Vector3.Dot(v0, v1);
  1927. const n = MathTmp.Vector3[3];
  1928. Vector3.CrossToRef(v0, v1, n);
  1929. if (Vector3.Dot(n, normal) > 0) {
  1930. return Math.acos(dot);
  1931. }
  1932. return -Math.acos(dot);
  1933. }
  1934. /**
  1935. * Returns a new Vector3 set from the index "offset" of the given array
  1936. * @param array defines the source array
  1937. * @param offset defines the offset in the source array
  1938. * @returns the new Vector3
  1939. */
  1940. public static FromArray(array: ArrayLike<number>, offset: number = 0): Vector3 {
  1941. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1942. }
  1943. /**
  1944. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  1945. * This function is deprecated. Use FromArray instead
  1946. * @param array defines the source array
  1947. * @param offset defines the offset in the source array
  1948. * @returns the new Vector3
  1949. */
  1950. public static FromFloatArray(array: Float32Array, offset?: number): Vector3 {
  1951. return Vector3.FromArray(array, offset);
  1952. }
  1953. /**
  1954. * Sets the given vector "result" with the element values from the index "offset" of the given array
  1955. * @param array defines the source array
  1956. * @param offset defines the offset in the source array
  1957. * @param result defines the Vector3 where to store the result
  1958. */
  1959. public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector3): void {
  1960. result.x = array[offset];
  1961. result.y = array[offset + 1];
  1962. result.z = array[offset + 2];
  1963. }
  1964. /**
  1965. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  1966. * This function is deprecated. Use FromArrayToRef instead.
  1967. * @param array defines the source array
  1968. * @param offset defines the offset in the source array
  1969. * @param result defines the Vector3 where to store the result
  1970. */
  1971. public static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector3): void {
  1972. return Vector3.FromArrayToRef(array, offset, result);
  1973. }
  1974. /**
  1975. * Sets the given vector "result" with the given floats.
  1976. * @param x defines the x coordinate of the source
  1977. * @param y defines the y coordinate of the source
  1978. * @param z defines the z coordinate of the source
  1979. * @param result defines the Vector3 where to store the result
  1980. */
  1981. public static FromFloatsToRef(x: number, y: number, z: number, result: Vector3): void {
  1982. result.copyFromFloats(x, y, z);
  1983. }
  1984. /**
  1985. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  1986. * @returns a new empty Vector3
  1987. */
  1988. public static Zero(): Vector3 {
  1989. return new Vector3(0.0, 0.0, 0.0);
  1990. }
  1991. /**
  1992. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  1993. * @returns a new unit Vector3
  1994. */
  1995. public static One(): Vector3 {
  1996. return new Vector3(1.0, 1.0, 1.0);
  1997. }
  1998. /**
  1999. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2000. * @returns a new up Vector3
  2001. */
  2002. public static Up(): Vector3 {
  2003. return new Vector3(0.0, 1.0, 0.0);
  2004. }
  2005. /**
  2006. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  2007. * @returns a new down Vector3
  2008. */
  2009. public static Down(): Vector3 {
  2010. return new Vector3(0.0, -1.0, 0.0);
  2011. }
  2012. /**
  2013. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2014. * @returns a new forward Vector3
  2015. */
  2016. public static Forward(): Vector3 {
  2017. return new Vector3(0.0, 0.0, 1.0);
  2018. }
  2019. /**
  2020. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  2021. * @returns a new forward Vector3
  2022. */
  2023. public static Backward(): Vector3 {
  2024. return new Vector3(0.0, 0.0, -1.0);
  2025. }
  2026. /**
  2027. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2028. * @returns a new right Vector3
  2029. */
  2030. public static Right(): Vector3 {
  2031. return new Vector3(1.0, 0.0, 0.0);
  2032. }
  2033. /**
  2034. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2035. * @returns a new left Vector3
  2036. */
  2037. public static Left(): Vector3 {
  2038. return new Vector3(-1.0, 0.0, 0.0);
  2039. }
  2040. /**
  2041. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  2042. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  2043. * @param vector defines the Vector3 to transform
  2044. * @param transformation defines the transformation matrix
  2045. * @returns the transformed Vector3
  2046. */
  2047. public static TransformCoordinates(vector: Vector3, transformation: Matrix): Vector3 {
  2048. var result = Vector3.Zero();
  2049. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2050. return result;
  2051. }
  2052. /**
  2053. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  2054. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  2055. * @param vector defines the Vector3 to transform
  2056. * @param transformation defines the transformation matrix
  2057. * @param result defines the Vector3 where to store the result
  2058. */
  2059. public static TransformCoordinatesToRef(vector: Vector3, transformation: Readonly<Matrix>, result: Vector3): void {
  2060. return Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  2061. }
  2062. /**
  2063. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  2064. * This method computes tranformed coordinates only, not transformed direction vectors
  2065. * @param x define the x coordinate of the source vector
  2066. * @param y define the y coordinate of the source vector
  2067. * @param z define the z coordinate of the source vector
  2068. * @param transformation defines the transformation matrix
  2069. * @param result defines the Vector3 where to store the result
  2070. */
  2071. public static TransformCoordinatesFromFloatsToRef(x: number, y: number, z: number, transformation: Readonly<Matrix>, result: Vector3): void {
  2072. const m = transformation.m;
  2073. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  2074. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  2075. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  2076. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  2077. result.x = rx * rw;
  2078. result.y = ry * rw;
  2079. result.z = rz * rw;
  2080. }
  2081. /**
  2082. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  2083. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  2084. * @param vector defines the Vector3 to transform
  2085. * @param transformation defines the transformation matrix
  2086. * @returns the new Vector3
  2087. */
  2088. public static TransformNormal(vector: Vector3, transformation: Matrix): Vector3 {
  2089. var result = Vector3.Zero();
  2090. Vector3.TransformNormalToRef(vector, transformation, result);
  2091. return result;
  2092. }
  2093. /**
  2094. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  2095. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  2096. * @param vector defines the Vector3 to transform
  2097. * @param transformation defines the transformation matrix
  2098. * @param result defines the Vector3 where to store the result
  2099. */
  2100. public static TransformNormalToRef(vector: Vector3, transformation: Readonly<Matrix>, result: Vector3): void {
  2101. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  2102. }
  2103. /**
  2104. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  2105. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  2106. * @param x define the x coordinate of the source vector
  2107. * @param y define the y coordinate of the source vector
  2108. * @param z define the z coordinate of the source vector
  2109. * @param transformation defines the transformation matrix
  2110. * @param result defines the Vector3 where to store the result
  2111. */
  2112. public static TransformNormalFromFloatsToRef(x: number, y: number, z: number, transformation: Readonly<Matrix>, result: Vector3): void {
  2113. const m = transformation.m;
  2114. result.x = x * m[0] + y * m[4] + z * m[8];
  2115. result.y = x * m[1] + y * m[5] + z * m[9];
  2116. result.z = x * m[2] + y * m[6] + z * m[10];
  2117. }
  2118. /**
  2119. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  2120. * @param value1 defines the first control point
  2121. * @param value2 defines the second control point
  2122. * @param value3 defines the third control point
  2123. * @param value4 defines the fourth control point
  2124. * @param amount defines the amount on the spline to use
  2125. * @returns the new Vector3
  2126. */
  2127. public static CatmullRom(value1: Vector3, value2: Vector3, value3: Vector3, value4: Vector3, amount: number): Vector3 {
  2128. var squared = amount * amount;
  2129. var cubed = amount * squared;
  2130. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2131. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2132. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2133. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2134. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2135. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2136. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2137. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2138. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2139. return new Vector3(x, y, z);
  2140. }
  2141. /**
  2142. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  2143. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  2144. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  2145. * @param value defines the current value
  2146. * @param min defines the lower range value
  2147. * @param max defines the upper range value
  2148. * @returns the new Vector3
  2149. */
  2150. public static Clamp(value: Vector3, min: Vector3, max: Vector3): Vector3 {
  2151. const v = new Vector3();
  2152. Vector3.ClampToRef(value, min, max, v);
  2153. return v;
  2154. }
  2155. /**
  2156. * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  2157. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  2158. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  2159. * @param value defines the current value
  2160. * @param min defines the lower range value
  2161. * @param max defines the upper range value
  2162. * @param result defines the Vector3 where to store the result
  2163. */
  2164. public static ClampToRef(value: Vector3, min: Vector3, max: Vector3, result: Vector3): void {
  2165. var x = value.x;
  2166. x = (x > max.x) ? max.x : x;
  2167. x = (x < min.x) ? min.x : x;
  2168. var y = value.y;
  2169. y = (y > max.y) ? max.y : y;
  2170. y = (y < min.y) ? min.y : y;
  2171. var z = value.z;
  2172. z = (z > max.z) ? max.z : z;
  2173. z = (z < min.z) ? min.z : z;
  2174. result.copyFromFloats(x, y, z);
  2175. }
  2176. /**
  2177. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  2178. * @param value1 defines the first control point
  2179. * @param tangent1 defines the first tangent vector
  2180. * @param value2 defines the second control point
  2181. * @param tangent2 defines the second tangent vector
  2182. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  2183. * @returns the new Vector3
  2184. */
  2185. public static Hermite(value1: Vector3, tangent1: Vector3, value2: Vector3, tangent2: Vector3, amount: number): Vector3 {
  2186. var squared = amount * amount;
  2187. var cubed = amount * squared;
  2188. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2189. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2190. var part3 = (cubed - (2.0 * squared)) + amount;
  2191. var part4 = cubed - squared;
  2192. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2193. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2194. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2195. return new Vector3(x, y, z);
  2196. }
  2197. /**
  2198. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  2199. * @param start defines the start value
  2200. * @param end defines the end value
  2201. * @param amount max defines amount between both (between 0 and 1)
  2202. * @returns the new Vector3
  2203. */
  2204. public static Lerp(start: Vector3, end: Vector3, amount: number): Vector3 {
  2205. var result = new Vector3(0, 0, 0);
  2206. Vector3.LerpToRef(start, end, amount, result);
  2207. return result;
  2208. }
  2209. /**
  2210. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  2211. * @param start defines the start value
  2212. * @param end defines the end value
  2213. * @param amount max defines amount between both (between 0 and 1)
  2214. * @param result defines the Vector3 where to store the result
  2215. */
  2216. public static LerpToRef(start: Vector3, end: Vector3, amount: number, result: Vector3): void {
  2217. result.x = start.x + ((end.x - start.x) * amount);
  2218. result.y = start.y + ((end.y - start.y) * amount);
  2219. result.z = start.z + ((end.z - start.z) * amount);
  2220. }
  2221. /**
  2222. * Returns the dot product (float) between the vectors "left" and "right"
  2223. * @param left defines the left operand
  2224. * @param right defines the right operand
  2225. * @returns the dot product
  2226. */
  2227. public static Dot(left: Vector3, right: Vector3): number {
  2228. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2229. }
  2230. /**
  2231. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  2232. * The cross product is then orthogonal to both "left" and "right"
  2233. * @param left defines the left operand
  2234. * @param right defines the right operand
  2235. * @returns the cross product
  2236. */
  2237. public static Cross(left: Vector3, right: Vector3): Vector3 {
  2238. var result = Vector3.Zero();
  2239. Vector3.CrossToRef(left, right, result);
  2240. return result;
  2241. }
  2242. /**
  2243. * Sets the given vector "result" with the cross product of "left" and "right"
  2244. * The cross product is then orthogonal to both "left" and "right"
  2245. * @param left defines the left operand
  2246. * @param right defines the right operand
  2247. * @param result defines the Vector3 where to store the result
  2248. */
  2249. public static CrossToRef(left: Vector3, right: Vector3, result: Vector3): void {
  2250. const x = left.y * right.z - left.z * right.y;
  2251. const y = left.z * right.x - left.x * right.z;
  2252. const z = left.x * right.y - left.y * right.x;
  2253. result.copyFromFloats(x, y, z);
  2254. }
  2255. /**
  2256. * Returns a new Vector3 as the normalization of the given vector
  2257. * @param vector defines the Vector3 to normalize
  2258. * @returns the new Vector3
  2259. */
  2260. public static Normalize(vector: Vector3): Vector3 {
  2261. var result = Vector3.Zero();
  2262. Vector3.NormalizeToRef(vector, result);
  2263. return result;
  2264. }
  2265. /**
  2266. * Sets the given vector "result" with the normalization of the given first vector
  2267. * @param vector defines the Vector3 to normalize
  2268. * @param result defines the Vector3 where to store the result
  2269. */
  2270. public static NormalizeToRef(vector: Vector3, result: Vector3): void {
  2271. vector.normalizeToRef(result);
  2272. }
  2273. /**
  2274. * Project a Vector3 onto screen space
  2275. * @param vector defines the Vector3 to project
  2276. * @param world defines the world matrix to use
  2277. * @param transform defines the transform (view x projection) matrix to use
  2278. * @param viewport defines the screen viewport to use
  2279. * @returns the new Vector3
  2280. */
  2281. public static Project(vector: Vector3, world: Matrix, transform: Matrix, viewport: Viewport): Vector3 {
  2282. var cw = viewport.width;
  2283. var ch = viewport.height;
  2284. var cx = viewport.x;
  2285. var cy = viewport.y;
  2286. var viewportMatrix = MathTmp.Matrix[1];
  2287. Matrix.FromValuesToRef(
  2288. cw / 2.0, 0, 0, 0,
  2289. 0, -ch / 2.0, 0, 0,
  2290. 0, 0, 0.5, 0,
  2291. cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  2292. var matrix = MathTmp.Matrix[0];
  2293. world.multiplyToRef(transform, matrix);
  2294. matrix.multiplyToRef(viewportMatrix, matrix);
  2295. return Vector3.TransformCoordinates(vector, matrix);
  2296. }
  2297. /** @hidden */
  2298. private static UnprojectFromInvertedMatrixToRef(source: Vector3, matrix: Readonly<Matrix>, result: Vector3) {
  2299. Vector3.TransformCoordinatesToRef(source, matrix, result);
  2300. const m = matrix.m;
  2301. var num = source.x * m[3] + source.y * m[7] + source.z * m[11] + m[15];
  2302. if (Scalar.WithinEpsilon(num, 1.0)) {
  2303. result.scaleInPlace(1.0 / num);
  2304. }
  2305. }
  2306. /**
  2307. * Unproject from screen space to object space
  2308. * @param source defines the screen space Vector3 to use
  2309. * @param viewportWidth defines the current width of the viewport
  2310. * @param viewportHeight defines the current height of the viewport
  2311. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  2312. * @param transform defines the transform (view x projection) matrix to use
  2313. * @returns the new Vector3
  2314. */
  2315. public static UnprojectFromTransform(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, transform: Matrix): Vector3 {
  2316. var matrix = MathTmp.Matrix[0];
  2317. world.multiplyToRef(transform, matrix);
  2318. matrix.invert();
  2319. source.x = source.x / viewportWidth * 2 - 1;
  2320. source.y = -(source.y / viewportHeight * 2 - 1);
  2321. const vector = new Vector3();
  2322. Vector3.UnprojectFromInvertedMatrixToRef(source, matrix, vector);
  2323. return vector;
  2324. }
  2325. /**
  2326. * Unproject from screen space to object space
  2327. * @param source defines the screen space Vector3 to use
  2328. * @param viewportWidth defines the current width of the viewport
  2329. * @param viewportHeight defines the current height of the viewport
  2330. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  2331. * @param view defines the view matrix to use
  2332. * @param projection defines the projection matrix to use
  2333. * @returns the new Vector3
  2334. */
  2335. public static Unproject(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Vector3 {
  2336. let result = Vector3.Zero();
  2337. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2338. return result;
  2339. }
  2340. /**
  2341. * Unproject from screen space to object space
  2342. * @param source defines the screen space Vector3 to use
  2343. * @param viewportWidth defines the current width of the viewport
  2344. * @param viewportHeight defines the current height of the viewport
  2345. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  2346. * @param view defines the view matrix to use
  2347. * @param projection defines the projection matrix to use
  2348. * @param result defines the Vector3 where to store the result
  2349. */
  2350. public static UnprojectToRef(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix, result: Vector3): void {
  2351. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2352. }
  2353. /**
  2354. * Unproject from screen space to object space
  2355. * @param sourceX defines the screen space x coordinate to use
  2356. * @param sourceY defines the screen space y coordinate to use
  2357. * @param sourceZ defines the screen space z coordinate to use
  2358. * @param viewportWidth defines the current width of the viewport
  2359. * @param viewportHeight defines the current height of the viewport
  2360. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  2361. * @param view defines the view matrix to use
  2362. * @param projection defines the projection matrix to use
  2363. * @param result defines the Vector3 where to store the result
  2364. */
  2365. public static UnprojectFloatsToRef(sourceX: float, sourceY: float, sourceZ: float, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix, result: Vector3): void {
  2366. var matrix = MathTmp.Matrix[0];
  2367. world.multiplyToRef(view, matrix);
  2368. matrix.multiplyToRef(projection, matrix);
  2369. matrix.invert();
  2370. var screenSource = MathTmp.Vector3[0];
  2371. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2372. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2373. screenSource.z = 2 * sourceZ - 1.0;
  2374. Vector3.UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
  2375. }
  2376. /**
  2377. * Unproject a ray from screen space to object space
  2378. * @param sourceX defines the screen space x coordinate to use
  2379. * @param sourceY defines the screen space y coordinate to use
  2380. * @param viewportWidth defines the current width of the viewport
  2381. * @param viewportHeight defines the current height of the viewport
  2382. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  2383. * @param view defines the view matrix to use
  2384. * @param projection defines the projection matrix to use
  2385. * @param ray defines the Ray where to store the result
  2386. */
  2387. public static UnprojectRayToRef(sourceX: float, sourceY: float, viewportWidth: number, viewportHeight: number, world: Readonly<Matrix>, view: Readonly<Matrix>, projection: Readonly<Matrix>, ray: Ray): void {
  2388. var matrix = MathTmp.Matrix[0];
  2389. world.multiplyToRef(view, matrix);
  2390. matrix.multiplyToRef(projection, matrix);
  2391. matrix.invert();
  2392. var nearScreenSource = MathTmp.Vector3[0];
  2393. nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
  2394. nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2395. nearScreenSource.z = -1.0;
  2396. var farScreenSource = MathTmp.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
  2397. const nearVec3 = MathTmp.Vector3[2];
  2398. const farVec3 = MathTmp.Vector3[3];
  2399. Vector3.UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
  2400. Vector3.UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
  2401. ray.origin.copyFrom(nearVec3);
  2402. farVec3.subtractToRef(nearVec3, ray.direction);
  2403. ray.direction.normalize();
  2404. }
  2405. /**
  2406. * Gets the minimal coordinate values between two Vector3
  2407. * @param left defines the first operand
  2408. * @param right defines the second operand
  2409. * @returns the new Vector3
  2410. */
  2411. public static Minimize(left: Vector3, right: Vector3): Vector3 {
  2412. var min = left.clone();
  2413. min.minimizeInPlace(right);
  2414. return min;
  2415. }
  2416. /**
  2417. * Gets the maximal coordinate values between two Vector3
  2418. * @param left defines the first operand
  2419. * @param right defines the second operand
  2420. * @returns the new Vector3
  2421. */
  2422. public static Maximize(left: Vector3, right: Vector3): Vector3 {
  2423. var max = left.clone();
  2424. max.maximizeInPlace(right);
  2425. return max;
  2426. }
  2427. /**
  2428. * Returns the distance between the vectors "value1" and "value2"
  2429. * @param value1 defines the first operand
  2430. * @param value2 defines the second operand
  2431. * @returns the distance
  2432. */
  2433. public static Distance(value1: Vector3, value2: Vector3): number {
  2434. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2435. }
  2436. /**
  2437. * Returns the squared distance between the vectors "value1" and "value2"
  2438. * @param value1 defines the first operand
  2439. * @param value2 defines the second operand
  2440. * @returns the squared distance
  2441. */
  2442. public static DistanceSquared(value1: Vector3, value2: Vector3): number {
  2443. var x = value1.x - value2.x;
  2444. var y = value1.y - value2.y;
  2445. var z = value1.z - value2.z;
  2446. return (x * x) + (y * y) + (z * z);
  2447. }
  2448. /**
  2449. * Returns a new Vector3 located at the center between "value1" and "value2"
  2450. * @param value1 defines the first operand
  2451. * @param value2 defines the second operand
  2452. * @returns the new Vector3
  2453. */
  2454. public static Center(value1: Vector3, value2: Vector3): Vector3 {
  2455. var center = value1.add(value2);
  2456. center.scaleInPlace(0.5);
  2457. return center;
  2458. }
  2459. /**
  2460. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2461. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2462. * to something in order to rotate it from its local system to the given target system
  2463. * Note: axis1, axis2 and axis3 are normalized during this operation
  2464. * @param axis1 defines the first axis
  2465. * @param axis2 defines the second axis
  2466. * @param axis3 defines the third axis
  2467. * @returns a new Vector3
  2468. */
  2469. public static RotationFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Vector3 {
  2470. var rotation = Vector3.Zero();
  2471. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2472. return rotation;
  2473. }
  2474. /**
  2475. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  2476. * @param axis1 defines the first axis
  2477. * @param axis2 defines the second axis
  2478. * @param axis3 defines the third axis
  2479. * @param ref defines the Vector3 where to store the result
  2480. */
  2481. public static RotationFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Vector3): void {
  2482. var quat = MathTmp.Quaternion[0];
  2483. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2484. quat.toEulerAnglesToRef(ref);
  2485. }
  2486. }
  2487. /**
  2488. * Vector4 class created for EulerAngle class conversion to Quaternion
  2489. */
  2490. export class Vector4 {
  2491. /**
  2492. * Creates a Vector4 object from the given floats.
  2493. * @param x x value of the vector
  2494. * @param y y value of the vector
  2495. * @param z z value of the vector
  2496. * @param w w value of the vector
  2497. */
  2498. constructor(
  2499. /** x value of the vector */
  2500. public x: number,
  2501. /** y value of the vector */
  2502. public y: number,
  2503. /** z value of the vector */
  2504. public z: number,
  2505. /** w value of the vector */
  2506. public w: number
  2507. ) { }
  2508. /**
  2509. * Returns the string with the Vector4 coordinates.
  2510. * @returns a string containing all the vector values
  2511. */
  2512. public toString(): string {
  2513. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2514. }
  2515. /**
  2516. * Returns the string "Vector4".
  2517. * @returns "Vector4"
  2518. */
  2519. public getClassName(): string {
  2520. return "Vector4";
  2521. }
  2522. /**
  2523. * Returns the Vector4 hash code.
  2524. * @returns a unique hash code
  2525. */
  2526. public getHashCode(): number {
  2527. let hash = this.x || 0;
  2528. hash = (hash * 397) ^ (this.y || 0);
  2529. hash = (hash * 397) ^ (this.z || 0);
  2530. hash = (hash * 397) ^ (this.w || 0);
  2531. return hash;
  2532. }
  2533. // Operators
  2534. /**
  2535. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2536. * @returns the resulting array
  2537. */
  2538. public asArray(): number[] {
  2539. var result = new Array<number>();
  2540. this.toArray(result, 0);
  2541. return result;
  2542. }
  2543. /**
  2544. * Populates the given array from the given index with the Vector4 coordinates.
  2545. * @param array array to populate
  2546. * @param index index of the array to start at (default: 0)
  2547. * @returns the Vector4.
  2548. */
  2549. public toArray(array: FloatArray, index?: number): Vector4 {
  2550. if (index === undefined) {
  2551. index = 0;
  2552. }
  2553. array[index] = this.x;
  2554. array[index + 1] = this.y;
  2555. array[index + 2] = this.z;
  2556. array[index + 3] = this.w;
  2557. return this;
  2558. }
  2559. /**
  2560. * Adds the given vector to the current Vector4.
  2561. * @param otherVector the vector to add
  2562. * @returns the updated Vector4.
  2563. */
  2564. public addInPlace(otherVector: Vector4): Vector4 {
  2565. this.x += otherVector.x;
  2566. this.y += otherVector.y;
  2567. this.z += otherVector.z;
  2568. this.w += otherVector.w;
  2569. return this;
  2570. }
  2571. /**
  2572. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  2573. * @param otherVector the vector to add
  2574. * @returns the resulting vector
  2575. */
  2576. public add(otherVector: Vector4): Vector4 {
  2577. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2578. }
  2579. /**
  2580. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  2581. * @param otherVector the vector to add
  2582. * @param result the vector to store the result
  2583. * @returns the current Vector4.
  2584. */
  2585. public addToRef(otherVector: Vector4, result: Vector4): Vector4 {
  2586. result.x = this.x + otherVector.x;
  2587. result.y = this.y + otherVector.y;
  2588. result.z = this.z + otherVector.z;
  2589. result.w = this.w + otherVector.w;
  2590. return this;
  2591. }
  2592. /**
  2593. * Subtract in place the given vector from the current Vector4.
  2594. * @param otherVector the vector to subtract
  2595. * @returns the updated Vector4.
  2596. */
  2597. public subtractInPlace(otherVector: Vector4): Vector4 {
  2598. this.x -= otherVector.x;
  2599. this.y -= otherVector.y;
  2600. this.z -= otherVector.z;
  2601. this.w -= otherVector.w;
  2602. return this;
  2603. }
  2604. /**
  2605. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  2606. * @param otherVector the vector to add
  2607. * @returns the new vector with the result
  2608. */
  2609. public subtract(otherVector: Vector4): Vector4 {
  2610. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2611. }
  2612. /**
  2613. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  2614. * @param otherVector the vector to subtract
  2615. * @param result the vector to store the result
  2616. * @returns the current Vector4.
  2617. */
  2618. public subtractToRef(otherVector: Vector4, result: Vector4): Vector4 {
  2619. result.x = this.x - otherVector.x;
  2620. result.y = this.y - otherVector.y;
  2621. result.z = this.z - otherVector.z;
  2622. result.w = this.w - otherVector.w;
  2623. return this;
  2624. }
  2625. /**
  2626. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  2627. */
  2628. /**
  2629. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  2630. * @param x value to subtract
  2631. * @param y value to subtract
  2632. * @param z value to subtract
  2633. * @param w value to subtract
  2634. * @returns new vector containing the result
  2635. */
  2636. public subtractFromFloats(x: number, y: number, z: number, w: number): Vector4 {
  2637. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2638. }
  2639. /**
  2640. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  2641. * @param x value to subtract
  2642. * @param y value to subtract
  2643. * @param z value to subtract
  2644. * @param w value to subtract
  2645. * @param result the vector to store the result in
  2646. * @returns the current Vector4.
  2647. */
  2648. public subtractFromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): Vector4 {
  2649. result.x = this.x - x;
  2650. result.y = this.y - y;
  2651. result.z = this.z - z;
  2652. result.w = this.w - w;
  2653. return this;
  2654. }
  2655. /**
  2656. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2657. * @returns a new vector with the negated values
  2658. */
  2659. public negate(): Vector4 {
  2660. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2661. }
  2662. /**
  2663. * Multiplies the current Vector4 coordinates by scale (float).
  2664. * @param scale the number to scale with
  2665. * @returns the updated Vector4.
  2666. */
  2667. public scaleInPlace(scale: number): Vector4 {
  2668. this.x *= scale;
  2669. this.y *= scale;
  2670. this.z *= scale;
  2671. this.w *= scale;
  2672. return this;
  2673. }
  2674. /**
  2675. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2676. * @param scale the number to scale with
  2677. * @returns a new vector with the result
  2678. */
  2679. public scale(scale: number): Vector4 {
  2680. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2681. }
  2682. /**
  2683. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2684. * @param scale the number to scale with
  2685. * @param result a vector to store the result in
  2686. * @returns the current Vector4.
  2687. */
  2688. public scaleToRef(scale: number, result: Vector4): Vector4 {
  2689. result.x = this.x * scale;
  2690. result.y = this.y * scale;
  2691. result.z = this.z * scale;
  2692. result.w = this.w * scale;
  2693. return this;
  2694. }
  2695. /**
  2696. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  2697. * @param scale defines the scale factor
  2698. * @param result defines the Vector4 object where to store the result
  2699. * @returns the unmodified current Vector4
  2700. */
  2701. public scaleAndAddToRef(scale: number, result: Vector4): Vector4 {
  2702. result.x += this.x * scale;
  2703. result.y += this.y * scale;
  2704. result.z += this.z * scale;
  2705. result.w += this.w * scale;
  2706. return this;
  2707. }
  2708. /**
  2709. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  2710. * @param otherVector the vector to compare against
  2711. * @returns true if they are equal
  2712. */
  2713. public equals(otherVector: Vector4): boolean {
  2714. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2715. }
  2716. /**
  2717. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  2718. * @param otherVector vector to compare against
  2719. * @param epsilon (Default: very small number)
  2720. * @returns true if they are equal
  2721. */
  2722. public equalsWithEpsilon(otherVector: Vector4, epsilon: number = Epsilon): boolean {
  2723. return otherVector
  2724. && Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2725. && Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2726. && Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2727. && Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2728. }
  2729. /**
  2730. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  2731. * @param x x value to compare against
  2732. * @param y y value to compare against
  2733. * @param z z value to compare against
  2734. * @param w w value to compare against
  2735. * @returns true if equal
  2736. */
  2737. public equalsToFloats(x: number, y: number, z: number, w: number): boolean {
  2738. return this.x === x && this.y === y && this.z === z && this.w === w;
  2739. }
  2740. /**
  2741. * Multiplies in place the current Vector4 by the given one.
  2742. * @param otherVector vector to multiple with
  2743. * @returns the updated Vector4.
  2744. */
  2745. public multiplyInPlace(otherVector: Vector4): Vector4 {
  2746. this.x *= otherVector.x;
  2747. this.y *= otherVector.y;
  2748. this.z *= otherVector.z;
  2749. this.w *= otherVector.w;
  2750. return this;
  2751. }
  2752. /**
  2753. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  2754. * @param otherVector vector to multiple with
  2755. * @returns resulting new vector
  2756. */
  2757. public multiply(otherVector: Vector4): Vector4 {
  2758. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2759. }
  2760. /**
  2761. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  2762. * @param otherVector vector to multiple with
  2763. * @param result vector to store the result
  2764. * @returns the current Vector4.
  2765. */
  2766. public multiplyToRef(otherVector: Vector4, result: Vector4): Vector4 {
  2767. result.x = this.x * otherVector.x;
  2768. result.y = this.y * otherVector.y;
  2769. result.z = this.z * otherVector.z;
  2770. result.w = this.w * otherVector.w;
  2771. return this;
  2772. }
  2773. /**
  2774. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  2775. * @param x x value multiply with
  2776. * @param y y value multiply with
  2777. * @param z z value multiply with
  2778. * @param w w value multiply with
  2779. * @returns resulting new vector
  2780. */
  2781. public multiplyByFloats(x: number, y: number, z: number, w: number): Vector4 {
  2782. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2783. }
  2784. /**
  2785. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  2786. * @param otherVector vector to devide with
  2787. * @returns resulting new vector
  2788. */
  2789. public divide(otherVector: Vector4): Vector4 {
  2790. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2791. }
  2792. /**
  2793. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  2794. * @param otherVector vector to devide with
  2795. * @param result vector to store the result
  2796. * @returns the current Vector4.
  2797. */
  2798. public divideToRef(otherVector: Vector4, result: Vector4): Vector4 {
  2799. result.x = this.x / otherVector.x;
  2800. result.y = this.y / otherVector.y;
  2801. result.z = this.z / otherVector.z;
  2802. result.w = this.w / otherVector.w;
  2803. return this;
  2804. }
  2805. /**
  2806. * Divides the current Vector3 coordinates by the given ones.
  2807. * @param otherVector vector to devide with
  2808. * @returns the updated Vector3.
  2809. */
  2810. public divideInPlace(otherVector: Vector4): Vector4 {
  2811. return this.divideToRef(otherVector, this);
  2812. }
  2813. /**
  2814. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  2815. * @param other defines the second operand
  2816. * @returns the current updated Vector4
  2817. */
  2818. public minimizeInPlace(other: Vector4): Vector4 {
  2819. if (other.x < this.x) { this.x = other.x; }
  2820. if (other.y < this.y) { this.y = other.y; }
  2821. if (other.z < this.z) { this.z = other.z; }
  2822. if (other.w < this.w) { this.w = other.w; }
  2823. return this;
  2824. }
  2825. /**
  2826. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  2827. * @param other defines the second operand
  2828. * @returns the current updated Vector4
  2829. */
  2830. public maximizeInPlace(other: Vector4): Vector4 {
  2831. if (other.x > this.x) { this.x = other.x; }
  2832. if (other.y > this.y) { this.y = other.y; }
  2833. if (other.z > this.z) { this.z = other.z; }
  2834. if (other.w > this.w) { this.w = other.w; }
  2835. return this;
  2836. }
  2837. /**
  2838. * Gets a new Vector4 from current Vector4 floored values
  2839. * @returns a new Vector4
  2840. */
  2841. public floor(): Vector4 {
  2842. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  2843. }
  2844. /**
  2845. * Gets a new Vector4 from current Vector3 floored values
  2846. * @returns a new Vector4
  2847. */
  2848. public fract(): Vector4 {
  2849. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  2850. }
  2851. // Properties
  2852. /**
  2853. * Returns the Vector4 length (float).
  2854. * @returns the length
  2855. */
  2856. public length(): number {
  2857. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2858. }
  2859. /**
  2860. * Returns the Vector4 squared length (float).
  2861. * @returns the length squared
  2862. */
  2863. public lengthSquared(): number {
  2864. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2865. }
  2866. // Methods
  2867. /**
  2868. * Normalizes in place the Vector4.
  2869. * @returns the updated Vector4.
  2870. */
  2871. public normalize(): Vector4 {
  2872. var len = this.length();
  2873. if (len === 0) {
  2874. return this;
  2875. }
  2876. return this.scaleInPlace(1.0 / len);
  2877. }
  2878. /**
  2879. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2880. * @returns this converted to a new vector3
  2881. */
  2882. public toVector3(): Vector3 {
  2883. return new Vector3(this.x, this.y, this.z);
  2884. }
  2885. /**
  2886. * Returns a new Vector4 copied from the current one.
  2887. * @returns the new cloned vector
  2888. */
  2889. public clone(): Vector4 {
  2890. return new Vector4(this.x, this.y, this.z, this.w);
  2891. }
  2892. /**
  2893. * Updates the current Vector4 with the given one coordinates.
  2894. * @param source the source vector to copy from
  2895. * @returns the updated Vector4.
  2896. */
  2897. public copyFrom(source: Vector4): Vector4 {
  2898. this.x = source.x;
  2899. this.y = source.y;
  2900. this.z = source.z;
  2901. this.w = source.w;
  2902. return this;
  2903. }
  2904. /**
  2905. * Updates the current Vector4 coordinates with the given floats.
  2906. * @param x float to copy from
  2907. * @param y float to copy from
  2908. * @param z float to copy from
  2909. * @param w float to copy from
  2910. * @returns the updated Vector4.
  2911. */
  2912. public copyFromFloats(x: number, y: number, z: number, w: number): Vector4 {
  2913. this.x = x;
  2914. this.y = y;
  2915. this.z = z;
  2916. this.w = w;
  2917. return this;
  2918. }
  2919. /**
  2920. * Updates the current Vector4 coordinates with the given floats.
  2921. * @param x float to set from
  2922. * @param y float to set from
  2923. * @param z float to set from
  2924. * @param w float to set from
  2925. * @returns the updated Vector4.
  2926. */
  2927. public set(x: number, y: number, z: number, w: number): Vector4 {
  2928. return this.copyFromFloats(x, y, z, w);
  2929. }
  2930. /**
  2931. * Copies the given float to the current Vector3 coordinates
  2932. * @param v defines the x, y, z and w coordinates of the operand
  2933. * @returns the current updated Vector3
  2934. */
  2935. public setAll(v: number): Vector4 {
  2936. this.x = this.y = this.z = this.w = v;
  2937. return this;
  2938. }
  2939. // Statics
  2940. /**
  2941. * Returns a new Vector4 set from the starting index of the given array.
  2942. * @param array the array to pull values from
  2943. * @param offset the offset into the array to start at
  2944. * @returns the new vector
  2945. */
  2946. public static FromArray(array: ArrayLike<number>, offset?: number): Vector4 {
  2947. if (!offset) {
  2948. offset = 0;
  2949. }
  2950. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2951. }
  2952. /**
  2953. * Updates the given vector "result" from the starting index of the given array.
  2954. * @param array the array to pull values from
  2955. * @param offset the offset into the array to start at
  2956. * @param result the vector to store the result in
  2957. */
  2958. public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector4): void {
  2959. result.x = array[offset];
  2960. result.y = array[offset + 1];
  2961. result.z = array[offset + 2];
  2962. result.w = array[offset + 3];
  2963. }
  2964. /**
  2965. * Updates the given vector "result" from the starting index of the given Float32Array.
  2966. * @param array the array to pull values from
  2967. * @param offset the offset into the array to start at
  2968. * @param result the vector to store the result in
  2969. */
  2970. public static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector4): void {
  2971. Vector4.FromArrayToRef(array, offset, result);
  2972. }
  2973. /**
  2974. * Updates the given vector "result" coordinates from the given floats.
  2975. * @param x float to set from
  2976. * @param y float to set from
  2977. * @param z float to set from
  2978. * @param w float to set from
  2979. * @param result the vector to the floats in
  2980. */
  2981. public static FromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): void {
  2982. result.x = x;
  2983. result.y = y;
  2984. result.z = z;
  2985. result.w = w;
  2986. }
  2987. /**
  2988. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2989. * @returns the new vector
  2990. */
  2991. public static Zero(): Vector4 {
  2992. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2993. }
  2994. /**
  2995. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2996. * @returns the new vector
  2997. */
  2998. public static One(): Vector4 {
  2999. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3000. }
  3001. /**
  3002. * Returns a new normalized Vector4 from the given one.
  3003. * @param vector the vector to normalize
  3004. * @returns the vector
  3005. */
  3006. public static Normalize(vector: Vector4): Vector4 {
  3007. var result = Vector4.Zero();
  3008. Vector4.NormalizeToRef(vector, result);
  3009. return result;
  3010. }
  3011. /**
  3012. * Updates the given vector "result" from the normalization of the given one.
  3013. * @param vector the vector to normalize
  3014. * @param result the vector to store the result in
  3015. */
  3016. public static NormalizeToRef(vector: Vector4, result: Vector4): void {
  3017. result.copyFrom(vector);
  3018. result.normalize();
  3019. }
  3020. /**
  3021. * Returns a vector with the minimum values from the left and right vectors
  3022. * @param left left vector to minimize
  3023. * @param right right vector to minimize
  3024. * @returns a new vector with the minimum of the left and right vector values
  3025. */
  3026. public static Minimize(left: Vector4, right: Vector4): Vector4 {
  3027. var min = left.clone();
  3028. min.minimizeInPlace(right);
  3029. return min;
  3030. }
  3031. /**
  3032. * Returns a vector with the maximum values from the left and right vectors
  3033. * @param left left vector to maximize
  3034. * @param right right vector to maximize
  3035. * @returns a new vector with the maximum of the left and right vector values
  3036. */
  3037. public static Maximize(left: Vector4, right: Vector4): Vector4 {
  3038. var max = left.clone();
  3039. max.maximizeInPlace(right);
  3040. return max;
  3041. }
  3042. /**
  3043. * Returns the distance (float) between the vectors "value1" and "value2".
  3044. * @param value1 value to calulate the distance between
  3045. * @param value2 value to calulate the distance between
  3046. * @return the distance between the two vectors
  3047. */
  3048. public static Distance(value1: Vector4, value2: Vector4): number {
  3049. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3050. }
  3051. /**
  3052. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3053. * @param value1 value to calulate the distance between
  3054. * @param value2 value to calulate the distance between
  3055. * @return the distance between the two vectors squared
  3056. */
  3057. public static DistanceSquared(value1: Vector4, value2: Vector4): number {
  3058. var x = value1.x - value2.x;
  3059. var y = value1.y - value2.y;
  3060. var z = value1.z - value2.z;
  3061. var w = value1.w - value2.w;
  3062. return (x * x) + (y * y) + (z * z) + (w * w);
  3063. }
  3064. /**
  3065. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3066. * @param value1 value to calulate the center between
  3067. * @param value2 value to calulate the center between
  3068. * @return the center between the two vectors
  3069. */
  3070. public static Center(value1: Vector4, value2: Vector4): Vector4 {
  3071. var center = value1.add(value2);
  3072. center.scaleInPlace(0.5);
  3073. return center;
  3074. }
  3075. /**
  3076. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  3077. * This methods computes transformed normalized direction vectors only.
  3078. * @param vector the vector to transform
  3079. * @param transformation the transformation matrix to apply
  3080. * @returns the new vector
  3081. */
  3082. public static TransformNormal(vector: Vector4, transformation: Matrix): Vector4 {
  3083. var result = Vector4.Zero();
  3084. Vector4.TransformNormalToRef(vector, transformation, result);
  3085. return result;
  3086. }
  3087. /**
  3088. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  3089. * This methods computes transformed normalized direction vectors only.
  3090. * @param vector the vector to transform
  3091. * @param transformation the transformation matrix to apply
  3092. * @param result the vector to store the result in
  3093. */
  3094. public static TransformNormalToRef(vector: Vector4, transformation: Matrix, result: Vector4): void {
  3095. const m = transformation.m;
  3096. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  3097. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  3098. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  3099. result.x = x;
  3100. result.y = y;
  3101. result.z = z;
  3102. result.w = vector.w;
  3103. }
  3104. /**
  3105. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  3106. * This methods computes transformed normalized direction vectors only.
  3107. * @param x value to transform
  3108. * @param y value to transform
  3109. * @param z value to transform
  3110. * @param w value to transform
  3111. * @param transformation the transformation matrix to apply
  3112. * @param result the vector to store the results in
  3113. */
  3114. public static TransformNormalFromFloatsToRef(x: number, y: number, z: number, w: number, transformation: Matrix, result: Vector4): void {
  3115. const m = transformation.m;
  3116. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  3117. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  3118. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  3119. result.w = w;
  3120. }
  3121. }
  3122. /**
  3123. * Interface for the size containing width and height
  3124. */
  3125. export interface ISize {
  3126. /**
  3127. * Width
  3128. */
  3129. width: number;
  3130. /**
  3131. * Heighht
  3132. */
  3133. height: number;
  3134. }
  3135. /**
  3136. * Size containing widht and height
  3137. */
  3138. export class Size implements ISize {
  3139. /**
  3140. * Width
  3141. */
  3142. public width: number;
  3143. /**
  3144. * Height
  3145. */
  3146. public height: number;
  3147. /**
  3148. * Creates a Size object from the given width and height (floats).
  3149. * @param width width of the new size
  3150. * @param height height of the new size
  3151. */
  3152. public constructor(width: number, height: number) {
  3153. this.width = width;
  3154. this.height = height;
  3155. }
  3156. /**
  3157. * Returns a string with the Size width and height
  3158. * @returns a string with the Size width and height
  3159. */
  3160. public toString(): string {
  3161. return `{W: ${this.width}, H: ${this.height}}`;
  3162. }
  3163. /**
  3164. * "Size"
  3165. * @returns the string "Size"
  3166. */
  3167. public getClassName(): string {
  3168. return "Size";
  3169. }
  3170. /**
  3171. * Returns the Size hash code.
  3172. * @returns a hash code for a unique width and height
  3173. */
  3174. public getHashCode(): number {
  3175. let hash = this.width || 0;
  3176. hash = (hash * 397) ^ (this.height || 0);
  3177. return hash;
  3178. }
  3179. /**
  3180. * Updates the current size from the given one.
  3181. * @param src the given size
  3182. */
  3183. public copyFrom(src: Size) {
  3184. this.width = src.width;
  3185. this.height = src.height;
  3186. }
  3187. /**
  3188. * Updates in place the current Size from the given floats.
  3189. * @param width width of the new size
  3190. * @param height height of the new size
  3191. * @returns the updated Size.
  3192. */
  3193. public copyFromFloats(width: number, height: number): Size {
  3194. this.width = width;
  3195. this.height = height;
  3196. return this;
  3197. }
  3198. /**
  3199. * Updates in place the current Size from the given floats.
  3200. * @param width width to set
  3201. * @param height height to set
  3202. * @returns the updated Size.
  3203. */
  3204. public set(width: number, height: number): Size {
  3205. return this.copyFromFloats(width, height);
  3206. }
  3207. /**
  3208. * Multiplies the width and height by numbers
  3209. * @param w factor to multiple the width by
  3210. * @param h factor to multiple the height by
  3211. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  3212. */
  3213. public multiplyByFloats(w: number, h: number): Size {
  3214. return new Size(this.width * w, this.height * h);
  3215. }
  3216. /**
  3217. * Clones the size
  3218. * @returns a new Size copied from the given one.
  3219. */
  3220. public clone(): Size {
  3221. return new Size(this.width, this.height);
  3222. }
  3223. /**
  3224. * True if the current Size and the given one width and height are strictly equal.
  3225. * @param other the other size to compare against
  3226. * @returns True if the current Size and the given one width and height are strictly equal.
  3227. */
  3228. public equals(other: Size): boolean {
  3229. if (!other) {
  3230. return false;
  3231. }
  3232. return (this.width === other.width) && (this.height === other.height);
  3233. }
  3234. /**
  3235. * The surface of the Size : width * height (float).
  3236. */
  3237. public get surface(): number {
  3238. return this.width * this.height;
  3239. }
  3240. /**
  3241. * Create a new size of zero
  3242. * @returns a new Size set to (0.0, 0.0)
  3243. */
  3244. public static Zero(): Size {
  3245. return new Size(0.0, 0.0);
  3246. }
  3247. /**
  3248. * Sums the width and height of two sizes
  3249. * @param otherSize size to add to this size
  3250. * @returns a new Size set as the addition result of the current Size and the given one.
  3251. */
  3252. public add(otherSize: Size): Size {
  3253. let r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3254. return r;
  3255. }
  3256. /**
  3257. * Subtracts the width and height of two
  3258. * @param otherSize size to subtract to this size
  3259. * @returns a new Size set as the subtraction result of the given one from the current Size.
  3260. */
  3261. public subtract(otherSize: Size): Size {
  3262. let r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3263. return r;
  3264. }
  3265. /**
  3266. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  3267. * @param start starting size to lerp between
  3268. * @param end end size to lerp between
  3269. * @param amount amount to lerp between the start and end values
  3270. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  3271. */
  3272. public static Lerp(start: Size, end: Size, amount: number): Size {
  3273. var w = start.width + ((end.width - start.width) * amount);
  3274. var h = start.height + ((end.height - start.height) * amount);
  3275. return new Size(w, h);
  3276. }
  3277. }
  3278. /**
  3279. * Class used to store quaternion data
  3280. * @see https://en.wikipedia.org/wiki/Quaternion
  3281. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  3282. */
  3283. export class Quaternion {
  3284. /**
  3285. * Creates a new Quaternion from the given floats
  3286. * @param x defines the first component (0 by default)
  3287. * @param y defines the second component (0 by default)
  3288. * @param z defines the third component (0 by default)
  3289. * @param w defines the fourth component (1.0 by default)
  3290. */
  3291. constructor(
  3292. /** defines the first component (0 by default) */
  3293. public x: number = 0.0,
  3294. /** defines the second component (0 by default) */
  3295. public y: number = 0.0,
  3296. /** defines the third component (0 by default) */
  3297. public z: number = 0.0,
  3298. /** defines the fourth component (1.0 by default) */
  3299. public w: number = 1.0) {
  3300. }
  3301. /**
  3302. * Gets a string representation for the current quaternion
  3303. * @returns a string with the Quaternion coordinates
  3304. */
  3305. public toString(): string {
  3306. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3307. }
  3308. /**
  3309. * Gets the class name of the quaternion
  3310. * @returns the string "Quaternion"
  3311. */
  3312. public getClassName(): string {
  3313. return "Quaternion";
  3314. }
  3315. /**
  3316. * Gets a hash code for this quaternion
  3317. * @returns the quaternion hash code
  3318. */
  3319. public getHashCode(): number {
  3320. let hash = this.x || 0;
  3321. hash = (hash * 397) ^ (this.y || 0);
  3322. hash = (hash * 397) ^ (this.z || 0);
  3323. hash = (hash * 397) ^ (this.w || 0);
  3324. return hash;
  3325. }
  3326. /**
  3327. * Copy the quaternion to an array
  3328. * @returns a new array populated with 4 elements from the quaternion coordinates
  3329. */
  3330. public asArray(): number[] {
  3331. return [this.x, this.y, this.z, this.w];
  3332. }
  3333. /**
  3334. * Check if two quaternions are equals
  3335. * @param otherQuaternion defines the second operand
  3336. * @return true if the current quaternion and the given one coordinates are strictly equals
  3337. */
  3338. public equals(otherQuaternion: Quaternion): boolean {
  3339. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3340. }
  3341. /**
  3342. * Clone the current quaternion
  3343. * @returns a new quaternion copied from the current one
  3344. */
  3345. public clone(): Quaternion {
  3346. return new Quaternion(this.x, this.y, this.z, this.w);
  3347. }
  3348. /**
  3349. * Copy a quaternion to the current one
  3350. * @param other defines the other quaternion
  3351. * @returns the updated current quaternion
  3352. */
  3353. public copyFrom(other: Quaternion): Quaternion {
  3354. this.x = other.x;
  3355. this.y = other.y;
  3356. this.z = other.z;
  3357. this.w = other.w;
  3358. return this;
  3359. }
  3360. /**
  3361. * Updates the current quaternion with the given float coordinates
  3362. * @param x defines the x coordinate
  3363. * @param y defines the y coordinate
  3364. * @param z defines the z coordinate
  3365. * @param w defines the w coordinate
  3366. * @returns the updated current quaternion
  3367. */
  3368. public copyFromFloats(x: number, y: number, z: number, w: number): Quaternion {
  3369. this.x = x;
  3370. this.y = y;
  3371. this.z = z;
  3372. this.w = w;
  3373. return this;
  3374. }
  3375. /**
  3376. * Updates the current quaternion from the given float coordinates
  3377. * @param x defines the x coordinate
  3378. * @param y defines the y coordinate
  3379. * @param z defines the z coordinate
  3380. * @param w defines the w coordinate
  3381. * @returns the updated current quaternion
  3382. */
  3383. public set(x: number, y: number, z: number, w: number): Quaternion {
  3384. return this.copyFromFloats(x, y, z, w);
  3385. }
  3386. /**
  3387. * Adds two quaternions
  3388. * @param other defines the second operand
  3389. * @returns a new quaternion as the addition result of the given one and the current quaternion
  3390. */
  3391. public add(other: Quaternion): Quaternion {
  3392. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3393. }
  3394. /**
  3395. * Add a quaternion to the current one
  3396. * @param other defines the quaternion to add
  3397. * @returns the current quaternion
  3398. */
  3399. public addInPlace(other: Quaternion): Quaternion {
  3400. this.x += other.x;
  3401. this.y += other.y;
  3402. this.z += other.z;
  3403. this.w += other.w;
  3404. return this;
  3405. }
  3406. /**
  3407. * Subtract two quaternions
  3408. * @param other defines the second operand
  3409. * @returns a new quaternion as the subtraction result of the given one from the current one
  3410. */
  3411. public subtract(other: Quaternion): Quaternion {
  3412. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3413. }
  3414. /**
  3415. * Multiplies the current quaternion by a scale factor
  3416. * @param value defines the scale factor
  3417. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  3418. */
  3419. public scale(value: number): Quaternion {
  3420. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3421. }
  3422. /**
  3423. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  3424. * @param scale defines the scale factor
  3425. * @param result defines the Quaternion object where to store the result
  3426. * @returns the unmodified current quaternion
  3427. */
  3428. public scaleToRef(scale: number, result: Quaternion): Quaternion {
  3429. result.x = this.x * scale;
  3430. result.y = this.y * scale;
  3431. result.z = this.z * scale;
  3432. result.w = this.w * scale;
  3433. return this;
  3434. }
  3435. /**
  3436. * Multiplies in place the current quaternion by a scale factor
  3437. * @param value defines the scale factor
  3438. * @returns the current modified quaternion
  3439. */
  3440. public scaleInPlace(value: number): Quaternion {
  3441. this.x *= value;
  3442. this.y *= value;
  3443. this.z *= value;
  3444. this.w *= value;
  3445. return this;
  3446. }
  3447. /**
  3448. * Scale the current quaternion values by a factor and add the result to a given quaternion
  3449. * @param scale defines the scale factor
  3450. * @param result defines the Quaternion object where to store the result
  3451. * @returns the unmodified current quaternion
  3452. */
  3453. public scaleAndAddToRef(scale: number, result: Quaternion): Quaternion {
  3454. result.x += this.x * scale;
  3455. result.y += this.y * scale;
  3456. result.z += this.z * scale;
  3457. result.w += this.w * scale;
  3458. return this;
  3459. }
  3460. /**
  3461. * Multiplies two quaternions
  3462. * @param q1 defines the second operand
  3463. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  3464. */
  3465. public multiply(q1: Quaternion): Quaternion {
  3466. var result = new Quaternion(0, 0, 0, 1.0);
  3467. this.multiplyToRef(q1, result);
  3468. return result;
  3469. }
  3470. /**
  3471. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  3472. * @param q1 defines the second operand
  3473. * @param result defines the target quaternion
  3474. * @returns the current quaternion
  3475. */
  3476. public multiplyToRef(q1: Quaternion, result: Quaternion): Quaternion {
  3477. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3478. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3479. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3480. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3481. result.copyFromFloats(x, y, z, w);
  3482. return this;
  3483. }
  3484. /**
  3485. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  3486. * @param q1 defines the second operand
  3487. * @returns the currentupdated quaternion
  3488. */
  3489. public multiplyInPlace(q1: Quaternion): Quaternion {
  3490. this.multiplyToRef(q1, this);
  3491. return this;
  3492. }
  3493. /**
  3494. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  3495. * @param ref defines the target quaternion
  3496. * @returns the current quaternion
  3497. */
  3498. public conjugateToRef(ref: Quaternion): Quaternion {
  3499. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3500. return this;
  3501. }
  3502. /**
  3503. * Conjugates in place (1-q) the current quaternion
  3504. * @returns the current updated quaternion
  3505. */
  3506. public conjugateInPlace(): Quaternion {
  3507. this.x *= -1;
  3508. this.y *= -1;
  3509. this.z *= -1;
  3510. return this;
  3511. }
  3512. /**
  3513. * Conjugates in place (1-q) the current quaternion
  3514. * @returns a new quaternion
  3515. */
  3516. public conjugate(): Quaternion {
  3517. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3518. return result;
  3519. }
  3520. /**
  3521. * Gets length of current quaternion
  3522. * @returns the quaternion length (float)
  3523. */
  3524. public length(): number {
  3525. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3526. }
  3527. /**
  3528. * Normalize in place the current quaternion
  3529. * @returns the current updated quaternion
  3530. */
  3531. public normalize(): Quaternion {
  3532. var length = 1.0 / this.length();
  3533. this.x *= length;
  3534. this.y *= length;
  3535. this.z *= length;
  3536. this.w *= length;
  3537. return this;
  3538. }
  3539. /**
  3540. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  3541. * @param order is a reserved parameter and is ignore for now
  3542. * @returns a new Vector3 containing the Euler angles
  3543. */
  3544. public toEulerAngles(order = "YZX"): Vector3 {
  3545. var result = Vector3.Zero();
  3546. this.toEulerAnglesToRef(result);
  3547. return result;
  3548. }
  3549. /**
  3550. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  3551. * @param result defines the vector which will be filled with the Euler angles
  3552. * @param order is a reserved parameter and is ignore for now
  3553. * @returns the current unchanged quaternion
  3554. */
  3555. public toEulerAnglesToRef(result: Vector3): Quaternion {
  3556. var qz = this.z;
  3557. var qx = this.x;
  3558. var qy = this.y;
  3559. var qw = this.w;
  3560. var sqw = qw * qw;
  3561. var sqz = qz * qz;
  3562. var sqx = qx * qx;
  3563. var sqy = qy * qy;
  3564. var zAxisY = qy * qz - qx * qw;
  3565. var limit = .4999999;
  3566. if (zAxisY < -limit) {
  3567. result.y = 2 * Math.atan2(qy, qw);
  3568. result.x = Math.PI / 2;
  3569. result.z = 0;
  3570. } else if (zAxisY > limit) {
  3571. result.y = 2 * Math.atan2(qy, qw);
  3572. result.x = -Math.PI / 2;
  3573. result.z = 0;
  3574. } else {
  3575. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3576. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3577. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3578. }
  3579. return this;
  3580. }
  3581. /**
  3582. * Updates the given rotation matrix with the current quaternion values
  3583. * @param result defines the target matrix
  3584. * @returns the current unchanged quaternion
  3585. */
  3586. public toRotationMatrix(result: Matrix): Quaternion {
  3587. Matrix.FromQuaternionToRef(this, result);
  3588. return this;
  3589. }
  3590. /**
  3591. * Updates the current quaternion from the given rotation matrix values
  3592. * @param matrix defines the source matrix
  3593. * @returns the current updated quaternion
  3594. */
  3595. public fromRotationMatrix(matrix: Matrix): Quaternion {
  3596. Quaternion.FromRotationMatrixToRef(matrix, this);
  3597. return this;
  3598. }
  3599. // Statics
  3600. /**
  3601. * Creates a new quaternion from a rotation matrix
  3602. * @param matrix defines the source matrix
  3603. * @returns a new quaternion created from the given rotation matrix values
  3604. */
  3605. public static FromRotationMatrix(matrix: Matrix): Quaternion {
  3606. var result = new Quaternion();
  3607. Quaternion.FromRotationMatrixToRef(matrix, result);
  3608. return result;
  3609. }
  3610. /**
  3611. * Updates the given quaternion with the given rotation matrix values
  3612. * @param matrix defines the source matrix
  3613. * @param result defines the target quaternion
  3614. */
  3615. public static FromRotationMatrixToRef(matrix: Matrix, result: Quaternion): void {
  3616. var data = matrix.m;
  3617. var m11 = data[0], m12 = data[4], m13 = data[8];
  3618. var m21 = data[1], m22 = data[5], m23 = data[9];
  3619. var m31 = data[2], m32 = data[6], m33 = data[10];
  3620. var trace = m11 + m22 + m33;
  3621. var s;
  3622. if (trace > 0) {
  3623. s = 0.5 / Math.sqrt(trace + 1.0);
  3624. result.w = 0.25 / s;
  3625. result.x = (m32 - m23) * s;
  3626. result.y = (m13 - m31) * s;
  3627. result.z = (m21 - m12) * s;
  3628. } else if (m11 > m22 && m11 > m33) {
  3629. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3630. result.w = (m32 - m23) / s;
  3631. result.x = 0.25 * s;
  3632. result.y = (m12 + m21) / s;
  3633. result.z = (m13 + m31) / s;
  3634. } else if (m22 > m33) {
  3635. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3636. result.w = (m13 - m31) / s;
  3637. result.x = (m12 + m21) / s;
  3638. result.y = 0.25 * s;
  3639. result.z = (m23 + m32) / s;
  3640. } else {
  3641. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3642. result.w = (m21 - m12) / s;
  3643. result.x = (m13 + m31) / s;
  3644. result.y = (m23 + m32) / s;
  3645. result.z = 0.25 * s;
  3646. }
  3647. }
  3648. /**
  3649. * Returns the dot product (float) between the quaternions "left" and "right"
  3650. * @param left defines the left operand
  3651. * @param right defines the right operand
  3652. * @returns the dot product
  3653. */
  3654. public static Dot(left: Quaternion, right: Quaternion): number {
  3655. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  3656. }
  3657. /**
  3658. * Checks if the two quaternions are close to each other
  3659. * @param quat0 defines the first quaternion to check
  3660. * @param quat1 defines the second quaternion to check
  3661. * @returns true if the two quaternions are close to each other
  3662. */
  3663. public static AreClose(quat0: Quaternion, quat1: Quaternion): boolean {
  3664. let dot = Quaternion.Dot(quat0, quat1);
  3665. return dot >= 0;
  3666. }
  3667. /**
  3668. * Creates an empty quaternion
  3669. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  3670. */
  3671. public static Zero(): Quaternion {
  3672. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3673. }
  3674. /**
  3675. * Inverse a given quaternion
  3676. * @param q defines the source quaternion
  3677. * @returns a new quaternion as the inverted current quaternion
  3678. */
  3679. public static Inverse(q: Quaternion): Quaternion {
  3680. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3681. }
  3682. /**
  3683. * Inverse a given quaternion
  3684. * @param q defines the source quaternion
  3685. * @param result the quaternion the result will be stored in
  3686. * @returns the result quaternion
  3687. */
  3688. public static InverseToRef(q: Quaternion, result: Quaternion): Quaternion {
  3689. result.set(-q.x, -q.y, -q.z, q.w);
  3690. return result;
  3691. }
  3692. /**
  3693. * Creates an identity quaternion
  3694. * @returns the identity quaternion
  3695. */
  3696. public static Identity(): Quaternion {
  3697. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3698. }
  3699. /**
  3700. * Gets a boolean indicating if the given quaternion is identity
  3701. * @param quaternion defines the quaternion to check
  3702. * @returns true if the quaternion is identity
  3703. */
  3704. public static IsIdentity(quaternion: Quaternion): boolean {
  3705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3706. }
  3707. /**
  3708. * Creates a quaternion from a rotation around an axis
  3709. * @param axis defines the axis to use
  3710. * @param angle defines the angle to use
  3711. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  3712. */
  3713. public static RotationAxis(axis: Vector3, angle: number): Quaternion {
  3714. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3715. }
  3716. /**
  3717. * Creates a rotation around an axis and stores it into the given quaternion
  3718. * @param axis defines the axis to use
  3719. * @param angle defines the angle to use
  3720. * @param result defines the target quaternion
  3721. * @returns the target quaternion
  3722. */
  3723. public static RotationAxisToRef(axis: Vector3, angle: number, result: Quaternion): Quaternion {
  3724. var sin = Math.sin(angle / 2);
  3725. axis.normalize();
  3726. result.w = Math.cos(angle / 2);
  3727. result.x = axis.x * sin;
  3728. result.y = axis.y * sin;
  3729. result.z = axis.z * sin;
  3730. return result;
  3731. }
  3732. /**
  3733. * Creates a new quaternion from data stored into an array
  3734. * @param array defines the data source
  3735. * @param offset defines the offset in the source array where the data starts
  3736. * @returns a new quaternion
  3737. */
  3738. public static FromArray(array: ArrayLike<number>, offset?: number): Quaternion {
  3739. if (!offset) {
  3740. offset = 0;
  3741. }
  3742. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3743. }
  3744. /**
  3745. * Create a quaternion from Euler rotation angles
  3746. * @param x Pitch
  3747. * @param y Yaw
  3748. * @param z Roll
  3749. * @returns the new Quaternion
  3750. */
  3751. public static FromEulerAngles(x: number, y: number, z: number): Quaternion {
  3752. var q = new Quaternion();
  3753. Quaternion.RotationYawPitchRollToRef(y, x, z, q);
  3754. return q;
  3755. }
  3756. /**
  3757. * Updates a quaternion from Euler rotation angles
  3758. * @param x Pitch
  3759. * @param y Yaw
  3760. * @param z Roll
  3761. * @param result the quaternion to store the result
  3762. * @returns the updated quaternion
  3763. */
  3764. public static FromEulerAnglesToRef(x: number, y: number, z: number, result: Quaternion): Quaternion {
  3765. Quaternion.RotationYawPitchRollToRef(y, x, z, result);
  3766. return result;
  3767. }
  3768. /**
  3769. * Create a quaternion from Euler rotation vector
  3770. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  3771. * @returns the new Quaternion
  3772. */
  3773. public static FromEulerVector(vec: Vector3): Quaternion {
  3774. var q = new Quaternion();
  3775. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, q);
  3776. return q;
  3777. }
  3778. /**
  3779. * Updates a quaternion from Euler rotation vector
  3780. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  3781. * @param result the quaternion to store the result
  3782. * @returns the updated quaternion
  3783. */
  3784. public static FromEulerVectorToRef(vec: Vector3, result: Quaternion): Quaternion {
  3785. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, result);
  3786. return result;
  3787. }
  3788. /**
  3789. * Creates a new quaternion from the given Euler float angles (y, x, z)
  3790. * @param yaw defines the rotation around Y axis
  3791. * @param pitch defines the rotation around X axis
  3792. * @param roll defines the rotation around Z axis
  3793. * @returns the new quaternion
  3794. */
  3795. public static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Quaternion {
  3796. var q = new Quaternion();
  3797. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3798. return q;
  3799. }
  3800. /**
  3801. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  3802. * @param yaw defines the rotation around Y axis
  3803. * @param pitch defines the rotation around X axis
  3804. * @param roll defines the rotation around Z axis
  3805. * @param result defines the target quaternion
  3806. */
  3807. public static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Quaternion): void {
  3808. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3809. var halfRoll = roll * 0.5;
  3810. var halfPitch = pitch * 0.5;
  3811. var halfYaw = yaw * 0.5;
  3812. var sinRoll = Math.sin(halfRoll);
  3813. var cosRoll = Math.cos(halfRoll);
  3814. var sinPitch = Math.sin(halfPitch);
  3815. var cosPitch = Math.cos(halfPitch);
  3816. var sinYaw = Math.sin(halfYaw);
  3817. var cosYaw = Math.cos(halfYaw);
  3818. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3819. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3820. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3821. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3822. }
  3823. /**
  3824. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  3825. * @param alpha defines the rotation around first axis
  3826. * @param beta defines the rotation around second axis
  3827. * @param gamma defines the rotation around third axis
  3828. * @returns the new quaternion
  3829. */
  3830. public static RotationAlphaBetaGamma(alpha: number, beta: number, gamma: number): Quaternion {
  3831. var result = new Quaternion();
  3832. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3833. return result;
  3834. }
  3835. /**
  3836. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  3837. * @param alpha defines the rotation around first axis
  3838. * @param beta defines the rotation around second axis
  3839. * @param gamma defines the rotation around third axis
  3840. * @param result defines the target quaternion
  3841. */
  3842. public static RotationAlphaBetaGammaToRef(alpha: number, beta: number, gamma: number, result: Quaternion): void {
  3843. // Produces a quaternion from Euler angles in the z-x-z orientation
  3844. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3845. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3846. var halfBeta = beta * 0.5;
  3847. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3848. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3849. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3850. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3851. }
  3852. /**
  3853. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  3854. * @param axis1 defines the first axis
  3855. * @param axis2 defines the second axis
  3856. * @param axis3 defines the third axis
  3857. * @returns the new quaternion
  3858. */
  3859. public static RotationQuaternionFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Quaternion {
  3860. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3861. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3862. return quat;
  3863. }
  3864. /**
  3865. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  3866. * @param axis1 defines the first axis
  3867. * @param axis2 defines the second axis
  3868. * @param axis3 defines the third axis
  3869. * @param ref defines the target quaternion
  3870. */
  3871. public static RotationQuaternionFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Quaternion): void {
  3872. var rotMat = MathTmp.Matrix[0];
  3873. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3874. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3875. }
  3876. /**
  3877. * Interpolates between two quaternions
  3878. * @param left defines first quaternion
  3879. * @param right defines second quaternion
  3880. * @param amount defines the gradient to use
  3881. * @returns the new interpolated quaternion
  3882. */
  3883. public static Slerp(left: Quaternion, right: Quaternion, amount: number): Quaternion {
  3884. var result = Quaternion.Identity();
  3885. Quaternion.SlerpToRef(left, right, amount, result);
  3886. return result;
  3887. }
  3888. /**
  3889. * Interpolates between two quaternions and stores it into a target quaternion
  3890. * @param left defines first quaternion
  3891. * @param right defines second quaternion
  3892. * @param amount defines the gradient to use
  3893. * @param result defines the target quaternion
  3894. */
  3895. public static SlerpToRef(left: Quaternion, right: Quaternion, amount: number, result: Quaternion): void {
  3896. var num2;
  3897. var num3;
  3898. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3899. var flag = false;
  3900. if (num4 < 0) {
  3901. flag = true;
  3902. num4 = -num4;
  3903. }
  3904. if (num4 > 0.999999) {
  3905. num3 = 1 - amount;
  3906. num2 = flag ? -amount : amount;
  3907. }
  3908. else {
  3909. var num5 = Math.acos(num4);
  3910. var num6 = (1.0 / Math.sin(num5));
  3911. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  3912. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  3913. }
  3914. result.x = (num3 * left.x) + (num2 * right.x);
  3915. result.y = (num3 * left.y) + (num2 * right.y);
  3916. result.z = (num3 * left.z) + (num2 * right.z);
  3917. result.w = (num3 * left.w) + (num2 * right.w);
  3918. }
  3919. /**
  3920. * Interpolate between two quaternions using Hermite interpolation
  3921. * @param value1 defines first quaternion
  3922. * @param tangent1 defines the incoming tangent
  3923. * @param value2 defines second quaternion
  3924. * @param tangent2 defines the outgoing tangent
  3925. * @param amount defines the target quaternion
  3926. * @returns the new interpolated quaternion
  3927. */
  3928. public static Hermite(value1: Quaternion, tangent1: Quaternion, value2: Quaternion, tangent2: Quaternion, amount: number): Quaternion {
  3929. var squared = amount * amount;
  3930. var cubed = amount * squared;
  3931. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3932. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3933. var part3 = (cubed - (2.0 * squared)) + amount;
  3934. var part4 = cubed - squared;
  3935. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3936. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3937. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3938. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3939. return new Quaternion(x, y, z, w);
  3940. }
  3941. }
  3942. /**
  3943. * Class used to store matrix data (4x4)
  3944. */
  3945. export class Matrix {
  3946. private static _updateFlagSeed = 0;
  3947. private static _identityReadOnly = Matrix.Identity();
  3948. private _isIdentity = false;
  3949. private _isIdentityDirty = true;
  3950. private _isIdentity3x2 = true;
  3951. private _isIdentity3x2Dirty = true;
  3952. /**
  3953. * Gets the update flag of the matrix which is an unique number for the matrix.
  3954. * It will be incremented every time the matrix data change.
  3955. * You can use it to speed the comparison between two versions of the same matrix.
  3956. */
  3957. public updateFlag: number;
  3958. private readonly _m: Float32Array = new Float32Array(16);
  3959. /**
  3960. * Gets the internal data of the matrix
  3961. */
  3962. public get m(): Readonly<Float32Array> { return this._m; }
  3963. /** @hidden */
  3964. public _markAsUpdated() {
  3965. this.updateFlag = Matrix._updateFlagSeed++;
  3966. this._isIdentity = false;
  3967. this._isIdentity3x2 = false;
  3968. this._isIdentityDirty = true;
  3969. this._isIdentity3x2Dirty = true;
  3970. }
  3971. /** @hidden */
  3972. private _updateIdentityStatus(isIdentity: boolean, isIdentityDirty: boolean = false, isIdentity3x2: boolean = false, isIdentity3x2Dirty: boolean = true) {
  3973. this.updateFlag = Matrix._updateFlagSeed++;
  3974. this._isIdentity = isIdentity;
  3975. this._isIdentity3x2 = isIdentity || isIdentity3x2;
  3976. this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
  3977. this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
  3978. }
  3979. /**
  3980. * Creates an empty matrix (filled with zeros)
  3981. */
  3982. public constructor() {
  3983. this._updateIdentityStatus(false);
  3984. }
  3985. // Properties
  3986. /**
  3987. * Check if the current matrix is identity
  3988. * @returns true is the matrix is the identity matrix
  3989. */
  3990. public isIdentity(): boolean {
  3991. if (this._isIdentityDirty) {
  3992. this._isIdentityDirty = false;
  3993. const m = this._m;
  3994. this._isIdentity = (
  3995. m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
  3996. m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
  3997. m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
  3998. m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0
  3999. );
  4000. }
  4001. return this._isIdentity;
  4002. }
  4003. /**
  4004. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  4005. * @returns true is the matrix is the identity matrix
  4006. */
  4007. public isIdentityAs3x2(): boolean {
  4008. if (this._isIdentity3x2Dirty) {
  4009. this._isIdentity3x2Dirty = false;
  4010. if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
  4011. this._isIdentity3x2 = false;
  4012. } else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
  4013. this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
  4014. this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
  4015. this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
  4016. this._isIdentity3x2 = false;
  4017. } else {
  4018. this._isIdentity3x2 = true;
  4019. }
  4020. }
  4021. return this._isIdentity3x2;
  4022. }
  4023. /**
  4024. * Gets the determinant of the matrix
  4025. * @returns the matrix determinant
  4026. */
  4027. public determinant(): number {
  4028. if (this._isIdentity === true) {
  4029. return 1;
  4030. }
  4031. const m = this._m;
  4032. const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  4033. const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  4034. const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  4035. const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  4036. // https://en.wikipedia.org/wiki/Laplace_expansion
  4037. // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
  4038. // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
  4039. // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
  4040. // where
  4041. // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
  4042. // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
  4043. //
  4044. // Here we do that for the 1st row.
  4045. const det_22_33 = m22 * m33 - m32 * m23;
  4046. const det_21_33 = m21 * m33 - m31 * m23;
  4047. const det_21_32 = m21 * m32 - m31 * m22;
  4048. const det_20_33 = m20 * m33 - m30 * m23;
  4049. const det_20_32 = m20 * m32 - m22 * m30;
  4050. const det_20_31 = m20 * m31 - m30 * m21;
  4051. const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  4052. const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  4053. const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  4054. const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  4055. return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  4056. }
  4057. // Methods
  4058. /**
  4059. * Returns the matrix as a Float32Array
  4060. * @returns the matrix underlying array
  4061. */
  4062. public toArray(): Readonly<Float32Array> {
  4063. return this._m;
  4064. }
  4065. /**
  4066. * Returns the matrix as a Float32Array
  4067. * @returns the matrix underlying array.
  4068. */
  4069. public asArray(): Readonly<Float32Array> {
  4070. return this._m;
  4071. }
  4072. /**
  4073. * Inverts the current matrix in place
  4074. * @returns the current inverted matrix
  4075. */
  4076. public invert(): Matrix {
  4077. this.invertToRef(this);
  4078. return this;
  4079. }
  4080. /**
  4081. * Sets all the matrix elements to zero
  4082. * @returns the current matrix
  4083. */
  4084. public reset(): Matrix {
  4085. Matrix.FromValuesToRef(
  4086. 0.0, 0.0, 0.0, 0.0,
  4087. 0.0, 0.0, 0.0, 0.0,
  4088. 0.0, 0.0, 0.0, 0.0,
  4089. 0.0, 0.0, 0.0, 0.0,
  4090. this
  4091. );
  4092. this._updateIdentityStatus(false);
  4093. return this;
  4094. }
  4095. /**
  4096. * Adds the current matrix with a second one
  4097. * @param other defines the matrix to add
  4098. * @returns a new matrix as the addition of the current matrix and the given one
  4099. */
  4100. public add(other: Matrix): Matrix {
  4101. var result = new Matrix();
  4102. this.addToRef(other, result);
  4103. return result;
  4104. }
  4105. /**
  4106. * Sets the given matrix "result" to the addition of the current matrix and the given one
  4107. * @param other defines the matrix to add
  4108. * @param result defines the target matrix
  4109. * @returns the current matrix
  4110. */
  4111. public addToRef(other: Matrix, result: Matrix): Matrix {
  4112. for (var index = 0; index < 16; index++) {
  4113. result._m[index] = this._m[index] + other._m[index];
  4114. }
  4115. result._markAsUpdated();
  4116. return this;
  4117. }
  4118. /**
  4119. * Adds in place the given matrix to the current matrix
  4120. * @param other defines the second operand
  4121. * @returns the current updated matrix
  4122. */
  4123. public addToSelf(other: Matrix): Matrix {
  4124. for (var index = 0; index < 16; index++) {
  4125. this._m[index] += other._m[index];
  4126. }
  4127. this._markAsUpdated();
  4128. return this;
  4129. }
  4130. /**
  4131. * Sets the given matrix to the current inverted Matrix
  4132. * @param other defines the target matrix
  4133. * @returns the unmodified current matrix
  4134. */
  4135. public invertToRef(other: Matrix): Matrix {
  4136. if (this._isIdentity === true) {
  4137. Matrix.IdentityToRef(other);
  4138. return this;
  4139. }
  4140. // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
  4141. const m = this._m;
  4142. const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  4143. const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  4144. const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  4145. const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  4146. const det_22_33 = m22 * m33 - m32 * m23;
  4147. const det_21_33 = m21 * m33 - m31 * m23;
  4148. const det_21_32 = m21 * m32 - m31 * m22;
  4149. const det_20_33 = m20 * m33 - m30 * m23;
  4150. const det_20_32 = m20 * m32 - m22 * m30;
  4151. const det_20_31 = m20 * m31 - m30 * m21;
  4152. const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  4153. const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  4154. const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  4155. const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  4156. const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  4157. if (det === 0) {
  4158. // not invertible
  4159. other.copyFrom(this);
  4160. return this;
  4161. }
  4162. const detInv = 1 / det;
  4163. const det_12_33 = m12 * m33 - m32 * m13;
  4164. const det_11_33 = m11 * m33 - m31 * m13;
  4165. const det_11_32 = m11 * m32 - m31 * m12;
  4166. const det_10_33 = m10 * m33 - m30 * m13;
  4167. const det_10_32 = m10 * m32 - m30 * m12;
  4168. const det_10_31 = m10 * m31 - m30 * m11;
  4169. const det_12_23 = m12 * m23 - m22 * m13;
  4170. const det_11_23 = m11 * m23 - m21 * m13;
  4171. const det_11_22 = m11 * m22 - m21 * m12;
  4172. const det_10_23 = m10 * m23 - m20 * m13;
  4173. const det_10_22 = m10 * m22 - m20 * m12;
  4174. const det_10_21 = m10 * m21 - m20 * m11;
  4175. const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
  4176. const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
  4177. const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
  4178. const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
  4179. const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
  4180. const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
  4181. const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
  4182. const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
  4183. const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
  4184. const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
  4185. const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
  4186. const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
  4187. Matrix.FromValuesToRef(
  4188. cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv,
  4189. cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv,
  4190. cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv,
  4191. cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv,
  4192. other
  4193. );
  4194. return this;
  4195. }
  4196. /**
  4197. * add a value at the specified position in the current Matrix
  4198. * @param index the index of the value within the matrix. between 0 and 15.
  4199. * @param value the value to be added
  4200. * @returns the current updated matrix
  4201. */
  4202. public addAtIndex(index: number, value: number): Matrix {
  4203. this._m[index] += value;
  4204. this._markAsUpdated();
  4205. return this;
  4206. }
  4207. /**
  4208. * mutiply the specified position in the current Matrix by a value
  4209. * @param index the index of the value within the matrix. between 0 and 15.
  4210. * @param value the value to be added
  4211. * @returns the current updated matrix
  4212. */
  4213. public multiplyAtIndex(index: number, value: number): Matrix {
  4214. this._m[index] *= value;
  4215. this._markAsUpdated();
  4216. return this;
  4217. }
  4218. /**
  4219. * Inserts the translation vector (using 3 floats) in the current matrix
  4220. * @param x defines the 1st component of the translation
  4221. * @param y defines the 2nd component of the translation
  4222. * @param z defines the 3rd component of the translation
  4223. * @returns the current updated matrix
  4224. */
  4225. public setTranslationFromFloats(x: number, y: number, z: number): Matrix {
  4226. this._m[12] = x;
  4227. this._m[13] = y;
  4228. this._m[14] = z;
  4229. this._markAsUpdated();
  4230. return this;
  4231. }
  4232. /**
  4233. * Inserts the translation vector in the current matrix
  4234. * @param vector3 defines the translation to insert
  4235. * @returns the current updated matrix
  4236. */
  4237. public setTranslation(vector3: Vector3): Matrix {
  4238. return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
  4239. }
  4240. /**
  4241. * Gets the translation value of the current matrix
  4242. * @returns a new Vector3 as the extracted translation from the matrix
  4243. */
  4244. public getTranslation(): Vector3 {
  4245. return new Vector3(this._m[12], this._m[13], this._m[14]);
  4246. }
  4247. /**
  4248. * Fill a Vector3 with the extracted translation from the matrix
  4249. * @param result defines the Vector3 where to store the translation
  4250. * @returns the current matrix
  4251. */
  4252. public getTranslationToRef(result: Vector3): Matrix {
  4253. result.x = this._m[12];
  4254. result.y = this._m[13];
  4255. result.z = this._m[14];
  4256. return this;
  4257. }
  4258. /**
  4259. * Remove rotation and scaling part from the matrix
  4260. * @returns the updated matrix
  4261. */
  4262. public removeRotationAndScaling(): Matrix {
  4263. const m = this.m;
  4264. Matrix.FromValuesToRef(
  4265. 1.0, 0.0, 0.0, 0.0,
  4266. 0.0, 1.0, 0.0, 0.0,
  4267. 0.0, 0.0, 1.0, 0.0,
  4268. m[12], m[13], m[14], m[15],
  4269. this
  4270. );
  4271. this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
  4272. return this;
  4273. }
  4274. /**
  4275. * Multiply two matrices
  4276. * @param other defines the second operand
  4277. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  4278. */
  4279. public multiply(other: Readonly<Matrix>): Matrix {
  4280. var result = new Matrix();
  4281. this.multiplyToRef(other, result);
  4282. return result;
  4283. }
  4284. /**
  4285. * Copy the current matrix from the given one
  4286. * @param other defines the source matrix
  4287. * @returns the current updated matrix
  4288. */
  4289. public copyFrom(other: Readonly<Matrix>): Matrix {
  4290. other.copyToArray(this._m);
  4291. const o = (other as Matrix);
  4292. this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
  4293. return this;
  4294. }
  4295. /**
  4296. * Populates the given array from the starting index with the current matrix values
  4297. * @param array defines the target array
  4298. * @param offset defines the offset in the target array where to start storing values
  4299. * @returns the current matrix
  4300. */
  4301. public copyToArray(array: Float32Array, offset: number = 0): Matrix {
  4302. for (var index = 0; index < 16; index++) {
  4303. array[offset + index] = this._m[index];
  4304. }
  4305. return this;
  4306. }
  4307. /**
  4308. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  4309. * @param other defines the second operand
  4310. * @param result defines the matrix where to store the multiplication
  4311. * @returns the current matrix
  4312. */
  4313. public multiplyToRef(other: Readonly<Matrix>, result: Matrix): Matrix {
  4314. if (this._isIdentity) {
  4315. result.copyFrom(other);
  4316. return this;
  4317. }
  4318. if ((other as Matrix)._isIdentity) {
  4319. result.copyFrom(this);
  4320. return this;
  4321. }
  4322. this.multiplyToArray(other, result._m, 0);
  4323. result._markAsUpdated();
  4324. return this;
  4325. }
  4326. /**
  4327. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  4328. * @param other defines the second operand
  4329. * @param result defines the array where to store the multiplication
  4330. * @param offset defines the offset in the target array where to start storing values
  4331. * @returns the current matrix
  4332. */
  4333. public multiplyToArray(other: Readonly<Matrix>, result: Float32Array, offset: number): Matrix {
  4334. const m = this._m;
  4335. const otherM = other.m;
  4336. var tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
  4337. var tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
  4338. var tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
  4339. var tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
  4340. var om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
  4341. var om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
  4342. var om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
  4343. var om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
  4344. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4345. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4346. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4347. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4348. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4349. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4350. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4351. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4352. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4353. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4354. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4355. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4356. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4357. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4358. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4359. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4360. return this;
  4361. }
  4362. /**
  4363. * Check equality between this matrix and a second one
  4364. * @param value defines the second matrix to compare
  4365. * @returns true is the current matrix and the given one values are strictly equal
  4366. */
  4367. public equals(value: Matrix): boolean {
  4368. const other = (value as Matrix);
  4369. if (!other) {
  4370. return false;
  4371. }
  4372. if (this._isIdentity || other._isIdentity) {
  4373. if (!this._isIdentityDirty && !other._isIdentityDirty) {
  4374. return this._isIdentity && other._isIdentity;
  4375. }
  4376. }
  4377. const m = this.m;
  4378. const om = other.m;
  4379. return (
  4380. m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
  4381. m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
  4382. m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
  4383. m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]
  4384. );
  4385. }
  4386. /**
  4387. * Clone the current matrix
  4388. * @returns a new matrix from the current matrix
  4389. */
  4390. public clone(): Matrix {
  4391. const matrix = new Matrix();
  4392. matrix.copyFrom(this);
  4393. return matrix;
  4394. }
  4395. /**
  4396. * Returns the name of the current matrix class
  4397. * @returns the string "Matrix"
  4398. */
  4399. public getClassName(): string {
  4400. return "Matrix";
  4401. }
  4402. /**
  4403. * Gets the hash code of the current matrix
  4404. * @returns the hash code
  4405. */
  4406. public getHashCode(): number {
  4407. let hash = this._m[0] || 0;
  4408. for (let i = 1; i < 16; i++) {
  4409. hash = (hash * 397) ^ (this._m[i] || 0);
  4410. }
  4411. return hash;
  4412. }
  4413. /**
  4414. * Decomposes the current Matrix into a translation, rotation and scaling components
  4415. * @param scale defines the scale vector3 given as a reference to update
  4416. * @param rotation defines the rotation quaternion given as a reference to update
  4417. * @param translation defines the translation vector3 given as a reference to update
  4418. * @returns true if operation was successful
  4419. */
  4420. public decompose(scale?: Vector3, rotation?: Quaternion, translation?: Vector3): boolean {
  4421. if (this._isIdentity) {
  4422. if (translation) {
  4423. translation.setAll(0);
  4424. }
  4425. if (scale) {
  4426. scale.setAll(1);
  4427. }
  4428. if (rotation) {
  4429. rotation.copyFromFloats(0, 0, 0, 1);
  4430. }
  4431. return true;
  4432. }
  4433. const m = this._m;
  4434. if (translation) {
  4435. translation.copyFromFloats(m[12], m[13], m[14]);
  4436. }
  4437. scale = scale || MathTmp.Vector3[0];
  4438. scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4439. scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4440. scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4441. if (this.determinant() <= 0) {
  4442. scale.y *= -1;
  4443. }
  4444. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4445. if (rotation) {
  4446. rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
  4447. }
  4448. return false;
  4449. }
  4450. if (rotation) {
  4451. const sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  4452. Matrix.FromValuesToRef(
  4453. m[0] * sx, m[1] * sx, m[2] * sx, 0.0,
  4454. m[4] * sy, m[5] * sy, m[6] * sy, 0.0,
  4455. m[8] * sz, m[9] * sz, m[10] * sz, 0.0,
  4456. 0.0, 0.0, 0.0, 1.0,
  4457. MathTmp.Matrix[0]
  4458. );
  4459. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4460. }
  4461. return true;
  4462. }
  4463. /**
  4464. * Gets specific row of the matrix
  4465. * @param index defines the number of the row to get
  4466. * @returns the index-th row of the current matrix as a new Vector4
  4467. */
  4468. public getRow(index: number): Nullable<Vector4> {
  4469. if (index < 0 || index > 3) {
  4470. return null;
  4471. }
  4472. var i = index * 4;
  4473. return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
  4474. }
  4475. /**
  4476. * Sets the index-th row of the current matrix to the vector4 values
  4477. * @param index defines the number of the row to set
  4478. * @param row defines the target vector4
  4479. * @returns the updated current matrix
  4480. */
  4481. public setRow(index: number, row: Vector4): Matrix {
  4482. return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
  4483. }
  4484. /**
  4485. * Compute the transpose of the matrix
  4486. * @returns the new transposed matrix
  4487. */
  4488. public transpose(): Matrix {
  4489. return Matrix.Transpose(this);
  4490. }
  4491. /**
  4492. * Compute the transpose of the matrix and store it in a given matrix
  4493. * @param result defines the target matrix
  4494. * @returns the current matrix
  4495. */
  4496. public transposeToRef(result: Matrix): Matrix {
  4497. Matrix.TransposeToRef(this, result);
  4498. return this;
  4499. }
  4500. /**
  4501. * Sets the index-th row of the current matrix with the given 4 x float values
  4502. * @param index defines the row index
  4503. * @param x defines the x component to set
  4504. * @param y defines the y component to set
  4505. * @param z defines the z component to set
  4506. * @param w defines the w component to set
  4507. * @returns the updated current matrix
  4508. */
  4509. public setRowFromFloats(index: number, x: number, y: number, z: number, w: number): Matrix {
  4510. if (index < 0 || index > 3) {
  4511. return this;
  4512. }
  4513. var i = index * 4;
  4514. this._m[i + 0] = x;
  4515. this._m[i + 1] = y;
  4516. this._m[i + 2] = z;
  4517. this._m[i + 3] = w;
  4518. this._markAsUpdated();
  4519. return this;
  4520. }
  4521. /**
  4522. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  4523. * @param scale defines the scale factor
  4524. * @returns a new matrix
  4525. */
  4526. public scale(scale: number): Matrix {
  4527. var result = new Matrix();
  4528. this.scaleToRef(scale, result);
  4529. return result;
  4530. }
  4531. /**
  4532. * Scale the current matrix values by a factor to a given result matrix
  4533. * @param scale defines the scale factor
  4534. * @param result defines the matrix to store the result
  4535. * @returns the current matrix
  4536. */
  4537. public scaleToRef(scale: number, result: Matrix): Matrix {
  4538. for (var index = 0; index < 16; index++) {
  4539. result._m[index] = this._m[index] * scale;
  4540. }
  4541. result._markAsUpdated();
  4542. return this;
  4543. }
  4544. /**
  4545. * Scale the current matrix values by a factor and add the result to a given matrix
  4546. * @param scale defines the scale factor
  4547. * @param result defines the Matrix to store the result
  4548. * @returns the current matrix
  4549. */
  4550. public scaleAndAddToRef(scale: number, result: Matrix): Matrix {
  4551. for (var index = 0; index < 16; index++) {
  4552. result._m[index] += this._m[index] * scale;
  4553. }
  4554. result._markAsUpdated();
  4555. return this;
  4556. }
  4557. /**
  4558. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4559. * @param ref matrix to store the result
  4560. */
  4561. public toNormalMatrix(ref: Matrix): void {
  4562. const tmp = MathTmp.Matrix[0];
  4563. this.invertToRef(tmp);
  4564. tmp.transposeToRef(ref);
  4565. var m = ref._m;
  4566. Matrix.FromValuesToRef(
  4567. m[0], m[1], m[2], 0.0,
  4568. m[4], m[5], m[6], 0.0,
  4569. m[8], m[9], m[10], 0.0,
  4570. 0.0, 0.0, 0.0, 1.0,
  4571. ref
  4572. );
  4573. }
  4574. /**
  4575. * Gets only rotation part of the current matrix
  4576. * @returns a new matrix sets to the extracted rotation matrix from the current one
  4577. */
  4578. public getRotationMatrix(): Matrix {
  4579. var result = new Matrix();
  4580. this.getRotationMatrixToRef(result);
  4581. return result;
  4582. }
  4583. /**
  4584. * Extracts the rotation matrix from the current one and sets it as the given "result"
  4585. * @param result defines the target matrix to store data to
  4586. * @returns the current matrix
  4587. */
  4588. public getRotationMatrixToRef(result: Matrix): Matrix {
  4589. const scale = MathTmp.Vector3[0];
  4590. if (!this.decompose(scale)) {
  4591. Matrix.IdentityToRef(result);
  4592. return this;
  4593. }
  4594. const m = this._m;
  4595. const sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  4596. Matrix.FromValuesToRef(
  4597. m[0] * sx, m[1] * sx, m[2] * sx, 0.0,
  4598. m[4] * sy, m[5] * sy, m[6] * sy, 0.0,
  4599. m[8] * sz, m[9] * sz, m[10] * sz, 0.0,
  4600. 0.0, 0.0, 0.0, 1.0,
  4601. result
  4602. );
  4603. return this;
  4604. }
  4605. /**
  4606. * Toggles model matrix from being right handed to left handed in place and vice versa
  4607. */
  4608. public toggleModelMatrixHandInPlace() {
  4609. const m = this._m;
  4610. m[2] *= -1;
  4611. m[6] *= -1;
  4612. m[8] *= -1;
  4613. m[9] *= -1;
  4614. m[14] *= -1;
  4615. this._markAsUpdated();
  4616. }
  4617. /**
  4618. * Toggles projection matrix from being right handed to left handed in place and vice versa
  4619. */
  4620. public toggleProjectionMatrixHandInPlace() {
  4621. var m = this._m;
  4622. m[8] *= -1;
  4623. m[9] *= -1;
  4624. m[10] *= -1;
  4625. m[11] *= -1;
  4626. this._markAsUpdated();
  4627. }
  4628. // Statics
  4629. /**
  4630. * Creates a matrix from an array
  4631. * @param array defines the source array
  4632. * @param offset defines an offset in the source array
  4633. * @returns a new Matrix set from the starting index of the given array
  4634. */
  4635. public static FromArray(array: ArrayLike<number>, offset: number = 0): Matrix {
  4636. var result = new Matrix();
  4637. Matrix.FromArrayToRef(array, offset, result);
  4638. return result;
  4639. }
  4640. /**
  4641. * Copy the content of an array into a given matrix
  4642. * @param array defines the source array
  4643. * @param offset defines an offset in the source array
  4644. * @param result defines the target matrix
  4645. */
  4646. public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Matrix) {
  4647. for (var index = 0; index < 16; index++) {
  4648. result._m[index] = array[index + offset];
  4649. }
  4650. result._markAsUpdated();
  4651. }
  4652. /**
  4653. * Stores an array into a matrix after having multiplied each component by a given factor
  4654. * @param array defines the source array
  4655. * @param offset defines the offset in the source array
  4656. * @param scale defines the scaling factor
  4657. * @param result defines the target matrix
  4658. */
  4659. public static FromFloat32ArrayToRefScaled(array: Float32Array, offset: number, scale: number, result: Matrix) {
  4660. for (var index = 0; index < 16; index++) {
  4661. result._m[index] = array[index + offset] * scale;
  4662. }
  4663. result._markAsUpdated();
  4664. }
  4665. /**
  4666. * Gets an identity matrix that must not be updated
  4667. */
  4668. public static get IdentityReadOnly(): Readonly<Matrix> {
  4669. return Matrix._identityReadOnly;
  4670. }
  4671. /**
  4672. * Stores a list of values (16) inside a given matrix
  4673. * @param initialM11 defines 1st value of 1st row
  4674. * @param initialM12 defines 2nd value of 1st row
  4675. * @param initialM13 defines 3rd value of 1st row
  4676. * @param initialM14 defines 4th value of 1st row
  4677. * @param initialM21 defines 1st value of 2nd row
  4678. * @param initialM22 defines 2nd value of 2nd row
  4679. * @param initialM23 defines 3rd value of 2nd row
  4680. * @param initialM24 defines 4th value of 2nd row
  4681. * @param initialM31 defines 1st value of 3rd row
  4682. * @param initialM32 defines 2nd value of 3rd row
  4683. * @param initialM33 defines 3rd value of 3rd row
  4684. * @param initialM34 defines 4th value of 3rd row
  4685. * @param initialM41 defines 1st value of 4th row
  4686. * @param initialM42 defines 2nd value of 4th row
  4687. * @param initialM43 defines 3rd value of 4th row
  4688. * @param initialM44 defines 4th value of 4th row
  4689. * @param result defines the target matrix
  4690. */
  4691. public static FromValuesToRef(initialM11: number, initialM12: number, initialM13: number, initialM14: number,
  4692. initialM21: number, initialM22: number, initialM23: number, initialM24: number,
  4693. initialM31: number, initialM32: number, initialM33: number, initialM34: number,
  4694. initialM41: number, initialM42: number, initialM43: number, initialM44: number, result: Matrix): void {
  4695. const m = result._m;
  4696. m[0] = initialM11; m[1] = initialM12; m[2] = initialM13; m[3] = initialM14;
  4697. m[4] = initialM21; m[5] = initialM22; m[6] = initialM23; m[7] = initialM24;
  4698. m[8] = initialM31; m[9] = initialM32; m[10] = initialM33; m[11] = initialM34;
  4699. m[12] = initialM41; m[13] = initialM42; m[14] = initialM43; m[15] = initialM44;
  4700. result._markAsUpdated();
  4701. }
  4702. /**
  4703. * Creates new matrix from a list of values (16)
  4704. * @param initialM11 defines 1st value of 1st row
  4705. * @param initialM12 defines 2nd value of 1st row
  4706. * @param initialM13 defines 3rd value of 1st row
  4707. * @param initialM14 defines 4th value of 1st row
  4708. * @param initialM21 defines 1st value of 2nd row
  4709. * @param initialM22 defines 2nd value of 2nd row
  4710. * @param initialM23 defines 3rd value of 2nd row
  4711. * @param initialM24 defines 4th value of 2nd row
  4712. * @param initialM31 defines 1st value of 3rd row
  4713. * @param initialM32 defines 2nd value of 3rd row
  4714. * @param initialM33 defines 3rd value of 3rd row
  4715. * @param initialM34 defines 4th value of 3rd row
  4716. * @param initialM41 defines 1st value of 4th row
  4717. * @param initialM42 defines 2nd value of 4th row
  4718. * @param initialM43 defines 3rd value of 4th row
  4719. * @param initialM44 defines 4th value of 4th row
  4720. * @returns the new matrix
  4721. */
  4722. public static FromValues(initialM11: number, initialM12: number, initialM13: number, initialM14: number,
  4723. initialM21: number, initialM22: number, initialM23: number, initialM24: number,
  4724. initialM31: number, initialM32: number, initialM33: number, initialM34: number,
  4725. initialM41: number, initialM42: number, initialM43: number, initialM44: number): Matrix {
  4726. var result = new Matrix();
  4727. const m = result._m;
  4728. m[0] = initialM11; m[1] = initialM12; m[2] = initialM13; m[3] = initialM14;
  4729. m[4] = initialM21; m[5] = initialM22; m[6] = initialM23; m[7] = initialM24;
  4730. m[8] = initialM31; m[9] = initialM32; m[10] = initialM33; m[11] = initialM34;
  4731. m[12] = initialM41; m[13] = initialM42; m[14] = initialM43; m[15] = initialM44;
  4732. result._markAsUpdated();
  4733. return result;
  4734. }
  4735. /**
  4736. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  4737. * @param scale defines the scale vector3
  4738. * @param rotation defines the rotation quaternion
  4739. * @param translation defines the translation vector3
  4740. * @returns a new matrix
  4741. */
  4742. public static Compose(scale: Vector3, rotation: Quaternion, translation: Vector3): Matrix {
  4743. var result = new Matrix();
  4744. Matrix.ComposeToRef(scale, rotation, translation, result);
  4745. return result;
  4746. }
  4747. /**
  4748. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  4749. * @param scale defines the scale vector3
  4750. * @param rotation defines the rotation quaternion
  4751. * @param translation defines the translation vector3
  4752. * @param result defines the target matrix
  4753. */
  4754. public static ComposeToRef(scale: Vector3, rotation: Quaternion, translation: Vector3, result: Matrix): void {
  4755. Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
  4756. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4757. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4758. result.setTranslation(translation);
  4759. }
  4760. /**
  4761. * Creates a new identity matrix
  4762. * @returns a new identity matrix
  4763. */
  4764. public static Identity(): Matrix {
  4765. const identity = Matrix.FromValues(
  4766. 1.0, 0.0, 0.0, 0.0,
  4767. 0.0, 1.0, 0.0, 0.0,
  4768. 0.0, 0.0, 1.0, 0.0,
  4769. 0.0, 0.0, 0.0, 1.0);
  4770. identity._updateIdentityStatus(true);
  4771. return identity;
  4772. }
  4773. /**
  4774. * Creates a new identity matrix and stores the result in a given matrix
  4775. * @param result defines the target matrix
  4776. */
  4777. public static IdentityToRef(result: Matrix): void {
  4778. Matrix.FromValuesToRef(
  4779. 1.0, 0.0, 0.0, 0.0,
  4780. 0.0, 1.0, 0.0, 0.0,
  4781. 0.0, 0.0, 1.0, 0.0,
  4782. 0.0, 0.0, 0.0, 1.0,
  4783. result
  4784. );
  4785. result._updateIdentityStatus(true);
  4786. }
  4787. /**
  4788. * Creates a new zero matrix
  4789. * @returns a new zero matrix
  4790. */
  4791. public static Zero(): Matrix {
  4792. const zero = Matrix.FromValues(
  4793. 0.0, 0.0, 0.0, 0.0,
  4794. 0.0, 0.0, 0.0, 0.0,
  4795. 0.0, 0.0, 0.0, 0.0,
  4796. 0.0, 0.0, 0.0, 0.0);
  4797. zero._updateIdentityStatus(false);
  4798. return zero;
  4799. }
  4800. /**
  4801. * Creates a new rotation matrix for "angle" radians around the X axis
  4802. * @param angle defines the angle (in radians) to use
  4803. * @return the new matrix
  4804. */
  4805. public static RotationX(angle: number): Matrix {
  4806. var result = new Matrix();
  4807. Matrix.RotationXToRef(angle, result);
  4808. return result;
  4809. }
  4810. /**
  4811. * Creates a new matrix as the invert of a given matrix
  4812. * @param source defines the source matrix
  4813. * @returns the new matrix
  4814. */
  4815. public static Invert(source: Matrix): Matrix {
  4816. var result = new Matrix();
  4817. source.invertToRef(result);
  4818. return result;
  4819. }
  4820. /**
  4821. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  4822. * @param angle defines the angle (in radians) to use
  4823. * @param result defines the target matrix
  4824. */
  4825. public static RotationXToRef(angle: number, result: Matrix): void {
  4826. var s = Math.sin(angle);
  4827. var c = Math.cos(angle);
  4828. Matrix.FromValuesToRef(
  4829. 1.0, 0.0, 0.0, 0.0,
  4830. 0.0, c, s, 0.0,
  4831. 0.0, -s, c, 0.0,
  4832. 0.0, 0.0, 0.0, 1.0,
  4833. result
  4834. );
  4835. result._updateIdentityStatus(c === 1 && s === 0);
  4836. }
  4837. /**
  4838. * Creates a new rotation matrix for "angle" radians around the Y axis
  4839. * @param angle defines the angle (in radians) to use
  4840. * @return the new matrix
  4841. */
  4842. public static RotationY(angle: number): Matrix {
  4843. var result = new Matrix();
  4844. Matrix.RotationYToRef(angle, result);
  4845. return result;
  4846. }
  4847. /**
  4848. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  4849. * @param angle defines the angle (in radians) to use
  4850. * @param result defines the target matrix
  4851. */
  4852. public static RotationYToRef(angle: number, result: Matrix): void {
  4853. var s = Math.sin(angle);
  4854. var c = Math.cos(angle);
  4855. Matrix.FromValuesToRef(
  4856. c, 0.0, -s, 0.0,
  4857. 0.0, 1.0, 0.0, 0.0,
  4858. s, 0.0, c, 0.0,
  4859. 0.0, 0.0, 0.0, 1.0,
  4860. result
  4861. );
  4862. result._updateIdentityStatus(c === 1 && s === 0);
  4863. }
  4864. /**
  4865. * Creates a new rotation matrix for "angle" radians around the Z axis
  4866. * @param angle defines the angle (in radians) to use
  4867. * @return the new matrix
  4868. */
  4869. public static RotationZ(angle: number): Matrix {
  4870. var result = new Matrix();
  4871. Matrix.RotationZToRef(angle, result);
  4872. return result;
  4873. }
  4874. /**
  4875. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  4876. * @param angle defines the angle (in radians) to use
  4877. * @param result defines the target matrix
  4878. */
  4879. public static RotationZToRef(angle: number, result: Matrix): void {
  4880. var s = Math.sin(angle);
  4881. var c = Math.cos(angle);
  4882. Matrix.FromValuesToRef(
  4883. c, s, 0.0, 0.0,
  4884. -s, c, 0.0, 0.0,
  4885. 0.0, 0.0, 1.0, 0.0,
  4886. 0.0, 0.0, 0.0, 1.0,
  4887. result
  4888. );
  4889. result._updateIdentityStatus(c === 1 && s === 0);
  4890. }
  4891. /**
  4892. * Creates a new rotation matrix for "angle" radians around the given axis
  4893. * @param axis defines the axis to use
  4894. * @param angle defines the angle (in radians) to use
  4895. * @return the new matrix
  4896. */
  4897. public static RotationAxis(axis: Vector3, angle: number): Matrix {
  4898. var result = new Matrix();
  4899. Matrix.RotationAxisToRef(axis, angle, result);
  4900. return result;
  4901. }
  4902. /**
  4903. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  4904. * @param axis defines the axis to use
  4905. * @param angle defines the angle (in radians) to use
  4906. * @param result defines the target matrix
  4907. */
  4908. public static RotationAxisToRef(axis: Vector3, angle: number, result: Matrix): void {
  4909. var s = Math.sin(-angle);
  4910. var c = Math.cos(-angle);
  4911. var c1 = 1 - c;
  4912. axis.normalize();
  4913. const m = result._m;
  4914. m[0] = (axis.x * axis.x) * c1 + c;
  4915. m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4916. m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4917. m[3] = 0.0;
  4918. m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4919. m[5] = (axis.y * axis.y) * c1 + c;
  4920. m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4921. m[7] = 0.0;
  4922. m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4923. m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4924. m[10] = (axis.z * axis.z) * c1 + c;
  4925. m[11] = 0.0;
  4926. m[12] = 0.0;
  4927. m[13] = 0.0;
  4928. m[14] = 0.0;
  4929. m[15] = 1.0;
  4930. result._markAsUpdated();
  4931. }
  4932. /**
  4933. * Creates a rotation matrix
  4934. * @param yaw defines the yaw angle in radians (Y axis)
  4935. * @param pitch defines the pitch angle in radians (X axis)
  4936. * @param roll defines the roll angle in radians (X axis)
  4937. * @returns the new rotation matrix
  4938. */
  4939. public static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Matrix {
  4940. var result = new Matrix();
  4941. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4942. return result;
  4943. }
  4944. /**
  4945. * Creates a rotation matrix and stores it in a given matrix
  4946. * @param yaw defines the yaw angle in radians (Y axis)
  4947. * @param pitch defines the pitch angle in radians (X axis)
  4948. * @param roll defines the roll angle in radians (X axis)
  4949. * @param result defines the target matrix
  4950. */
  4951. public static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Matrix): void {
  4952. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
  4953. MathTmp.Quaternion[0].toRotationMatrix(result);
  4954. }
  4955. /**
  4956. * Creates a scaling matrix
  4957. * @param x defines the scale factor on X axis
  4958. * @param y defines the scale factor on Y axis
  4959. * @param z defines the scale factor on Z axis
  4960. * @returns the new matrix
  4961. */
  4962. public static Scaling(x: number, y: number, z: number): Matrix {
  4963. var result = new Matrix();
  4964. Matrix.ScalingToRef(x, y, z, result);
  4965. return result;
  4966. }
  4967. /**
  4968. * Creates a scaling matrix and stores it in a given matrix
  4969. * @param x defines the scale factor on X axis
  4970. * @param y defines the scale factor on Y axis
  4971. * @param z defines the scale factor on Z axis
  4972. * @param result defines the target matrix
  4973. */
  4974. public static ScalingToRef(x: number, y: number, z: number, result: Matrix): void {
  4975. Matrix.FromValuesToRef(
  4976. x, 0.0, 0.0, 0.0,
  4977. 0.0, y, 0.0, 0.0,
  4978. 0.0, 0.0, z, 0.0,
  4979. 0.0, 0.0, 0.0, 1.0,
  4980. result
  4981. );
  4982. result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
  4983. }
  4984. /**
  4985. * Creates a translation matrix
  4986. * @param x defines the translation on X axis
  4987. * @param y defines the translation on Y axis
  4988. * @param z defines the translationon Z axis
  4989. * @returns the new matrix
  4990. */
  4991. public static Translation(x: number, y: number, z: number): Matrix {
  4992. var result = new Matrix();
  4993. Matrix.TranslationToRef(x, y, z, result);
  4994. return result;
  4995. }
  4996. /**
  4997. * Creates a translation matrix and stores it in a given matrix
  4998. * @param x defines the translation on X axis
  4999. * @param y defines the translation on Y axis
  5000. * @param z defines the translationon Z axis
  5001. * @param result defines the target matrix
  5002. */
  5003. public static TranslationToRef(x: number, y: number, z: number, result: Matrix): void {
  5004. Matrix.FromValuesToRef(
  5005. 1.0, 0.0, 0.0, 0.0,
  5006. 0.0, 1.0, 0.0, 0.0,
  5007. 0.0, 0.0, 1.0, 0.0,
  5008. x, y, z, 1.0,
  5009. result
  5010. );
  5011. result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
  5012. }
  5013. /**
  5014. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5015. * @param startValue defines the start value
  5016. * @param endValue defines the end value
  5017. * @param gradient defines the gradient factor
  5018. * @returns the new matrix
  5019. */
  5020. public static Lerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
  5021. var result = new Matrix();
  5022. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5023. return result;
  5024. }
  5025. /**
  5026. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5027. * @param startValue defines the start value
  5028. * @param endValue defines the end value
  5029. * @param gradient defines the gradient factor
  5030. * @param result defines the Matrix object where to store data
  5031. */
  5032. public static LerpToRef(startValue: Matrix, endValue: Matrix, gradient: number, result: Matrix): void {
  5033. for (var index = 0; index < 16; index++) {
  5034. result._m[index] = startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;
  5035. }
  5036. result._markAsUpdated();
  5037. }
  5038. /**
  5039. * Builds a new matrix whose values are computed by:
  5040. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5041. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5042. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5043. * @param startValue defines the first matrix
  5044. * @param endValue defines the second matrix
  5045. * @param gradient defines the gradient between the two matrices
  5046. * @returns the new matrix
  5047. */
  5048. public static DecomposeLerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
  5049. var result = new Matrix();
  5050. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5051. return result;
  5052. }
  5053. /**
  5054. * Update a matrix to values which are computed by:
  5055. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5056. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5057. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5058. * @param startValue defines the first matrix
  5059. * @param endValue defines the second matrix
  5060. * @param gradient defines the gradient between the two matrices
  5061. * @param result defines the target matrix
  5062. */
  5063. public static DecomposeLerpToRef(startValue: Matrix, endValue: Matrix, gradient: number, result: Matrix) {
  5064. var startScale = MathTmp.Vector3[0];
  5065. var startRotation = MathTmp.Quaternion[0];
  5066. var startTranslation = MathTmp.Vector3[1];
  5067. startValue.decompose(startScale, startRotation, startTranslation);
  5068. var endScale = MathTmp.Vector3[2];
  5069. var endRotation = MathTmp.Quaternion[1];
  5070. var endTranslation = MathTmp.Vector3[3];
  5071. endValue.decompose(endScale, endRotation, endTranslation);
  5072. var resultScale = MathTmp.Vector3[4];
  5073. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5074. var resultRotation = MathTmp.Quaternion[2];
  5075. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5076. var resultTranslation = MathTmp.Vector3[5];
  5077. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5078. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5079. }
  5080. /**
  5081. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  5082. * This function works in left handed mode
  5083. * @param eye defines the final position of the entity
  5084. * @param target defines where the entity should look at
  5085. * @param up defines the up vector for the entity
  5086. * @returns the new matrix
  5087. */
  5088. public static LookAtLH(eye: Vector3, target: Vector3, up: Vector3): Matrix {
  5089. var result = new Matrix();
  5090. Matrix.LookAtLHToRef(eye, target, up, result);
  5091. return result;
  5092. }
  5093. /**
  5094. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  5095. * This function works in left handed mode
  5096. * @param eye defines the final position of the entity
  5097. * @param target defines where the entity should look at
  5098. * @param up defines the up vector for the entity
  5099. * @param result defines the target matrix
  5100. */
  5101. public static LookAtLHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void {
  5102. const xAxis = MathTmp.Vector3[0];
  5103. const yAxis = MathTmp.Vector3[1];
  5104. const zAxis = MathTmp.Vector3[2];
  5105. // Z axis
  5106. target.subtractToRef(eye, zAxis);
  5107. zAxis.normalize();
  5108. // X axis
  5109. Vector3.CrossToRef(up, zAxis, xAxis);
  5110. const xSquareLength = xAxis.lengthSquared();
  5111. if (xSquareLength === 0) {
  5112. xAxis.x = 1.0;
  5113. } else {
  5114. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  5115. }
  5116. // Y axis
  5117. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  5118. yAxis.normalize();
  5119. // Eye angles
  5120. var ex = -Vector3.Dot(xAxis, eye);
  5121. var ey = -Vector3.Dot(yAxis, eye);
  5122. var ez = -Vector3.Dot(zAxis, eye);
  5123. Matrix.FromValuesToRef(
  5124. xAxis.x, yAxis.x, zAxis.x, 0.0,
  5125. xAxis.y, yAxis.y, zAxis.y, 0.0,
  5126. xAxis.z, yAxis.z, zAxis.z, 0.0,
  5127. ex, ey, ez, 1.0,
  5128. result
  5129. );
  5130. }
  5131. /**
  5132. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  5133. * This function works in right handed mode
  5134. * @param eye defines the final position of the entity
  5135. * @param target defines where the entity should look at
  5136. * @param up defines the up vector for the entity
  5137. * @returns the new matrix
  5138. */
  5139. public static LookAtRH(eye: Vector3, target: Vector3, up: Vector3): Matrix {
  5140. var result = new Matrix();
  5141. Matrix.LookAtRHToRef(eye, target, up, result);
  5142. return result;
  5143. }
  5144. /**
  5145. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  5146. * This function works in right handed mode
  5147. * @param eye defines the final position of the entity
  5148. * @param target defines where the entity should look at
  5149. * @param up defines the up vector for the entity
  5150. * @param result defines the target matrix
  5151. */
  5152. public static LookAtRHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void {
  5153. const xAxis = MathTmp.Vector3[0];
  5154. const yAxis = MathTmp.Vector3[1];
  5155. const zAxis = MathTmp.Vector3[2];
  5156. // Z axis
  5157. eye.subtractToRef(target, zAxis);
  5158. zAxis.normalize();
  5159. // X axis
  5160. Vector3.CrossToRef(up, zAxis, xAxis);
  5161. const xSquareLength = xAxis.lengthSquared();
  5162. if (xSquareLength === 0) {
  5163. xAxis.x = 1.0;
  5164. } else {
  5165. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  5166. }
  5167. // Y axis
  5168. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  5169. yAxis.normalize();
  5170. // Eye angles
  5171. var ex = -Vector3.Dot(xAxis, eye);
  5172. var ey = -Vector3.Dot(yAxis, eye);
  5173. var ez = -Vector3.Dot(zAxis, eye);
  5174. Matrix.FromValuesToRef(
  5175. xAxis.x, yAxis.x, zAxis.x, 0.0,
  5176. xAxis.y, yAxis.y, zAxis.y, 0.0,
  5177. xAxis.z, yAxis.z, zAxis.z, 0.0,
  5178. ex, ey, ez, 1.0,
  5179. result
  5180. );
  5181. }
  5182. /**
  5183. * Create a left-handed orthographic projection matrix
  5184. * @param width defines the viewport width
  5185. * @param height defines the viewport height
  5186. * @param znear defines the near clip plane
  5187. * @param zfar defines the far clip plane
  5188. * @returns a new matrix as a left-handed orthographic projection matrix
  5189. */
  5190. public static OrthoLH(width: number, height: number, znear: number, zfar: number): Matrix {
  5191. var matrix = new Matrix();
  5192. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5193. return matrix;
  5194. }
  5195. /**
  5196. * Store a left-handed orthographic projection to a given matrix
  5197. * @param width defines the viewport width
  5198. * @param height defines the viewport height
  5199. * @param znear defines the near clip plane
  5200. * @param zfar defines the far clip plane
  5201. * @param result defines the target matrix
  5202. */
  5203. public static OrthoLHToRef(width: number, height: number, znear: number, zfar: number, result: Matrix): void {
  5204. let n = znear;
  5205. let f = zfar;
  5206. let a = 2.0 / width;
  5207. let b = 2.0 / height;
  5208. let c = 2.0 / (f - n);
  5209. let d = -(f + n) / (f - n);
  5210. Matrix.FromValuesToRef(
  5211. a, 0.0, 0.0, 0.0,
  5212. 0.0, b, 0.0, 0.0,
  5213. 0.0, 0.0, c, 0.0,
  5214. 0.0, 0.0, d, 1.0,
  5215. result
  5216. );
  5217. result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
  5218. }
  5219. /**
  5220. * Create a left-handed orthographic projection matrix
  5221. * @param left defines the viewport left coordinate
  5222. * @param right defines the viewport right coordinate
  5223. * @param bottom defines the viewport bottom coordinate
  5224. * @param top defines the viewport top coordinate
  5225. * @param znear defines the near clip plane
  5226. * @param zfar defines the far clip plane
  5227. * @returns a new matrix as a left-handed orthographic projection matrix
  5228. */
  5229. public static OrthoOffCenterLH(left: number, right: number, bottom: number, top: number, znear: number, zfar: number): Matrix {
  5230. var matrix = new Matrix();
  5231. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5232. return matrix;
  5233. }
  5234. /**
  5235. * Stores a left-handed orthographic projection into a given matrix
  5236. * @param left defines the viewport left coordinate
  5237. * @param right defines the viewport right coordinate
  5238. * @param bottom defines the viewport bottom coordinate
  5239. * @param top defines the viewport top coordinate
  5240. * @param znear defines the near clip plane
  5241. * @param zfar defines the far clip plane
  5242. * @param result defines the target matrix
  5243. */
  5244. public static OrthoOffCenterLHToRef(left: number, right: number, bottom: number, top: number, znear: number, zfar: number, result: Matrix): void {
  5245. let n = znear;
  5246. let f = zfar;
  5247. let a = 2.0 / (right - left);
  5248. let b = 2.0 / (top - bottom);
  5249. let c = 2.0 / (f - n);
  5250. let d = -(f + n) / (f - n);
  5251. let i0 = (left + right) / (left - right);
  5252. let i1 = (top + bottom) / (bottom - top);
  5253. Matrix.FromValuesToRef(
  5254. a, 0.0, 0.0, 0.0,
  5255. 0.0, b, 0.0, 0.0,
  5256. 0.0, 0.0, c, 0.0,
  5257. i0, i1, d, 1.0,
  5258. result
  5259. );
  5260. result._markAsUpdated();
  5261. }
  5262. /**
  5263. * Creates a right-handed orthographic projection matrix
  5264. * @param left defines the viewport left coordinate
  5265. * @param right defines the viewport right coordinate
  5266. * @param bottom defines the viewport bottom coordinate
  5267. * @param top defines the viewport top coordinate
  5268. * @param znear defines the near clip plane
  5269. * @param zfar defines the far clip plane
  5270. * @returns a new matrix as a right-handed orthographic projection matrix
  5271. */
  5272. public static OrthoOffCenterRH(left: number, right: number, bottom: number, top: number, znear: number, zfar: number): Matrix {
  5273. var matrix = new Matrix();
  5274. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5275. return matrix;
  5276. }
  5277. /**
  5278. * Stores a right-handed orthographic projection into a given matrix
  5279. * @param left defines the viewport left coordinate
  5280. * @param right defines the viewport right coordinate
  5281. * @param bottom defines the viewport bottom coordinate
  5282. * @param top defines the viewport top coordinate
  5283. * @param znear defines the near clip plane
  5284. * @param zfar defines the far clip plane
  5285. * @param result defines the target matrix
  5286. */
  5287. public static OrthoOffCenterRHToRef(left: number, right: number, bottom: number, top: number, znear: number, zfar: number, result: Matrix): void {
  5288. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5289. result._m[10] *= -1; // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
  5290. }
  5291. /**
  5292. * Creates a left-handed perspective projection matrix
  5293. * @param width defines the viewport width
  5294. * @param height defines the viewport height
  5295. * @param znear defines the near clip plane
  5296. * @param zfar defines the far clip plane
  5297. * @returns a new matrix as a left-handed perspective projection matrix
  5298. */
  5299. public static PerspectiveLH(width: number, height: number, znear: number, zfar: number): Matrix {
  5300. var matrix = new Matrix();
  5301. let n = znear;
  5302. let f = zfar;
  5303. let a = 2.0 * n / width;
  5304. let b = 2.0 * n / height;
  5305. let c = (f + n) / (f - n);
  5306. let d = -2.0 * f * n / (f - n);
  5307. Matrix.FromValuesToRef(
  5308. a, 0.0, 0.0, 0.0,
  5309. 0.0, b, 0.0, 0.0,
  5310. 0.0, 0.0, c, 1.0,
  5311. 0.0, 0.0, d, 0.0,
  5312. matrix
  5313. );
  5314. matrix._updateIdentityStatus(false);
  5315. return matrix;
  5316. }
  5317. /**
  5318. * Creates a left-handed perspective projection matrix
  5319. * @param fov defines the horizontal field of view
  5320. * @param aspect defines the aspect ratio
  5321. * @param znear defines the near clip plane
  5322. * @param zfar defines the far clip plane
  5323. * @returns a new matrix as a left-handed perspective projection matrix
  5324. */
  5325. public static PerspectiveFovLH(fov: number, aspect: number, znear: number, zfar: number): Matrix {
  5326. var matrix = new Matrix();
  5327. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5328. return matrix;
  5329. }
  5330. /**
  5331. * Stores a left-handed perspective projection into a given matrix
  5332. * @param fov defines the horizontal field of view
  5333. * @param aspect defines the aspect ratio
  5334. * @param znear defines the near clip plane
  5335. * @param zfar defines the far clip plane
  5336. * @param result defines the target matrix
  5337. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  5338. */
  5339. public static PerspectiveFovLHToRef(fov: number, aspect: number, znear: number, zfar: number, result: Matrix, isVerticalFovFixed = true): void {
  5340. let n = znear;
  5341. let f = zfar;
  5342. let t = 1.0 / (Math.tan(fov * 0.5));
  5343. let a = isVerticalFovFixed ? (t / aspect) : t;
  5344. let b = isVerticalFovFixed ? t : (t * aspect);
  5345. let c = (f + n) / (f - n);
  5346. let d = -2.0 * f * n / (f - n);
  5347. Matrix.FromValuesToRef(
  5348. a, 0.0, 0.0, 0.0,
  5349. 0.0, b, 0.0, 0.0,
  5350. 0.0, 0.0, c, 1.0,
  5351. 0.0, 0.0, d, 0.0,
  5352. result
  5353. );
  5354. result._updateIdentityStatus(false);
  5355. }
  5356. /**
  5357. * Creates a right-handed perspective projection matrix
  5358. * @param fov defines the horizontal field of view
  5359. * @param aspect defines the aspect ratio
  5360. * @param znear defines the near clip plane
  5361. * @param zfar defines the far clip plane
  5362. * @returns a new matrix as a right-handed perspective projection matrix
  5363. */
  5364. public static PerspectiveFovRH(fov: number, aspect: number, znear: number, zfar: number): Matrix {
  5365. var matrix = new Matrix();
  5366. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5367. return matrix;
  5368. }
  5369. /**
  5370. * Stores a right-handed perspective projection into a given matrix
  5371. * @param fov defines the horizontal field of view
  5372. * @param aspect defines the aspect ratio
  5373. * @param znear defines the near clip plane
  5374. * @param zfar defines the far clip plane
  5375. * @param result defines the target matrix
  5376. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  5377. */
  5378. public static PerspectiveFovRHToRef(fov: number, aspect: number, znear: number, zfar: number, result: Matrix, isVerticalFovFixed = true): void {
  5379. //alternatively this could be expressed as:
  5380. // m = PerspectiveFovLHToRef
  5381. // m[10] *= -1.0;
  5382. // m[11] *= -1.0;
  5383. let n = znear;
  5384. let f = zfar;
  5385. let t = 1.0 / (Math.tan(fov * 0.5));
  5386. let a = isVerticalFovFixed ? (t / aspect) : t;
  5387. let b = isVerticalFovFixed ? t : (t * aspect);
  5388. let c = -(f + n) / (f - n);
  5389. let d = -2 * f * n / (f - n);
  5390. Matrix.FromValuesToRef(
  5391. a, 0.0, 0.0, 0.0,
  5392. 0.0, b, 0.0, 0.0,
  5393. 0.0, 0.0, c, -1.0,
  5394. 0.0, 0.0, d, 0.0,
  5395. result
  5396. );
  5397. result._updateIdentityStatus(false);
  5398. }
  5399. /**
  5400. * Stores a perspective projection for WebVR info a given matrix
  5401. * @param fov defines the field of view
  5402. * @param znear defines the near clip plane
  5403. * @param zfar defines the far clip plane
  5404. * @param result defines the target matrix
  5405. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  5406. */
  5407. public static PerspectiveFovWebVRToRef(fov: { upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number }, znear: number, zfar: number, result: Matrix, rightHanded = false): void {
  5408. var rightHandedFactor = rightHanded ? -1 : 1;
  5409. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5410. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5411. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5412. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5413. var xScale = 2.0 / (leftTan + rightTan);
  5414. var yScale = 2.0 / (upTan + downTan);
  5415. const m = result._m;
  5416. m[0] = xScale;
  5417. m[1] = m[2] = m[3] = m[4] = 0.0;
  5418. m[5] = yScale;
  5419. m[6] = m[7] = 0.0;
  5420. m[8] = ((leftTan - rightTan) * xScale * 0.5);
  5421. m[9] = -((upTan - downTan) * yScale * 0.5);
  5422. m[10] = -zfar / (znear - zfar);
  5423. m[11] = 1.0 * rightHandedFactor;
  5424. m[12] = m[13] = m[15] = 0.0;
  5425. m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5426. result._markAsUpdated();
  5427. }
  5428. /**
  5429. * Computes a complete transformation matrix
  5430. * @param viewport defines the viewport to use
  5431. * @param world defines the world matrix
  5432. * @param view defines the view matrix
  5433. * @param projection defines the projection matrix
  5434. * @param zmin defines the near clip plane
  5435. * @param zmax defines the far clip plane
  5436. * @returns the transformation matrix
  5437. */
  5438. public static GetFinalMatrix(viewport: Viewport, world: Matrix, view: Matrix, projection: Matrix, zmin: number, zmax: number): Matrix {
  5439. var cw = viewport.width;
  5440. var ch = viewport.height;
  5441. var cx = viewport.x;
  5442. var cy = viewport.y;
  5443. var viewportMatrix = Matrix.FromValues(
  5444. cw / 2.0, 0.0, 0.0, 0.0,
  5445. 0.0, -ch / 2.0, 0.0, 0.0,
  5446. 0.0, 0.0, zmax - zmin, 0.0,
  5447. cx + cw / 2.0, ch / 2.0 + cy, zmin, 1.0);
  5448. var matrix = MathTmp.Matrix[0];
  5449. world.multiplyToRef(view, matrix);
  5450. matrix.multiplyToRef(projection, matrix);
  5451. return matrix.multiply(viewportMatrix);
  5452. }
  5453. /**
  5454. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  5455. * @param matrix defines the matrix to use
  5456. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  5457. */
  5458. public static GetAsMatrix2x2(matrix: Matrix): Float32Array {
  5459. return new Float32Array([
  5460. matrix._m[0], matrix._m[1],
  5461. matrix._m[4], matrix._m[5]
  5462. ]);
  5463. }
  5464. /**
  5465. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  5466. * @param matrix defines the matrix to use
  5467. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  5468. */
  5469. public static GetAsMatrix3x3(matrix: Matrix): Float32Array {
  5470. return new Float32Array([
  5471. matrix._m[0], matrix._m[1], matrix._m[2],
  5472. matrix._m[4], matrix._m[5], matrix._m[6],
  5473. matrix._m[8], matrix._m[9], matrix._m[10]
  5474. ]);
  5475. }
  5476. /**
  5477. * Compute the transpose of a given matrix
  5478. * @param matrix defines the matrix to transpose
  5479. * @returns the new matrix
  5480. */
  5481. public static Transpose(matrix: Matrix): Matrix {
  5482. var result = new Matrix();
  5483. Matrix.TransposeToRef(matrix, result);
  5484. return result;
  5485. }
  5486. /**
  5487. * Compute the transpose of a matrix and store it in a target matrix
  5488. * @param matrix defines the matrix to transpose
  5489. * @param result defines the target matrix
  5490. */
  5491. public static TransposeToRef(matrix: Matrix, result: Matrix): void {
  5492. const rm = result._m;
  5493. const mm = matrix._m;
  5494. rm[0] = mm[0];
  5495. rm[1] = mm[4];
  5496. rm[2] = mm[8];
  5497. rm[3] = mm[12];
  5498. rm[4] = mm[1];
  5499. rm[5] = mm[5];
  5500. rm[6] = mm[9];
  5501. rm[7] = mm[13];
  5502. rm[8] = mm[2];
  5503. rm[9] = mm[6];
  5504. rm[10] = mm[10];
  5505. rm[11] = mm[14];
  5506. rm[12] = mm[3];
  5507. rm[13] = mm[7];
  5508. rm[14] = mm[11];
  5509. rm[15] = mm[15];
  5510. // identity-ness does not change when transposing
  5511. result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
  5512. }
  5513. /**
  5514. * Computes a reflection matrix from a plane
  5515. * @param plane defines the reflection plane
  5516. * @returns a new matrix
  5517. */
  5518. public static Reflection(plane: Plane): Matrix {
  5519. var matrix = new Matrix();
  5520. Matrix.ReflectionToRef(plane, matrix);
  5521. return matrix;
  5522. }
  5523. /**
  5524. * Computes a reflection matrix from a plane
  5525. * @param plane defines the reflection plane
  5526. * @param result defines the target matrix
  5527. */
  5528. public static ReflectionToRef(plane: Plane, result: Matrix): void {
  5529. plane.normalize();
  5530. var x = plane.normal.x;
  5531. var y = plane.normal.y;
  5532. var z = plane.normal.z;
  5533. var temp = -2 * x;
  5534. var temp2 = -2 * y;
  5535. var temp3 = -2 * z;
  5536. Matrix.FromValuesToRef(
  5537. temp * x + 1, temp2 * x, temp3 * x, 0.0,
  5538. temp * y, temp2 * y + 1, temp3 * y, 0.0,
  5539. temp * z, temp2 * z, temp3 * z + 1, 0.0,
  5540. temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0,
  5541. result
  5542. );
  5543. }
  5544. /**
  5545. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  5546. * @param xaxis defines the value of the 1st axis
  5547. * @param yaxis defines the value of the 2nd axis
  5548. * @param zaxis defines the value of the 3rd axis
  5549. * @param result defines the target matrix
  5550. */
  5551. public static FromXYZAxesToRef(xaxis: Vector3, yaxis: Vector3, zaxis: Vector3, result: Matrix) {
  5552. Matrix.FromValuesToRef(
  5553. xaxis.x, xaxis.y, xaxis.z, 0.0,
  5554. yaxis.x, yaxis.y, yaxis.z, 0.0,
  5555. zaxis.x, zaxis.y, zaxis.z, 0.0,
  5556. 0.0, 0.0, 0.0, 1.0,
  5557. result
  5558. );
  5559. }
  5560. /**
  5561. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  5562. * @param quat defines the quaternion to use
  5563. * @param result defines the target matrix
  5564. */
  5565. public static FromQuaternionToRef(quat: Quaternion, result: Matrix) {
  5566. var xx = quat.x * quat.x;
  5567. var yy = quat.y * quat.y;
  5568. var zz = quat.z * quat.z;
  5569. var xy = quat.x * quat.y;
  5570. var zw = quat.z * quat.w;
  5571. var zx = quat.z * quat.x;
  5572. var yw = quat.y * quat.w;
  5573. var yz = quat.y * quat.z;
  5574. var xw = quat.x * quat.w;
  5575. result._m[0] = 1.0 - (2.0 * (yy + zz));
  5576. result._m[1] = 2.0 * (xy + zw);
  5577. result._m[2] = 2.0 * (zx - yw);
  5578. result._m[3] = 0.0;
  5579. result._m[4] = 2.0 * (xy - zw);
  5580. result._m[5] = 1.0 - (2.0 * (zz + xx));
  5581. result._m[6] = 2.0 * (yz + xw);
  5582. result._m[7] = 0.0;
  5583. result._m[8] = 2.0 * (zx + yw);
  5584. result._m[9] = 2.0 * (yz - xw);
  5585. result._m[10] = 1.0 - (2.0 * (yy + xx));
  5586. result._m[11] = 0.0;
  5587. result._m[12] = 0.0;
  5588. result._m[13] = 0.0;
  5589. result._m[14] = 0.0;
  5590. result._m[15] = 1.0;
  5591. result._markAsUpdated();
  5592. }
  5593. }
  5594. /**
  5595. * Represens a plane by the equation ax + by + cz + d = 0
  5596. */
  5597. export class Plane {
  5598. /**
  5599. * Normal of the plane (a,b,c)
  5600. */
  5601. public normal: Vector3;
  5602. /**
  5603. * d component of the plane
  5604. */
  5605. public d: number;
  5606. /**
  5607. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5608. * @param a a component of the plane
  5609. * @param b b component of the plane
  5610. * @param c c component of the plane
  5611. * @param d d component of the plane
  5612. */
  5613. constructor(a: number, b: number, c: number, d: number) {
  5614. this.normal = new Vector3(a, b, c);
  5615. this.d = d;
  5616. }
  5617. /**
  5618. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5619. */
  5620. public asArray(): number[] {
  5621. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5622. }
  5623. // Methods
  5624. /**
  5625. * @returns a new plane copied from the current Plane.
  5626. */
  5627. public clone(): Plane {
  5628. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5629. }
  5630. /**
  5631. * @returns the string "Plane".
  5632. */
  5633. public getClassName(): string {
  5634. return "Plane";
  5635. }
  5636. /**
  5637. * @returns the Plane hash code.
  5638. */
  5639. public getHashCode(): number {
  5640. let hash = this.normal.getHashCode();
  5641. hash = (hash * 397) ^ (this.d || 0);
  5642. return hash;
  5643. }
  5644. /**
  5645. * Normalize the current Plane in place.
  5646. * @returns the updated Plane.
  5647. */
  5648. public normalize(): Plane {
  5649. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5650. var magnitude = 0.0;
  5651. if (norm !== 0) {
  5652. magnitude = 1.0 / norm;
  5653. }
  5654. this.normal.x *= magnitude;
  5655. this.normal.y *= magnitude;
  5656. this.normal.z *= magnitude;
  5657. this.d *= magnitude;
  5658. return this;
  5659. }
  5660. /**
  5661. * Applies a transformation the plane and returns the result
  5662. * @param transformation the transformation matrix to be applied to the plane
  5663. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  5664. */
  5665. public transform(transformation: Matrix): Plane {
  5666. const transposedMatrix = MathTmp.Matrix[0];
  5667. Matrix.TransposeToRef(transformation, transposedMatrix);
  5668. const m = transposedMatrix.m;
  5669. var x = this.normal.x;
  5670. var y = this.normal.y;
  5671. var z = this.normal.z;
  5672. var d = this.d;
  5673. var normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
  5674. var normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
  5675. var normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
  5676. var finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
  5677. return new Plane(normalX, normalY, normalZ, finalD);
  5678. }
  5679. /**
  5680. * Calcualtte the dot product between the point and the plane normal
  5681. * @param point point to calculate the dot product with
  5682. * @returns the dot product (float) of the point coordinates and the plane normal.
  5683. */
  5684. public dotCoordinate(point: Vector3): number {
  5685. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5686. }
  5687. /**
  5688. * Updates the current Plane from the plane defined by the three given points.
  5689. * @param point1 one of the points used to contruct the plane
  5690. * @param point2 one of the points used to contruct the plane
  5691. * @param point3 one of the points used to contruct the plane
  5692. * @returns the updated Plane.
  5693. */
  5694. public copyFromPoints(point1: Vector3, point2: Vector3, point3: Vector3): Plane {
  5695. var x1 = point2.x - point1.x;
  5696. var y1 = point2.y - point1.y;
  5697. var z1 = point2.z - point1.z;
  5698. var x2 = point3.x - point1.x;
  5699. var y2 = point3.y - point1.y;
  5700. var z2 = point3.z - point1.z;
  5701. var yz = (y1 * z2) - (z1 * y2);
  5702. var xz = (z1 * x2) - (x1 * z2);
  5703. var xy = (x1 * y2) - (y1 * x2);
  5704. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5705. var invPyth;
  5706. if (pyth !== 0) {
  5707. invPyth = 1.0 / pyth;
  5708. }
  5709. else {
  5710. invPyth = 0.0;
  5711. }
  5712. this.normal.x = yz * invPyth;
  5713. this.normal.y = xz * invPyth;
  5714. this.normal.z = xy * invPyth;
  5715. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5716. return this;
  5717. }
  5718. /**
  5719. * Checks if the plane is facing a given direction
  5720. * @param direction the direction to check if the plane is facing
  5721. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  5722. * @returns True is the vector "direction" is the same side than the plane normal.
  5723. */
  5724. public isFrontFacingTo(direction: Vector3, epsilon: number): boolean {
  5725. var dot = Vector3.Dot(this.normal, direction);
  5726. return (dot <= epsilon);
  5727. }
  5728. /**
  5729. * Calculates the distance to a point
  5730. * @param point point to calculate distance to
  5731. * @returns the signed distance (float) from the given point to the Plane.
  5732. */
  5733. public signedDistanceTo(point: Vector3): number {
  5734. return Vector3.Dot(point, this.normal) + this.d;
  5735. }
  5736. // Statics
  5737. /**
  5738. * Creates a plane from an array
  5739. * @param array the array to create a plane from
  5740. * @returns a new Plane from the given array.
  5741. */
  5742. static FromArray(array: ArrayLike<number>): Plane {
  5743. return new Plane(array[0], array[1], array[2], array[3]);
  5744. }
  5745. /**
  5746. * Creates a plane from three points
  5747. * @param point1 point used to create the plane
  5748. * @param point2 point used to create the plane
  5749. * @param point3 point used to create the plane
  5750. * @returns a new Plane defined by the three given points.
  5751. */
  5752. static FromPoints(point1: Vector3, point2: Vector3, point3: Vector3): Plane {
  5753. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5754. result.copyFromPoints(point1, point2, point3);
  5755. return result;
  5756. }
  5757. /**
  5758. * Creates a plane from an origin point and a normal
  5759. * @param origin origin of the plane to be constructed
  5760. * @param normal normal of the plane to be constructed
  5761. * @returns a new Plane the normal vector to this plane at the given origin point.
  5762. * Note : the vector "normal" is updated because normalized.
  5763. */
  5764. static FromPositionAndNormal(origin: Vector3, normal: Vector3): Plane {
  5765. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5766. normal.normalize();
  5767. result.normal = normal;
  5768. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5769. return result;
  5770. }
  5771. /**
  5772. * Calculates the distance from a plane and a point
  5773. * @param origin origin of the plane to be constructed
  5774. * @param normal normal of the plane to be constructed
  5775. * @param point point to calculate distance to
  5776. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  5777. */
  5778. static SignedDistanceToPlaneFromPositionAndNormal(origin: Vector3, normal: Vector3, point: Vector3): number {
  5779. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5780. return Vector3.Dot(point, normal) + d;
  5781. }
  5782. }
  5783. /**
  5784. * Class used to represent a viewport on screen
  5785. */
  5786. export class Viewport {
  5787. /**
  5788. * Creates a Viewport object located at (x, y) and sized (width, height)
  5789. * @param x defines viewport left coordinate
  5790. * @param y defines viewport top coordinate
  5791. * @param width defines the viewport width
  5792. * @param height defines the viewport height
  5793. */
  5794. constructor(
  5795. /** viewport left coordinate */
  5796. public x: number,
  5797. /** viewport top coordinate */
  5798. public y: number,
  5799. /**viewport width */
  5800. public width: number,
  5801. /** viewport height */
  5802. public height: number) {
  5803. }
  5804. /**
  5805. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  5806. * @param renderWidthOrEngine defines either an engine or the rendering width
  5807. * @param renderHeight defines the rendering height
  5808. * @returns a new Viewport
  5809. */
  5810. public toGlobal(renderWidthOrEngine: number | Engine, renderHeight: number): Viewport {
  5811. if ((<Engine>renderWidthOrEngine).getRenderWidth) {
  5812. var engine = (<Engine>renderWidthOrEngine);
  5813. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5814. }
  5815. let renderWidth = <number>renderWidthOrEngine;
  5816. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5817. }
  5818. /**
  5819. * Returns a new Viewport copied from the current one
  5820. * @returns a new Viewport
  5821. */
  5822. public clone(): Viewport {
  5823. return new Viewport(this.x, this.y, this.width, this.height);
  5824. }
  5825. }
  5826. /**
  5827. * Reprasents a camera frustum
  5828. */
  5829. export class Frustum {
  5830. /**
  5831. * Gets the planes representing the frustum
  5832. * @param transform matrix to be applied to the returned planes
  5833. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  5834. */
  5835. public static GetPlanes(transform: Matrix): Plane[] {
  5836. var frustumPlanes = [];
  5837. for (var index = 0; index < 6; index++) {
  5838. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5839. }
  5840. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5841. return frustumPlanes;
  5842. }
  5843. /**
  5844. * Gets the near frustum plane transformed by the transform matrix
  5845. * @param transform transformation matrix to be applied to the resulting frustum plane
  5846. * @param frustumPlane the resuling frustum plane
  5847. */
  5848. public static GetNearPlaneToRef(transform: Matrix, frustumPlane: Plane): void {
  5849. const m = transform.m;
  5850. frustumPlane.normal.x = m[3] + m[2];
  5851. frustumPlane.normal.y = m[7] + m[6];
  5852. frustumPlane.normal.z = m[11] + m[10];
  5853. frustumPlane.d = m[15] + m[14];
  5854. frustumPlane.normalize();
  5855. }
  5856. /**
  5857. * Gets the far frustum plane transformed by the transform matrix
  5858. * @param transform transformation matrix to be applied to the resulting frustum plane
  5859. * @param frustumPlane the resuling frustum plane
  5860. */
  5861. public static GetFarPlaneToRef(transform: Matrix, frustumPlane: Plane): void {
  5862. const m = transform.m;
  5863. frustumPlane.normal.x = m[3] - m[2];
  5864. frustumPlane.normal.y = m[7] - m[6];
  5865. frustumPlane.normal.z = m[11] - m[10];
  5866. frustumPlane.d = m[15] - m[14];
  5867. frustumPlane.normalize();
  5868. }
  5869. /**
  5870. * Gets the left frustum plane transformed by the transform matrix
  5871. * @param transform transformation matrix to be applied to the resulting frustum plane
  5872. * @param frustumPlane the resuling frustum plane
  5873. */
  5874. public static GetLeftPlaneToRef(transform: Matrix, frustumPlane: Plane): void {
  5875. const m = transform.m;
  5876. frustumPlane.normal.x = m[3] + m[0];
  5877. frustumPlane.normal.y = m[7] + m[4];
  5878. frustumPlane.normal.z = m[11] + m[8];
  5879. frustumPlane.d = m[15] + m[12];
  5880. frustumPlane.normalize();
  5881. }
  5882. /**
  5883. * Gets the right frustum plane transformed by the transform matrix
  5884. * @param transform transformation matrix to be applied to the resulting frustum plane
  5885. * @param frustumPlane the resuling frustum plane
  5886. */
  5887. public static GetRightPlaneToRef(transform: Matrix, frustumPlane: Plane): void {
  5888. const m = transform.m;
  5889. frustumPlane.normal.x = m[3] - m[0];
  5890. frustumPlane.normal.y = m[7] - m[4];
  5891. frustumPlane.normal.z = m[11] - m[8];
  5892. frustumPlane.d = m[15] - m[12];
  5893. frustumPlane.normalize();
  5894. }
  5895. /**
  5896. * Gets the top frustum plane transformed by the transform matrix
  5897. * @param transform transformation matrix to be applied to the resulting frustum plane
  5898. * @param frustumPlane the resuling frustum plane
  5899. */
  5900. public static GetTopPlaneToRef(transform: Matrix, frustumPlane: Plane): void {
  5901. const m = transform.m;
  5902. frustumPlane.normal.x = m[3] - m[1];
  5903. frustumPlane.normal.y = m[7] - m[5];
  5904. frustumPlane.normal.z = m[11] - m[9];
  5905. frustumPlane.d = m[15] - m[13];
  5906. frustumPlane.normalize();
  5907. }
  5908. /**
  5909. * Gets the bottom frustum plane transformed by the transform matrix
  5910. * @param transform transformation matrix to be applied to the resulting frustum plane
  5911. * @param frustumPlane the resuling frustum plane
  5912. */
  5913. public static GetBottomPlaneToRef(transform: Matrix, frustumPlane: Plane): void {
  5914. const m = transform.m;
  5915. frustumPlane.normal.x = m[3] + m[1];
  5916. frustumPlane.normal.y = m[7] + m[5];
  5917. frustumPlane.normal.z = m[11] + m[9];
  5918. frustumPlane.d = m[15] + m[13];
  5919. frustumPlane.normalize();
  5920. }
  5921. /**
  5922. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  5923. * @param transform transformation matrix to be applied to the resulting frustum planes
  5924. * @param frustumPlanes the resuling frustum planes
  5925. */
  5926. public static GetPlanesToRef(transform: Matrix, frustumPlanes: Plane[]): void {
  5927. // Near
  5928. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5929. // Far
  5930. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5931. // Left
  5932. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5933. // Right
  5934. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5935. // Top
  5936. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5937. // Bottom
  5938. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5939. }
  5940. }
  5941. /** Defines supported spaces */
  5942. export enum Space {
  5943. /** Local (object) space */
  5944. LOCAL = 0,
  5945. /** World space */
  5946. WORLD = 1,
  5947. /** Bone space */
  5948. BONE = 2
  5949. }
  5950. /** Defines the 3 main axes */
  5951. export class Axis {
  5952. /** X axis */
  5953. public static X: Vector3 = new Vector3(1.0, 0.0, 0.0);
  5954. /** Y axis */
  5955. public static Y: Vector3 = new Vector3(0.0, 1.0, 0.0);
  5956. /** Z axis */
  5957. public static Z: Vector3 = new Vector3(0.0, 0.0, 1.0);
  5958. }
  5959. /** Class used to represent a Bezier curve */
  5960. export class BezierCurve {
  5961. /**
  5962. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  5963. * @param t defines the time
  5964. * @param x1 defines the left coordinate on X axis
  5965. * @param y1 defines the left coordinate on Y axis
  5966. * @param x2 defines the right coordinate on X axis
  5967. * @param y2 defines the right coordinate on Y axis
  5968. * @returns the interpolated value
  5969. */
  5970. public static Interpolate(t: number, x1: number, y1: number, x2: number, y2: number): number {
  5971. // Extract X (which is equal to time here)
  5972. var f0 = 1 - 3 * x2 + 3 * x1;
  5973. var f1 = 3 * x2 - 6 * x1;
  5974. var f2 = 3 * x1;
  5975. var refinedT = t;
  5976. for (var i = 0; i < 5; i++) {
  5977. var refinedT2 = refinedT * refinedT;
  5978. var refinedT3 = refinedT2 * refinedT;
  5979. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5980. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5981. refinedT -= (x - t) * slope;
  5982. refinedT = Math.min(1, Math.max(0, refinedT));
  5983. }
  5984. // Resolve cubic bezier for the given x
  5985. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5986. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5987. Math.pow(refinedT, 3);
  5988. }
  5989. }
  5990. /**
  5991. * Defines potential orientation for back face culling
  5992. */
  5993. export enum Orientation {
  5994. /**
  5995. * Clockwise
  5996. */
  5997. CW = 0,
  5998. /** Counter clockwise */
  5999. CCW = 1
  6000. }
  6001. /**
  6002. * Defines angle representation
  6003. */
  6004. export class Angle {
  6005. private _radians: number;
  6006. /**
  6007. * Creates an Angle object of "radians" radians (float).
  6008. */
  6009. constructor(radians: number) {
  6010. this._radians = radians;
  6011. if (this._radians < 0.0) { this._radians += (2.0 * Math.PI); }
  6012. }
  6013. /**
  6014. * Get value in degrees
  6015. * @returns the Angle value in degrees (float)
  6016. */
  6017. public degrees() {
  6018. return this._radians * 180.0 / Math.PI;
  6019. }
  6020. /**
  6021. * Get value in radians
  6022. * @returns the Angle value in radians (float)
  6023. */
  6024. public radians() {
  6025. return this._radians;
  6026. }
  6027. /**
  6028. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6029. * @param a defines first vector
  6030. * @param b defines second vector
  6031. * @returns a new Angle
  6032. */
  6033. public static BetweenTwoPoints(a: Vector2, b: Vector2): Angle {
  6034. var delta = b.subtract(a);
  6035. var theta = Math.atan2(delta.y, delta.x);
  6036. return new Angle(theta);
  6037. }
  6038. /**
  6039. * Gets a new Angle object from the given float in radians
  6040. * @param radians defines the angle value in radians
  6041. * @returns a new Angle
  6042. */
  6043. public static FromRadians(radians: number): Angle {
  6044. return new Angle(radians);
  6045. }
  6046. /**
  6047. * Gets a new Angle object from the given float in degrees
  6048. * @param degrees defines the angle value in degrees
  6049. * @returns a new Angle
  6050. */
  6051. public static FromDegrees(degrees: number): Angle {
  6052. return new Angle(degrees * Math.PI / 180.0);
  6053. }
  6054. }
  6055. /**
  6056. * This represents an arc in a 2d space.
  6057. */
  6058. export class Arc2 {
  6059. /**
  6060. * Defines the center point of the arc.
  6061. */
  6062. public centerPoint: Vector2;
  6063. /**
  6064. * Defines the radius of the arc.
  6065. */
  6066. public radius: number;
  6067. /**
  6068. * Defines the angle of the arc (from mid point to end point).
  6069. */
  6070. public angle: Angle;
  6071. /**
  6072. * Defines the start angle of the arc (from start point to middle point).
  6073. */
  6074. public startAngle: Angle;
  6075. /**
  6076. * Defines the orientation of the arc (clock wise/counter clock wise).
  6077. */
  6078. public orientation: Orientation;
  6079. /**
  6080. * Creates an Arc object from the three given points : start, middle and end.
  6081. * @param startPoint Defines the start point of the arc
  6082. * @param midPoint Defines the midlle point of the arc
  6083. * @param endPoint Defines the end point of the arc
  6084. */
  6085. constructor(
  6086. /** Defines the start point of the arc */
  6087. public startPoint: Vector2,
  6088. /** Defines the mid point of the arc */
  6089. public midPoint: Vector2,
  6090. /** Defines the end point of the arc */
  6091. public endPoint: Vector2) {
  6092. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6093. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6094. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6095. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6096. this.centerPoint = new Vector2(
  6097. (startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det,
  6098. ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det
  6099. );
  6100. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6101. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6102. var a1 = this.startAngle.degrees();
  6103. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6104. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6105. // angles correction
  6106. if (a2 - a1 > +180.0) { a2 -= 360.0; }
  6107. if (a2 - a1 < -180.0) { a2 += 360.0; }
  6108. if (a3 - a2 > +180.0) { a3 -= 360.0; }
  6109. if (a3 - a2 < -180.0) { a3 += 360.0; }
  6110. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6111. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6112. }
  6113. }
  6114. /**
  6115. * Represents a 2D path made up of multiple 2D points
  6116. */
  6117. export class Path2 {
  6118. private _points = new Array<Vector2>();
  6119. private _length = 0.0;
  6120. /**
  6121. * If the path start and end point are the same
  6122. */
  6123. public closed = false;
  6124. /**
  6125. * Creates a Path2 object from the starting 2D coordinates x and y.
  6126. * @param x the starting points x value
  6127. * @param y the starting points y value
  6128. */
  6129. constructor(x: number, y: number) {
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6134. * @param x the added points x value
  6135. * @param y the added points y value
  6136. * @returns the updated Path2.
  6137. */
  6138. public addLineTo(x: number, y: number): Path2 {
  6139. if (this.closed) {
  6140. return this;
  6141. }
  6142. var newPoint = new Vector2(x, y);
  6143. var previousPoint = this._points[this._points.length - 1];
  6144. this._points.push(newPoint);
  6145. this._length += newPoint.subtract(previousPoint).length();
  6146. return this;
  6147. }
  6148. /**
  6149. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6150. * @param midX middle point x value
  6151. * @param midY middle point y value
  6152. * @param endX end point x value
  6153. * @param endY end point y value
  6154. * @param numberOfSegments (default: 36)
  6155. * @returns the updated Path2.
  6156. */
  6157. public addArcTo(midX: number, midY: number, endX: number, endY: number, numberOfSegments = 36): Path2 {
  6158. if (this.closed) {
  6159. return this;
  6160. }
  6161. var startPoint = this._points[this._points.length - 1];
  6162. var midPoint = new Vector2(midX, midY);
  6163. var endPoint = new Vector2(endX, endY);
  6164. var arc = new Arc2(startPoint, midPoint, endPoint);
  6165. var increment = arc.angle.radians() / numberOfSegments;
  6166. if (arc.orientation === Orientation.CW) { increment *= -1; }
  6167. var currentAngle = arc.startAngle.radians() + increment;
  6168. for (var i = 0; i < numberOfSegments; i++) {
  6169. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6170. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6171. this.addLineTo(x, y);
  6172. currentAngle += increment;
  6173. }
  6174. return this;
  6175. }
  6176. /**
  6177. * Closes the Path2.
  6178. * @returns the Path2.
  6179. */
  6180. public close(): Path2 {
  6181. this.closed = true;
  6182. return this;
  6183. }
  6184. /**
  6185. * Gets the sum of the distance between each sequential point in the path
  6186. * @returns the Path2 total length (float).
  6187. */
  6188. public length(): number {
  6189. var result = this._length;
  6190. if (!this.closed) {
  6191. var lastPoint = this._points[this._points.length - 1];
  6192. var firstPoint = this._points[0];
  6193. result += (firstPoint.subtract(lastPoint).length());
  6194. }
  6195. return result;
  6196. }
  6197. /**
  6198. * Gets the points which construct the path
  6199. * @returns the Path2 internal array of points.
  6200. */
  6201. public getPoints(): Vector2[] {
  6202. return this._points;
  6203. }
  6204. /**
  6205. * Retreives the point at the distance aways from the starting point
  6206. * @param normalizedLengthPosition the length along the path to retreive the point from
  6207. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6208. */
  6209. public getPointAtLengthPosition(normalizedLengthPosition: number): Vector2 {
  6210. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6211. return Vector2.Zero();
  6212. }
  6213. var lengthPosition = normalizedLengthPosition * this.length();
  6214. var previousOffset = 0;
  6215. for (var i = 0; i < this._points.length; i++) {
  6216. var j = (i + 1) % this._points.length;
  6217. var a = this._points[i];
  6218. var b = this._points[j];
  6219. var bToA = b.subtract(a);
  6220. var nextOffset = (bToA.length() + previousOffset);
  6221. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6222. var dir = bToA.normalize();
  6223. var localOffset = lengthPosition - previousOffset;
  6224. return new Vector2(
  6225. a.x + (dir.x * localOffset),
  6226. a.y + (dir.y * localOffset)
  6227. );
  6228. }
  6229. previousOffset = nextOffset;
  6230. }
  6231. return Vector2.Zero();
  6232. }
  6233. /**
  6234. * Creates a new path starting from an x and y position
  6235. * @param x starting x value
  6236. * @param y starting y value
  6237. * @returns a new Path2 starting at the coordinates (x, y).
  6238. */
  6239. public static StartingAt(x: number, y: number): Path2 {
  6240. return new Path2(x, y);
  6241. }
  6242. }
  6243. /**
  6244. * Represents a 3D path made up of multiple 3D points
  6245. */
  6246. export class Path3D {
  6247. private _curve = new Array<Vector3>();
  6248. private _distances = new Array<number>();
  6249. private _tangents = new Array<Vector3>();
  6250. private _normals = new Array<Vector3>();
  6251. private _binormals = new Array<Vector3>();
  6252. private _raw: boolean;
  6253. /**
  6254. * new Path3D(path, normal, raw)
  6255. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6256. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6257. * @param path an array of Vector3, the curve axis of the Path3D
  6258. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6259. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6260. */
  6261. constructor(
  6262. /**
  6263. * an array of Vector3, the curve axis of the Path3D
  6264. */
  6265. public path: Vector3[],
  6266. firstNormal: Nullable<Vector3> = null,
  6267. raw?: boolean
  6268. ) {
  6269. for (var p = 0; p < path.length; p++) {
  6270. this._curve[p] = path[p].clone(); // hard copy
  6271. }
  6272. this._raw = raw || false;
  6273. this._compute(firstNormal);
  6274. }
  6275. /**
  6276. * Returns the Path3D array of successive Vector3 designing its curve.
  6277. * @returns the Path3D array of successive Vector3 designing its curve.
  6278. */
  6279. public getCurve(): Vector3[] {
  6280. return this._curve;
  6281. }
  6282. /**
  6283. * Returns an array populated with tangent vectors on each Path3D curve point.
  6284. * @returns an array populated with tangent vectors on each Path3D curve point.
  6285. */
  6286. public getTangents(): Vector3[] {
  6287. return this._tangents;
  6288. }
  6289. /**
  6290. * Returns an array populated with normal vectors on each Path3D curve point.
  6291. * @returns an array populated with normal vectors on each Path3D curve point.
  6292. */
  6293. public getNormals(): Vector3[] {
  6294. return this._normals;
  6295. }
  6296. /**
  6297. * Returns an array populated with binormal vectors on each Path3D curve point.
  6298. * @returns an array populated with binormal vectors on each Path3D curve point.
  6299. */
  6300. public getBinormals(): Vector3[] {
  6301. return this._binormals;
  6302. }
  6303. /**
  6304. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6305. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  6306. */
  6307. public getDistances(): number[] {
  6308. return this._distances;
  6309. }
  6310. /**
  6311. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6312. * @param path path which all values are copied into the curves points
  6313. * @param firstNormal which should be projected onto the curve
  6314. * @returns the same object updated.
  6315. */
  6316. public update(path: Vector3[], firstNormal: Nullable<Vector3> = null): Path3D {
  6317. for (var p = 0; p < path.length; p++) {
  6318. this._curve[p].x = path[p].x;
  6319. this._curve[p].y = path[p].y;
  6320. this._curve[p].z = path[p].z;
  6321. }
  6322. this._compute(firstNormal);
  6323. return this;
  6324. }
  6325. // private function compute() : computes tangents, normals and binormals
  6326. private _compute(firstNormal: Nullable<Vector3>): void {
  6327. var l = this._curve.length;
  6328. // first and last tangents
  6329. this._tangents[0] = this._getFirstNonNullVector(0);
  6330. if (!this._raw) {
  6331. this._tangents[0].normalize();
  6332. }
  6333. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6334. if (!this._raw) {
  6335. this._tangents[l - 1].normalize();
  6336. }
  6337. // normals and binormals at first point : arbitrary vector with _normalVector()
  6338. var tg0 = this._tangents[0];
  6339. var pp0 = this._normalVector(tg0, firstNormal);
  6340. this._normals[0] = pp0;
  6341. if (!this._raw) {
  6342. this._normals[0].normalize();
  6343. }
  6344. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6345. if (!this._raw) {
  6346. this._binormals[0].normalize();
  6347. }
  6348. this._distances[0] = 0.0;
  6349. // normals and binormals : next points
  6350. var prev: Vector3; // previous vector (segment)
  6351. var cur: Vector3; // current vector (segment)
  6352. var curTang: Vector3; // current tangent
  6353. // previous normal
  6354. var prevBinor: Vector3; // previous binormal
  6355. for (var i = 1; i < l; i++) {
  6356. // tangents
  6357. prev = this._getLastNonNullVector(i);
  6358. if (i < l - 1) {
  6359. cur = this._getFirstNonNullVector(i);
  6360. this._tangents[i] = prev.add(cur);
  6361. this._tangents[i].normalize();
  6362. }
  6363. this._distances[i] = this._distances[i - 1] + prev.length();
  6364. // normals and binormals
  6365. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6366. curTang = this._tangents[i];
  6367. prevBinor = this._binormals[i - 1];
  6368. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6369. if (!this._raw) {
  6370. this._normals[i].normalize();
  6371. }
  6372. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6373. if (!this._raw) {
  6374. this._binormals[i].normalize();
  6375. }
  6376. }
  6377. }
  6378. // private function getFirstNonNullVector(index)
  6379. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6380. private _getFirstNonNullVector(index: number): Vector3 {
  6381. var i = 1;
  6382. var nNVector: Vector3 = this._curve[index + i].subtract(this._curve[index]);
  6383. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6384. i++;
  6385. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6386. }
  6387. return nNVector;
  6388. }
  6389. // private function getLastNonNullVector(index)
  6390. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6391. private _getLastNonNullVector(index: number): Vector3 {
  6392. var i = 1;
  6393. var nLVector: Vector3 = this._curve[index].subtract(this._curve[index - i]);
  6394. while (nLVector.length() === 0 && index > i + 1) {
  6395. i++;
  6396. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6397. }
  6398. return nLVector;
  6399. }
  6400. // private function normalVector(v0, vt, va) :
  6401. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6402. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6403. private _normalVector(vt: Vector3, va: Nullable<Vector3>): Vector3 {
  6404. var normal0: Vector3;
  6405. var tgl = vt.length();
  6406. if (tgl === 0.0) {
  6407. tgl = 1.0;
  6408. }
  6409. if (va === undefined || va === null) {
  6410. var point: Vector3;
  6411. if (!Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, Epsilon)) { // search for a point in the plane
  6412. point = new Vector3(0.0, -1.0, 0.0);
  6413. }
  6414. else if (!Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, Epsilon)) {
  6415. point = new Vector3(1.0, 0.0, 0.0);
  6416. }
  6417. else if (!Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, Epsilon)) {
  6418. point = new Vector3(0.0, 0.0, 1.0);
  6419. }
  6420. else {
  6421. point = Vector3.Zero();
  6422. }
  6423. normal0 = Vector3.Cross(vt, point);
  6424. }
  6425. else {
  6426. normal0 = Vector3.Cross(vt, va);
  6427. Vector3.CrossToRef(normal0, vt, normal0);
  6428. }
  6429. normal0.normalize();
  6430. return normal0;
  6431. }
  6432. }
  6433. /**
  6434. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6435. * A Curve3 is designed from a series of successive Vector3.
  6436. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  6437. */
  6438. export class Curve3 {
  6439. private _points: Vector3[];
  6440. private _length: number = 0.0;
  6441. /**
  6442. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6444. * @param v1 (Vector3) the control point
  6445. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6446. * @param nbPoints (integer) the wanted number of points in the curve
  6447. * @returns the created Curve3
  6448. */
  6449. public static CreateQuadraticBezier(v0: Vector3, v1: Vector3, v2: Vector3, nbPoints: number): Curve3 {
  6450. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6451. var bez = new Array<Vector3>();
  6452. var equation = (t: number, val0: number, val1: number, val2: number) => {
  6453. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  6458. }
  6459. return new Curve3(bez);
  6460. }
  6461. /**
  6462. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6463. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6464. * @param v1 (Vector3) the first control point
  6465. * @param v2 (Vector3) the second control point
  6466. * @param v3 (Vector3) the end point of the Cubic Bezier
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. * @returns the created Curve3
  6469. */
  6470. public static CreateCubicBezier(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3, nbPoints: number): Curve3 {
  6471. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6472. var bez = new Array<Vector3>();
  6473. var equation = (t: number, val0: number, val1: number, val2: number, val3: number) => {
  6474. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  6475. return res;
  6476. };
  6477. for (var i = 0; i <= nbPoints; i++) {
  6478. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  6479. }
  6480. return new Curve3(bez);
  6481. }
  6482. /**
  6483. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6484. * @param p1 (Vector3) the origin point of the Hermite Spline
  6485. * @param t1 (Vector3) the tangent vector at the origin point
  6486. * @param p2 (Vector3) the end point of the Hermite Spline
  6487. * @param t2 (Vector3) the tangent vector at the end point
  6488. * @param nbPoints (integer) the wanted number of points in the curve
  6489. * @returns the created Curve3
  6490. */
  6491. public static CreateHermiteSpline(p1: Vector3, t1: Vector3, p2: Vector3, t2: Vector3, nbPoints: number): Curve3 {
  6492. var hermite = new Array<Vector3>();
  6493. var step = 1.0 / nbPoints;
  6494. for (var i = 0; i <= nbPoints; i++) {
  6495. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6496. }
  6497. return new Curve3(hermite);
  6498. }
  6499. /**
  6500. * Returns a Curve3 object along a CatmullRom Spline curve :
  6501. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  6502. * @param nbPoints (integer) the wanted number of points between each curve control points
  6503. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  6504. * @returns the created Curve3
  6505. */
  6506. public static CreateCatmullRomSpline(points: Vector3[], nbPoints: number, closed?: boolean): Curve3 {
  6507. var catmullRom = new Array<Vector3>();
  6508. var step = 1.0 / nbPoints;
  6509. var amount = 0.0;
  6510. if (closed) {
  6511. var pointsCount = points.length;
  6512. for (var i = 0; i < pointsCount; i++) {
  6513. amount = 0;
  6514. for (var c = 0; c < nbPoints; c++) {
  6515. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  6516. amount += step;
  6517. }
  6518. }
  6519. catmullRom.push(catmullRom[0]);
  6520. }
  6521. else {
  6522. var totalPoints = new Array<Vector3>();
  6523. totalPoints.push(points[0].clone());
  6524. Array.prototype.push.apply(totalPoints, points);
  6525. totalPoints.push(points[points.length - 1].clone());
  6526. for (var i = 0; i < totalPoints.length - 3; i++) {
  6527. amount = 0;
  6528. for (var c = 0; c < nbPoints; c++) {
  6529. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6530. amount += step;
  6531. }
  6532. }
  6533. i--;
  6534. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6535. }
  6536. return new Curve3(catmullRom);
  6537. }
  6538. /**
  6539. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6540. * A Curve3 is designed from a series of successive Vector3.
  6541. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6542. * @param points points which make up the curve
  6543. */
  6544. constructor(points: Vector3[]) {
  6545. this._points = points;
  6546. this._length = this._computeLength(points);
  6547. }
  6548. /**
  6549. * @returns the Curve3 stored array of successive Vector3
  6550. */
  6551. public getPoints() {
  6552. return this._points;
  6553. }
  6554. /**
  6555. * @returns the computed length (float) of the curve.
  6556. */
  6557. public length() {
  6558. return this._length;
  6559. }
  6560. /**
  6561. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6562. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6563. * curveA and curveB keep unchanged.
  6564. * @param curve the curve to continue from this curve
  6565. * @returns the newly constructed curve
  6566. */
  6567. public continue(curve: Curve3): Curve3 {
  6568. var lastPoint = this._points[this._points.length - 1];
  6569. var continuedPoints = this._points.slice();
  6570. var curvePoints = curve.getPoints();
  6571. for (var i = 1; i < curvePoints.length; i++) {
  6572. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6573. }
  6574. var continuedCurve = new Curve3(continuedPoints);
  6575. return continuedCurve;
  6576. }
  6577. private _computeLength(path: Vector3[]): number {
  6578. var l = 0;
  6579. for (var i = 1; i < path.length; i++) {
  6580. l += (path[i].subtract(path[i - 1])).length();
  6581. }
  6582. return l;
  6583. }
  6584. }
  6585. // Vertex formats
  6586. /**
  6587. * Contains position and normal vectors for a vertex
  6588. */
  6589. export class PositionNormalVertex {
  6590. /**
  6591. * Creates a PositionNormalVertex
  6592. * @param position the position of the vertex (defaut: 0,0,0)
  6593. * @param normal the normal of the vertex (defaut: 0,1,0)
  6594. */
  6595. constructor(
  6596. /** the position of the vertex (defaut: 0,0,0) */
  6597. public position: Vector3 = Vector3.Zero(),
  6598. /** the normal of the vertex (defaut: 0,1,0) */
  6599. public normal: Vector3 = Vector3.Up()
  6600. ) {
  6601. }
  6602. /**
  6603. * Clones the PositionNormalVertex
  6604. * @returns the cloned PositionNormalVertex
  6605. */
  6606. public clone(): PositionNormalVertex {
  6607. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6608. }
  6609. }
  6610. /**
  6611. * Contains position, normal and uv vectors for a vertex
  6612. */
  6613. export class PositionNormalTextureVertex {
  6614. /**
  6615. * Creates a PositionNormalTextureVertex
  6616. * @param position the position of the vertex (defaut: 0,0,0)
  6617. * @param normal the normal of the vertex (defaut: 0,1,0)
  6618. * @param uv the uv of the vertex (default: 0,0)
  6619. */
  6620. constructor(
  6621. /** the position of the vertex (defaut: 0,0,0) */
  6622. public position: Vector3 = Vector3.Zero(),
  6623. /** the normal of the vertex (defaut: 0,1,0) */
  6624. public normal: Vector3 = Vector3.Up(),
  6625. /** the uv of the vertex (default: 0,0) */
  6626. public uv: Vector2 = Vector2.Zero()
  6627. ) {
  6628. }
  6629. /**
  6630. * Clones the PositionNormalTextureVertex
  6631. * @returns the cloned PositionNormalTextureVertex
  6632. */
  6633. public clone(): PositionNormalTextureVertex {
  6634. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6635. }
  6636. }
  6637. // Temporary pre-allocated objects for engine internal use
  6638. // usage in any internal function :
  6639. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6640. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6641. /**
  6642. * @hidden
  6643. */
  6644. export class Tmp {
  6645. public static Color3: Color3[] = Tools.BuildArray(3, Color3.Black);
  6646. public static Color4: Color4[] = Tools.BuildArray(3, () => new Color4(0, 0, 0, 0));
  6647. public static Vector2: Vector2[] = Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  6648. public static Vector3: Vector3[] = Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  6649. public static Vector4: Vector4[] = Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  6650. public static Quaternion: Quaternion[] = Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  6651. public static Matrix: Matrix[] = Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  6652. }
  6653. /**
  6654. * @hidden
  6655. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  6656. */
  6657. class MathTmp {
  6658. public static Vector3: Vector3[] = Tools.BuildArray(6, Vector3.Zero);
  6659. public static Matrix: Matrix[] = Tools.BuildArray(2, Matrix.Identity);
  6660. public static Quaternion: Quaternion[] = Tools.BuildArray(3, Quaternion.Zero);
  6661. }