babylon.max.js 3.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Color3 = (function () {
  67. /**
  68. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  69. */
  70. function Color3(r, g, b) {
  71. if (r === void 0) { r = 0; }
  72. if (g === void 0) { g = 0; }
  73. if (b === void 0) { b = 0; }
  74. this.r = r;
  75. this.g = g;
  76. this.b = b;
  77. }
  78. /**
  79. * Returns a string with the Color3 current values.
  80. */
  81. Color3.prototype.toString = function () {
  82. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  83. };
  84. /**
  85. * Returns the string "Color3".
  86. */
  87. Color3.prototype.getClassName = function () {
  88. return "Color3";
  89. };
  90. /**
  91. * Returns the Color3 hash code.
  92. */
  93. Color3.prototype.getHashCode = function () {
  94. var hash = this.r || 0;
  95. hash = (hash * 397) ^ (this.g || 0);
  96. hash = (hash * 397) ^ (this.b || 0);
  97. return hash;
  98. };
  99. // Operators
  100. /**
  101. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  102. * Returns the Color3.
  103. */
  104. Color3.prototype.toArray = function (array, index) {
  105. if (index === undefined) {
  106. index = 0;
  107. }
  108. array[index] = this.r;
  109. array[index + 1] = this.g;
  110. array[index + 2] = this.b;
  111. return this;
  112. };
  113. /**
  114. * Returns a new Color4 object from the current Color3 and the passed alpha.
  115. */
  116. Color3.prototype.toColor4 = function (alpha) {
  117. if (alpha === void 0) { alpha = 1; }
  118. return new Color4(this.r, this.g, this.b, alpha);
  119. };
  120. /**
  121. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  122. */
  123. Color3.prototype.asArray = function () {
  124. var result = [];
  125. this.toArray(result, 0);
  126. return result;
  127. };
  128. /**
  129. * Returns the luminance value (float).
  130. */
  131. Color3.prototype.toLuminance = function () {
  132. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  133. };
  134. /**
  135. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  136. * Returns this new object.
  137. */
  138. Color3.prototype.multiply = function (otherColor) {
  139. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  140. };
  141. /**
  142. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  143. * Returns the current Color3.
  144. */
  145. Color3.prototype.multiplyToRef = function (otherColor, result) {
  146. result.r = this.r * otherColor.r;
  147. result.g = this.g * otherColor.g;
  148. result.b = this.b * otherColor.b;
  149. return this;
  150. };
  151. /**
  152. * Boolean : True if the rgb values are equal to the passed ones.
  153. */
  154. Color3.prototype.equals = function (otherColor) {
  155. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  156. };
  157. /**
  158. * Boolean : True if the rgb values are equal to the passed ones.
  159. */
  160. Color3.prototype.equalsFloats = function (r, g, b) {
  161. return this.r === r && this.g === g && this.b === b;
  162. };
  163. /**
  164. * Multiplies in place each rgb value by scale.
  165. * Returns the updated Color3.
  166. */
  167. Color3.prototype.scale = function (scale) {
  168. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  169. };
  170. /**
  171. * Multiplies the rgb values by scale and stores the result into "result".
  172. * Returns the unmodified current Color3.
  173. */
  174. Color3.prototype.scaleToRef = function (scale, result) {
  175. result.r = this.r * scale;
  176. result.g = this.g * scale;
  177. result.b = this.b * scale;
  178. return this;
  179. };
  180. /**
  181. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  182. */
  183. Color3.prototype.add = function (otherColor) {
  184. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  185. };
  186. /**
  187. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  188. * Returns the unmodified current Color3.
  189. */
  190. Color3.prototype.addToRef = function (otherColor, result) {
  191. result.r = this.r + otherColor.r;
  192. result.g = this.g + otherColor.g;
  193. result.b = this.b + otherColor.b;
  194. return this;
  195. };
  196. /**
  197. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  198. */
  199. Color3.prototype.subtract = function (otherColor) {
  200. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  201. };
  202. /**
  203. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  204. * Returns the unmodified current Color3.
  205. */
  206. Color3.prototype.subtractToRef = function (otherColor, result) {
  207. result.r = this.r - otherColor.r;
  208. result.g = this.g - otherColor.g;
  209. result.b = this.b - otherColor.b;
  210. return this;
  211. };
  212. /**
  213. * Returns a new Color3 copied the current one.
  214. */
  215. Color3.prototype.clone = function () {
  216. return new Color3(this.r, this.g, this.b);
  217. };
  218. /**
  219. * Copies the rgb values from the source in the current Color3.
  220. * Returns the updated Color3.
  221. */
  222. Color3.prototype.copyFrom = function (source) {
  223. this.r = source.r;
  224. this.g = source.g;
  225. this.b = source.b;
  226. return this;
  227. };
  228. /**
  229. * Updates the Color3 rgb values from the passed floats.
  230. * Returns the Color3.
  231. */
  232. Color3.prototype.copyFromFloats = function (r, g, b) {
  233. this.r = r;
  234. this.g = g;
  235. this.b = b;
  236. return this;
  237. };
  238. /**
  239. * Updates the Color3 rgb values from the passed floats.
  240. * Returns the Color3.
  241. */
  242. Color3.prototype.set = function (r, g, b) {
  243. return this.copyFromFloats(r, g, b);
  244. };
  245. /**
  246. * Returns the Color3 hexadecimal code as a string.
  247. */
  248. Color3.prototype.toHexString = function () {
  249. var intR = (this.r * 255) | 0;
  250. var intG = (this.g * 255) | 0;
  251. var intB = (this.b * 255) | 0;
  252. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  253. };
  254. /**
  255. * Returns a new Color3 converted to linear space.
  256. */
  257. Color3.prototype.toLinearSpace = function () {
  258. var convertedColor = new Color3();
  259. this.toLinearSpaceToRef(convertedColor);
  260. return convertedColor;
  261. };
  262. /**
  263. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  264. * Returns the unmodified Color3.
  265. */
  266. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  267. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  268. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  269. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  270. return this;
  271. };
  272. /**
  273. * Returns a new Color3 converted to gamma space.
  274. */
  275. Color3.prototype.toGammaSpace = function () {
  276. var convertedColor = new Color3();
  277. this.toGammaSpaceToRef(convertedColor);
  278. return convertedColor;
  279. };
  280. /**
  281. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  282. * Returns the unmodified Color3.
  283. */
  284. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  285. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  286. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  287. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  288. return this;
  289. };
  290. // Statics
  291. /**
  292. * Creates a new Color3 from the string containing valid hexadecimal values.
  293. */
  294. Color3.FromHexString = function (hex) {
  295. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  296. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  297. return new Color3(0, 0, 0);
  298. }
  299. var r = parseInt(hex.substring(1, 3), 16);
  300. var g = parseInt(hex.substring(3, 5), 16);
  301. var b = parseInt(hex.substring(5, 7), 16);
  302. return Color3.FromInts(r, g, b);
  303. };
  304. /**
  305. * Creates a new Vector3 from the startind index of the passed array.
  306. */
  307. Color3.FromArray = function (array, offset) {
  308. if (offset === void 0) { offset = 0; }
  309. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  310. };
  311. /**
  312. * Creates a new Color3 from integer values ( < 256).
  313. */
  314. Color3.FromInts = function (r, g, b) {
  315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  316. };
  317. /**
  318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  319. */
  320. Color3.Lerp = function (start, end, amount) {
  321. var r = start.r + ((end.r - start.r) * amount);
  322. var g = start.g + ((end.g - start.g) * amount);
  323. var b = start.b + ((end.b - start.b) * amount);
  324. return new Color3(r, g, b);
  325. };
  326. Color3.Red = function () { return new Color3(1, 0, 0); };
  327. Color3.Green = function () { return new Color3(0, 1, 0); };
  328. Color3.Blue = function () { return new Color3(0, 0, 1); };
  329. Color3.Black = function () { return new Color3(0, 0, 0); };
  330. Color3.White = function () { return new Color3(1, 1, 1); };
  331. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  332. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  333. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  334. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  335. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  336. return Color3;
  337. }());
  338. BABYLON.Color3 = Color3;
  339. var Color4 = (function () {
  340. /**
  341. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  342. */
  343. function Color4(r, g, b, a) {
  344. this.r = r;
  345. this.g = g;
  346. this.b = b;
  347. this.a = a;
  348. }
  349. // Operators
  350. /**
  351. * Adds in place the passed Color4 values to the current Color4.
  352. * Returns the updated Color4.
  353. */
  354. Color4.prototype.addInPlace = function (right) {
  355. this.r += right.r;
  356. this.g += right.g;
  357. this.b += right.b;
  358. this.a += right.a;
  359. return this;
  360. };
  361. /**
  362. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  363. */
  364. Color4.prototype.asArray = function () {
  365. var result = [];
  366. this.toArray(result, 0);
  367. return result;
  368. };
  369. /**
  370. * Stores from the starting index in the passed array the Color4 successive values.
  371. * Returns the Color4.
  372. */
  373. Color4.prototype.toArray = function (array, index) {
  374. if (index === undefined) {
  375. index = 0;
  376. }
  377. array[index] = this.r;
  378. array[index + 1] = this.g;
  379. array[index + 2] = this.b;
  380. array[index + 3] = this.a;
  381. return this;
  382. };
  383. /**
  384. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  385. */
  386. Color4.prototype.add = function (right) {
  387. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  388. };
  389. /**
  390. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  391. */
  392. Color4.prototype.subtract = function (right) {
  393. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  394. };
  395. /**
  396. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  397. * Returns the Color4.
  398. */
  399. Color4.prototype.subtractToRef = function (right, result) {
  400. result.r = this.r - right.r;
  401. result.g = this.g - right.g;
  402. result.b = this.b - right.b;
  403. result.a = this.a - right.a;
  404. return this;
  405. };
  406. /**
  407. * Creates a new Color4 with the current Color4 values multiplied by scale.
  408. */
  409. Color4.prototype.scale = function (scale) {
  410. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  411. };
  412. /**
  413. * Multiplies the current Color4 values by scale and stores the result in "result".
  414. * Returns the Color4.
  415. */
  416. Color4.prototype.scaleToRef = function (scale, result) {
  417. result.r = this.r * scale;
  418. result.g = this.g * scale;
  419. result.b = this.b * scale;
  420. result.a = this.a * scale;
  421. return this;
  422. };
  423. /**
  424. * Multipy an RGBA Color4 value by another and return a new Color4 object
  425. * @param color The Color4 (RGBA) value to multiply by
  426. * @returns A new Color4.
  427. */
  428. Color4.prototype.multiply = function (color) {
  429. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  430. };
  431. /**
  432. * Multipy an RGBA Color4 value by another and push the result in a reference value
  433. * @param color The Color4 (RGBA) value to multiply by
  434. * @param result The Color4 (RGBA) to fill the result in
  435. * @returns the result Color4.
  436. */
  437. Color4.prototype.multiplyToRef = function (color, result) {
  438. result.r = this.r * color.r;
  439. result.g = this.g * color.g;
  440. result.b = this.b * color.b;
  441. result.a = this.a * color.a;
  442. return result;
  443. };
  444. /**
  445. * Returns a string with the Color4 values.
  446. */
  447. Color4.prototype.toString = function () {
  448. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  449. };
  450. /**
  451. * Returns the string "Color4"
  452. */
  453. Color4.prototype.getClassName = function () {
  454. return "Color4";
  455. };
  456. /**
  457. * Return the Color4 hash code as a number.
  458. */
  459. Color4.prototype.getHashCode = function () {
  460. var hash = this.r || 0;
  461. hash = (hash * 397) ^ (this.g || 0);
  462. hash = (hash * 397) ^ (this.b || 0);
  463. hash = (hash * 397) ^ (this.a || 0);
  464. return hash;
  465. };
  466. /**
  467. * Creates a new Color4 copied from the current one.
  468. */
  469. Color4.prototype.clone = function () {
  470. return new Color4(this.r, this.g, this.b, this.a);
  471. };
  472. /**
  473. * Copies the passed Color4 values into the current one.
  474. * Returns the updated Color4.
  475. */
  476. Color4.prototype.copyFrom = function (source) {
  477. this.r = source.r;
  478. this.g = source.g;
  479. this.b = source.b;
  480. this.a = source.a;
  481. return this;
  482. };
  483. /**
  484. * Copies the passed float values into the current one.
  485. * Returns the updated Color4.
  486. */
  487. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  488. this.r = r;
  489. this.g = g;
  490. this.b = b;
  491. this.a = a;
  492. return this;
  493. };
  494. /**
  495. * Copies the passed float values into the current one.
  496. * Returns the updated Color4.
  497. */
  498. Color4.prototype.set = function (r, g, b, a) {
  499. return this.copyFromFloats(r, g, b, a);
  500. };
  501. /**
  502. * Returns a string containing the hexadecimal Color4 code.
  503. */
  504. Color4.prototype.toHexString = function () {
  505. var intR = (this.r * 255) | 0;
  506. var intG = (this.g * 255) | 0;
  507. var intB = (this.b * 255) | 0;
  508. var intA = (this.a * 255) | 0;
  509. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  510. };
  511. // Statics
  512. /**
  513. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  514. */
  515. Color4.FromHexString = function (hex) {
  516. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  517. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  518. return new Color4(0.0, 0.0, 0.0, 0.0);
  519. }
  520. var r = parseInt(hex.substring(1, 3), 16);
  521. var g = parseInt(hex.substring(3, 5), 16);
  522. var b = parseInt(hex.substring(5, 7), 16);
  523. var a = parseInt(hex.substring(7, 9), 16);
  524. return Color4.FromInts(r, g, b, a);
  525. };
  526. /**
  527. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  528. */
  529. Color4.Lerp = function (left, right, amount) {
  530. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  531. Color4.LerpToRef(left, right, amount, result);
  532. return result;
  533. };
  534. /**
  535. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  536. */
  537. Color4.LerpToRef = function (left, right, amount, result) {
  538. result.r = left.r + (right.r - left.r) * amount;
  539. result.g = left.g + (right.g - left.g) * amount;
  540. result.b = left.b + (right.b - left.b) * amount;
  541. result.a = left.a + (right.a - left.a) * amount;
  542. };
  543. /**
  544. * Creates a new Color4 from the starting index element of the passed array.
  545. */
  546. Color4.FromArray = function (array, offset) {
  547. if (offset === void 0) { offset = 0; }
  548. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  549. };
  550. /**
  551. * Creates a new Color4 from the passed integers ( < 256 ).
  552. */
  553. Color4.FromInts = function (r, g, b, a) {
  554. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  555. };
  556. Color4.CheckColors4 = function (colors, count) {
  557. // Check if color3 was used
  558. if (colors.length === count * 3) {
  559. var colors4 = [];
  560. for (var index = 0; index < colors.length; index += 3) {
  561. var newIndex = (index / 3) * 4;
  562. colors4[newIndex] = colors[index];
  563. colors4[newIndex + 1] = colors[index + 1];
  564. colors4[newIndex + 2] = colors[index + 2];
  565. colors4[newIndex + 3] = 1.0;
  566. }
  567. return colors4;
  568. }
  569. return colors;
  570. };
  571. return Color4;
  572. }());
  573. BABYLON.Color4 = Color4;
  574. var Vector2 = (function () {
  575. /**
  576. * Creates a new Vector2 from the passed x and y coordinates.
  577. */
  578. function Vector2(x, y) {
  579. this.x = x;
  580. this.y = y;
  581. }
  582. /**
  583. * Returns a string with the Vector2 coordinates.
  584. */
  585. Vector2.prototype.toString = function () {
  586. return "{X: " + this.x + " Y:" + this.y + "}";
  587. };
  588. /**
  589. * Returns the string "Vector2"
  590. */
  591. Vector2.prototype.getClassName = function () {
  592. return "Vector2";
  593. };
  594. /**
  595. * Returns the Vector2 hash code as a number.
  596. */
  597. Vector2.prototype.getHashCode = function () {
  598. var hash = this.x || 0;
  599. hash = (hash * 397) ^ (this.y || 0);
  600. return hash;
  601. };
  602. // Operators
  603. /**
  604. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  605. * Returns the Vector2.
  606. */
  607. Vector2.prototype.toArray = function (array, index) {
  608. if (index === void 0) { index = 0; }
  609. array[index] = this.x;
  610. array[index + 1] = this.y;
  611. return this;
  612. };
  613. /**
  614. * Returns a new array with 2 elements : the Vector2 coordinates.
  615. */
  616. Vector2.prototype.asArray = function () {
  617. var result = [];
  618. this.toArray(result, 0);
  619. return result;
  620. };
  621. /**
  622. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  623. * Returns the updated Vector2.
  624. */
  625. Vector2.prototype.copyFrom = function (source) {
  626. this.x = source.x;
  627. this.y = source.y;
  628. return this;
  629. };
  630. /**
  631. * Sets the Vector2 coordinates with the passed floats.
  632. * Returns the updated Vector2.
  633. */
  634. Vector2.prototype.copyFromFloats = function (x, y) {
  635. this.x = x;
  636. this.y = y;
  637. return this;
  638. };
  639. /**
  640. * Sets the Vector2 coordinates with the passed floats.
  641. * Returns the updated Vector2.
  642. */
  643. Vector2.prototype.set = function (x, y) {
  644. return this.copyFromFloats(x, y);
  645. };
  646. /**
  647. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  648. */
  649. Vector2.prototype.add = function (otherVector) {
  650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  651. };
  652. /**
  653. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  654. * Returns the Vector2.
  655. */
  656. Vector2.prototype.addToRef = function (otherVector, result) {
  657. result.x = this.x + otherVector.x;
  658. result.y = this.y + otherVector.y;
  659. return this;
  660. };
  661. /**
  662. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  663. * Returns the updated Vector2.
  664. */
  665. Vector2.prototype.addInPlace = function (otherVector) {
  666. this.x += otherVector.x;
  667. this.y += otherVector.y;
  668. return this;
  669. };
  670. /**
  671. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  672. */
  673. Vector2.prototype.addVector3 = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  678. */
  679. Vector2.prototype.subtract = function (otherVector) {
  680. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.subtractToRef = function (otherVector, result) {
  687. result.x = this.x - otherVector.x;
  688. result.y = this.y - otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.subtractInPlace = function (otherVector) {
  696. this.x -= otherVector.x;
  697. this.y -= otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Multiplies in place the current Vector2 coordinates by the passed ones.
  702. * Returns the updated Vector2.
  703. */
  704. Vector2.prototype.multiplyInPlace = function (otherVector) {
  705. this.x *= otherVector.x;
  706. this.y *= otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  711. */
  712. Vector2.prototype.multiply = function (otherVector) {
  713. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  714. };
  715. /**
  716. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  717. * Returns the Vector2.
  718. */
  719. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  720. result.x = this.x * otherVector.x;
  721. result.y = this.y * otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  726. */
  727. Vector2.prototype.multiplyByFloats = function (x, y) {
  728. return new Vector2(this.x * x, this.y * y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  732. */
  733. Vector2.prototype.divide = function (otherVector) {
  734. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.divideToRef = function (otherVector, result) {
  741. result.x = this.x / otherVector.x;
  742. result.y = this.y / otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Returns a new Vector2 with current Vector2 negated coordinates.
  747. */
  748. Vector2.prototype.negate = function () {
  749. return new Vector2(-this.x, -this.y);
  750. };
  751. /**
  752. * Multiply the Vector2 coordinates by scale.
  753. * Returns the updated Vector2.
  754. */
  755. Vector2.prototype.scaleInPlace = function (scale) {
  756. this.x *= scale;
  757. this.y *= scale;
  758. return this;
  759. };
  760. /**
  761. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  762. */
  763. Vector2.prototype.scale = function (scale) {
  764. return new Vector2(this.x * scale, this.y * scale);
  765. };
  766. /**
  767. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  768. */
  769. Vector2.prototype.equals = function (otherVector) {
  770. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  771. };
  772. /**
  773. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  774. */
  775. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  776. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  777. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  778. };
  779. // Properties
  780. /**
  781. * Returns the vector length (float).
  782. */
  783. Vector2.prototype.length = function () {
  784. return Math.sqrt(this.x * this.x + this.y * this.y);
  785. };
  786. /**
  787. * Returns the vector squared length (float);
  788. */
  789. Vector2.prototype.lengthSquared = function () {
  790. return (this.x * this.x + this.y * this.y);
  791. };
  792. // Methods
  793. /**
  794. * Normalize the vector.
  795. * Returns the updated Vector2.
  796. */
  797. Vector2.prototype.normalize = function () {
  798. var len = this.length();
  799. if (len === 0)
  800. return this;
  801. var num = 1.0 / len;
  802. this.x *= num;
  803. this.y *= num;
  804. return this;
  805. };
  806. /**
  807. * Returns a new Vector2 copied from the Vector2.
  808. */
  809. Vector2.prototype.clone = function () {
  810. return new Vector2(this.x, this.y);
  811. };
  812. // Statics
  813. /**
  814. * Returns a new Vector2(0, 0)
  815. */
  816. Vector2.Zero = function () {
  817. return new Vector2(0, 0);
  818. };
  819. /**
  820. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  821. */
  822. Vector2.FromArray = function (array, offset) {
  823. if (offset === void 0) { offset = 0; }
  824. return new Vector2(array[offset], array[offset + 1]);
  825. };
  826. /**
  827. * Sets "result" from the passed index element of the passed array or Float32Array.
  828. * Returns the Vector2.
  829. */
  830. Vector2.FromArrayToRef = function (array, offset, result) {
  831. result.x = array[offset];
  832. result.y = array[offset + 1];
  833. };
  834. /**
  835. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  836. */
  837. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  838. var squared = amount * amount;
  839. var cubed = amount * squared;
  840. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  841. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  842. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  843. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  844. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  845. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * 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".
  850. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  851. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  852. */
  853. Vector2.Clamp = function (value, min, max) {
  854. var x = value.x;
  855. x = (x > max.x) ? max.x : x;
  856. x = (x < min.x) ? min.x : x;
  857. var y = value.y;
  858. y = (y > max.y) ? max.y : y;
  859. y = (y < min.y) ? min.y : y;
  860. return new Vector2(x, y);
  861. };
  862. /**
  863. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  864. */
  865. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  866. var squared = amount * amount;
  867. var cubed = amount * squared;
  868. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  869. var part2 = (-2.0 * cubed) + (3.0 * squared);
  870. var part3 = (cubed - (2.0 * squared)) + amount;
  871. var part4 = cubed - squared;
  872. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  873. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  874. return new Vector2(x, y);
  875. };
  876. /**
  877. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  878. */
  879. Vector2.Lerp = function (start, end, amount) {
  880. var x = start.x + ((end.x - start.x) * amount);
  881. var y = start.y + ((end.y - start.y) * amount);
  882. return new Vector2(x, y);
  883. };
  884. /**
  885. * Returns the dot product (float) of the vector "left" and the vector "right".
  886. */
  887. Vector2.Dot = function (left, right) {
  888. return left.x * right.x + left.y * right.y;
  889. };
  890. /**
  891. * Returns a new Vector2 equal to the normalized passed vector.
  892. */
  893. Vector2.Normalize = function (vector) {
  894. var newVector = vector.clone();
  895. newVector.normalize();
  896. return newVector;
  897. };
  898. /**
  899. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  900. */
  901. Vector2.Minimize = function (left, right) {
  902. var x = (left.x < right.x) ? left.x : right.x;
  903. var y = (left.y < right.y) ? left.y : right.y;
  904. return new Vector2(x, y);
  905. };
  906. /**
  907. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  908. */
  909. Vector2.Maximize = function (left, right) {
  910. var x = (left.x > right.x) ? left.x : right.x;
  911. var y = (left.y > right.y) ? left.y : right.y;
  912. return new Vector2(x, y);
  913. };
  914. /**
  915. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  916. */
  917. Vector2.Transform = function (vector, transformation) {
  918. var r = Vector2.Zero();
  919. Vector2.TransformToRef(vector, transformation, r);
  920. return r;
  921. };
  922. /**
  923. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  924. */
  925. Vector2.TransformToRef = function (vector, transformation, result) {
  926. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  927. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  928. result.x = x;
  929. result.y = y;
  930. };
  931. /**
  932. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  933. */
  934. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  935. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  936. var sign = a < 0 ? -1 : 1;
  937. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  938. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  939. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  940. };
  941. /**
  942. * Returns the distance (float) between the vectors "value1" and "value2".
  943. */
  944. Vector2.Distance = function (value1, value2) {
  945. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  946. };
  947. /**
  948. * Returns the squared distance (float) between the vectors "value1" and "value2".
  949. */
  950. Vector2.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. return (x * x) + (y * y);
  954. };
  955. /**
  956. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  957. */
  958. Vector2.Center = function (value1, value2) {
  959. var center = value1.add(value2);
  960. center.scaleInPlace(0.5);
  961. return center;
  962. };
  963. /**
  964. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  965. */
  966. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  967. var l2 = Vector2.DistanceSquared(segA, segB);
  968. if (l2 === 0.0) {
  969. return Vector2.Distance(p, segA);
  970. }
  971. var v = segB.subtract(segA);
  972. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  973. var proj = segA.add(v.multiplyByFloats(t, t));
  974. return Vector2.Distance(p, proj);
  975. };
  976. return Vector2;
  977. }());
  978. BABYLON.Vector2 = Vector2;
  979. var Vector3 = (function () {
  980. /**
  981. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  982. * A Vector3 is the main object used in 3D geometry.
  983. * It can represent etiher the coordinates of a point the space, either a direction.
  984. */
  985. function Vector3(x, y, z) {
  986. this.x = x;
  987. this.y = y;
  988. this.z = z;
  989. }
  990. /**
  991. * Returns a string with the Vector3 coordinates.
  992. */
  993. Vector3.prototype.toString = function () {
  994. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  995. };
  996. /**
  997. * Returns the string "Vector3"
  998. */
  999. Vector3.prototype.getClassName = function () {
  1000. return "Vector3";
  1001. };
  1002. /**
  1003. * Returns the Vector hash code.
  1004. */
  1005. Vector3.prototype.getHashCode = function () {
  1006. var hash = this.x || 0;
  1007. hash = (hash * 397) ^ (this.y || 0);
  1008. hash = (hash * 397) ^ (this.z || 0);
  1009. return hash;
  1010. };
  1011. // Operators
  1012. /**
  1013. * Returns a new array with three elements : the coordinates the Vector3.
  1014. */
  1015. Vector3.prototype.asArray = function () {
  1016. var result = [];
  1017. this.toArray(result, 0);
  1018. return result;
  1019. };
  1020. /**
  1021. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1022. * Returns the Vector3.
  1023. */
  1024. Vector3.prototype.toArray = function (array, index) {
  1025. if (index === void 0) { index = 0; }
  1026. array[index] = this.x;
  1027. array[index + 1] = this.y;
  1028. array[index + 2] = this.z;
  1029. return this;
  1030. };
  1031. /**
  1032. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1033. */
  1034. Vector3.prototype.toQuaternion = function () {
  1035. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1036. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1037. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1038. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1039. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1040. var cosy = Math.cos(this.y * 0.5);
  1041. var siny = Math.sin(this.y * 0.5);
  1042. result.x = coszMinusx * siny;
  1043. result.y = -sinzMinusx * siny;
  1044. result.z = sinxPlusz * cosy;
  1045. result.w = cosxPlusz * cosy;
  1046. return result;
  1047. };
  1048. /**
  1049. * Adds the passed vector to the current Vector3.
  1050. * Returns the updated Vector3.
  1051. */
  1052. Vector3.prototype.addInPlace = function (otherVector) {
  1053. this.x += otherVector.x;
  1054. this.y += otherVector.y;
  1055. this.z += otherVector.z;
  1056. return this;
  1057. };
  1058. /**
  1059. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1060. */
  1061. Vector3.prototype.add = function (otherVector) {
  1062. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1063. };
  1064. /**
  1065. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1066. * Returns the current Vector3.
  1067. */
  1068. Vector3.prototype.addToRef = function (otherVector, result) {
  1069. result.x = this.x + otherVector.x;
  1070. result.y = this.y + otherVector.y;
  1071. result.z = this.z + otherVector.z;
  1072. return this;
  1073. };
  1074. /**
  1075. * Subtract the passed vector from the current Vector3.
  1076. * Returns the updated Vector3.
  1077. */
  1078. Vector3.prototype.subtractInPlace = function (otherVector) {
  1079. this.x -= otherVector.x;
  1080. this.y -= otherVector.y;
  1081. this.z -= otherVector.z;
  1082. return this;
  1083. };
  1084. /**
  1085. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1086. */
  1087. Vector3.prototype.subtract = function (otherVector) {
  1088. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1089. };
  1090. /**
  1091. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1092. * Returns the current Vector3.
  1093. */
  1094. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1095. result.x = this.x - otherVector.x;
  1096. result.y = this.y - otherVector.y;
  1097. result.z = this.z - otherVector.z;
  1098. return this;
  1099. };
  1100. /**
  1101. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1102. */
  1103. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1104. return new Vector3(this.x - x, this.y - y, this.z - z);
  1105. };
  1106. /**
  1107. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1108. * Returns the current Vector3.
  1109. */
  1110. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1111. result.x = this.x - x;
  1112. result.y = this.y - y;
  1113. result.z = this.z - z;
  1114. return this;
  1115. };
  1116. /**
  1117. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1118. */
  1119. Vector3.prototype.negate = function () {
  1120. return new Vector3(-this.x, -this.y, -this.z);
  1121. };
  1122. /**
  1123. * Multiplies the Vector3 coordinates by the float "scale".
  1124. * Returns the updated Vector3.
  1125. */
  1126. Vector3.prototype.scaleInPlace = function (scale) {
  1127. this.x *= scale;
  1128. this.y *= scale;
  1129. this.z *= scale;
  1130. return this;
  1131. };
  1132. /**
  1133. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1134. */
  1135. Vector3.prototype.scale = function (scale) {
  1136. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1137. };
  1138. /**
  1139. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1140. * Returns the current Vector3.
  1141. */
  1142. Vector3.prototype.scaleToRef = function (scale, result) {
  1143. result.x = this.x * scale;
  1144. result.y = this.y * scale;
  1145. result.z = this.z * scale;
  1146. return this;
  1147. };
  1148. /**
  1149. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1150. */
  1151. Vector3.prototype.equals = function (otherVector) {
  1152. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1153. };
  1154. /**
  1155. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1156. */
  1157. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1158. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1159. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1160. };
  1161. /**
  1162. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1163. */
  1164. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1165. return this.x === x && this.y === y && this.z === z;
  1166. };
  1167. /**
  1168. * Muliplies the current Vector3 coordinates by the passed ones.
  1169. * Returns the updated Vector3.
  1170. */
  1171. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1172. this.x *= otherVector.x;
  1173. this.y *= otherVector.y;
  1174. this.z *= otherVector.z;
  1175. return this;
  1176. };
  1177. /**
  1178. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1179. */
  1180. Vector3.prototype.multiply = function (otherVector) {
  1181. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1182. };
  1183. /**
  1184. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1185. * Returns the current Vector3.
  1186. */
  1187. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1188. result.x = this.x * otherVector.x;
  1189. result.y = this.y * otherVector.y;
  1190. result.z = this.z * otherVector.z;
  1191. return this;
  1192. };
  1193. /**
  1194. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1195. */
  1196. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1197. return new Vector3(this.x * x, this.y * y, this.z * z);
  1198. };
  1199. /**
  1200. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1201. */
  1202. Vector3.prototype.divide = function (otherVector) {
  1203. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1204. };
  1205. /**
  1206. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1207. * Returns the current Vector3.
  1208. */
  1209. Vector3.prototype.divideToRef = function (otherVector, result) {
  1210. result.x = this.x / otherVector.x;
  1211. result.y = this.y / otherVector.y;
  1212. result.z = this.z / otherVector.z;
  1213. return this;
  1214. };
  1215. /**
  1216. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1217. * Returns the updated Vector3.
  1218. */
  1219. Vector3.prototype.MinimizeInPlace = function (other) {
  1220. if (other.x < this.x)
  1221. this.x = other.x;
  1222. if (other.y < this.y)
  1223. this.y = other.y;
  1224. if (other.z < this.z)
  1225. this.z = other.z;
  1226. return this;
  1227. };
  1228. /**
  1229. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1230. * Returns the updated Vector3.
  1231. */
  1232. Vector3.prototype.MaximizeInPlace = function (other) {
  1233. if (other.x > this.x)
  1234. this.x = other.x;
  1235. if (other.y > this.y)
  1236. this.y = other.y;
  1237. if (other.z > this.z)
  1238. this.z = other.z;
  1239. return this;
  1240. };
  1241. // Properties
  1242. /**
  1243. * Returns the length of the Vector3 (float).
  1244. */
  1245. Vector3.prototype.length = function () {
  1246. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1247. };
  1248. /**
  1249. * Returns the squared length of the Vector3 (float).
  1250. */
  1251. Vector3.prototype.lengthSquared = function () {
  1252. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1253. };
  1254. // Methods
  1255. /**
  1256. * Normalize the current Vector3.
  1257. * Returns the updated Vector3.
  1258. */
  1259. Vector3.prototype.normalize = function () {
  1260. var len = this.length();
  1261. if (len === 0 || len === 1.0)
  1262. return this;
  1263. var num = 1.0 / len;
  1264. this.x *= num;
  1265. this.y *= num;
  1266. this.z *= num;
  1267. return this;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 copied from the current Vector3.
  1271. */
  1272. Vector3.prototype.clone = function () {
  1273. return new Vector3(this.x, this.y, this.z);
  1274. };
  1275. /**
  1276. * Copies the passed vector coordinates to the current Vector3 ones.
  1277. * Returns the updated Vector3.
  1278. */
  1279. Vector3.prototype.copyFrom = function (source) {
  1280. this.x = source.x;
  1281. this.y = source.y;
  1282. this.z = source.z;
  1283. return this;
  1284. };
  1285. /**
  1286. * Copies the passed floats to the current Vector3 coordinates.
  1287. * Returns the updated Vector3.
  1288. */
  1289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1290. this.x = x;
  1291. this.y = y;
  1292. this.z = z;
  1293. return this;
  1294. };
  1295. /**
  1296. * Copies the passed floats to the current Vector3 coordinates.
  1297. * Returns the updated Vector3.
  1298. */
  1299. Vector3.prototype.set = function (x, y, z) {
  1300. return this.copyFromFloats(x, y, z);
  1301. };
  1302. // Statics
  1303. /**
  1304. *
  1305. */
  1306. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1307. var d0 = Vector3.Dot(vector0, axis) - size;
  1308. var d1 = Vector3.Dot(vector1, axis) - size;
  1309. var s = d0 / (d0 - d1);
  1310. return s;
  1311. };
  1312. /**
  1313. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1314. */
  1315. Vector3.FromArray = function (array, offset) {
  1316. if (!offset) {
  1317. offset = 0;
  1318. }
  1319. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1320. };
  1321. /**
  1322. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1323. */
  1324. Vector3.FromFloatArray = function (array, offset) {
  1325. if (!offset) {
  1326. offset = 0;
  1327. }
  1328. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1329. };
  1330. /**
  1331. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1332. */
  1333. Vector3.FromArrayToRef = function (array, offset, result) {
  1334. result.x = array[offset];
  1335. result.y = array[offset + 1];
  1336. result.z = array[offset + 2];
  1337. };
  1338. /**
  1339. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1340. */
  1341. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1342. result.x = array[offset];
  1343. result.y = array[offset + 1];
  1344. result.z = array[offset + 2];
  1345. };
  1346. /**
  1347. * Sets the passed vector "result" with the passed floats.
  1348. */
  1349. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1350. result.x = x;
  1351. result.y = y;
  1352. result.z = z;
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1356. */
  1357. Vector3.Zero = function () {
  1358. return new Vector3(0.0, 0.0, 0.0);
  1359. };
  1360. /**
  1361. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1362. */
  1363. Vector3.Up = function () {
  1364. return new Vector3(0.0, 1.0, 0.0);
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1368. */
  1369. Vector3.Forward = function () {
  1370. return new Vector3(0.0, 0.0, 1.0);
  1371. };
  1372. /**
  1373. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1374. */
  1375. Vector3.Right = function () {
  1376. return new Vector3(1.0, 0.0, 0.0);
  1377. };
  1378. /**
  1379. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1380. */
  1381. Vector3.Left = function () {
  1382. return new Vector3(-1.0, 0.0, 0.0);
  1383. };
  1384. /**
  1385. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1386. * This method computes tranformed coordinates only, not transformed direction vectors.
  1387. */
  1388. Vector3.TransformCoordinates = function (vector, transformation) {
  1389. var result = Vector3.Zero();
  1390. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1391. return result;
  1392. };
  1393. /**
  1394. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1395. * This method computes tranformed coordinates only, not transformed direction vectors.
  1396. */
  1397. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1398. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1399. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1400. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1401. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1402. result.x = x / w;
  1403. result.y = y / w;
  1404. result.z = z / w;
  1405. };
  1406. /**
  1407. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1408. * This method computes tranformed coordinates only, not transformed direction vectors.
  1409. */
  1410. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1411. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1412. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1413. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1414. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1415. result.x = rx / rw;
  1416. result.y = ry / rw;
  1417. result.z = rz / rw;
  1418. };
  1419. /**
  1420. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1421. * This methods computes transformed normalized direction vectors only.
  1422. */
  1423. Vector3.TransformNormal = function (vector, transformation) {
  1424. var result = Vector3.Zero();
  1425. Vector3.TransformNormalToRef(vector, transformation, result);
  1426. return result;
  1427. };
  1428. /**
  1429. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1430. * This methods computes transformed normalized direction vectors only.
  1431. */
  1432. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1433. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1434. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1435. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1436. result.x = x;
  1437. result.y = y;
  1438. result.z = z;
  1439. };
  1440. /**
  1441. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1442. * This methods computes transformed normalized direction vectors only.
  1443. */
  1444. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1445. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1446. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1447. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1448. };
  1449. /**
  1450. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1451. */
  1452. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1453. var squared = amount * amount;
  1454. var cubed = amount * squared;
  1455. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1456. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1457. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1458. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1459. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1460. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1461. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1462. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1463. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1464. return new Vector3(x, y, z);
  1465. };
  1466. /**
  1467. * 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".
  1468. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1469. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1470. */
  1471. Vector3.Clamp = function (value, min, max) {
  1472. var x = value.x;
  1473. x = (x > max.x) ? max.x : x;
  1474. x = (x < min.x) ? min.x : x;
  1475. var y = value.y;
  1476. y = (y > max.y) ? max.y : y;
  1477. y = (y < min.y) ? min.y : y;
  1478. var z = value.z;
  1479. z = (z > max.z) ? max.z : z;
  1480. z = (z < min.z) ? min.z : z;
  1481. return new Vector3(x, y, z);
  1482. };
  1483. /**
  1484. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1485. */
  1486. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1487. var squared = amount * amount;
  1488. var cubed = amount * squared;
  1489. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1490. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1491. var part3 = (cubed - (2.0 * squared)) + amount;
  1492. var part4 = cubed - squared;
  1493. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1494. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1495. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1500. */
  1501. Vector3.Lerp = function (start, end, amount) {
  1502. var result = new Vector3(0, 0, 0);
  1503. Vector3.LerpToRef(start, end, amount, result);
  1504. return result;
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1508. */
  1509. Vector3.LerpToRef = function (start, end, amount, result) {
  1510. result.x = start.x + ((end.x - start.x) * amount);
  1511. result.y = start.y + ((end.y - start.y) * amount);
  1512. result.z = start.z + ((end.z - start.z) * amount);
  1513. };
  1514. /**
  1515. * Returns the dot product (float) between the vectors "left" and "right".
  1516. */
  1517. Vector3.Dot = function (left, right) {
  1518. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1519. };
  1520. /**
  1521. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1522. * The cross product is then orthogonal to both "left" and "right".
  1523. */
  1524. Vector3.Cross = function (left, right) {
  1525. var result = Vector3.Zero();
  1526. Vector3.CrossToRef(left, right, result);
  1527. return result;
  1528. };
  1529. /**
  1530. * Sets the passed vector "result" with the cross product of "left" and "right".
  1531. * The cross product is then orthogonal to both "left" and "right".
  1532. */
  1533. Vector3.CrossToRef = function (left, right, result) {
  1534. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1535. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1536. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1537. result.copyFrom(MathTmp.Vector3[0]);
  1538. };
  1539. /**
  1540. * Returns a new Vector3 as the normalization of the passed vector.
  1541. */
  1542. Vector3.Normalize = function (vector) {
  1543. var result = Vector3.Zero();
  1544. Vector3.NormalizeToRef(vector, result);
  1545. return result;
  1546. };
  1547. /**
  1548. * Sets the passed vector "result" with the normalization of the passed first vector.
  1549. */
  1550. Vector3.NormalizeToRef = function (vector, result) {
  1551. result.copyFrom(vector);
  1552. result.normalize();
  1553. };
  1554. Vector3.Project = function (vector, world, transform, viewport) {
  1555. var cw = viewport.width;
  1556. var ch = viewport.height;
  1557. var cx = viewport.x;
  1558. var cy = viewport.y;
  1559. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1560. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1561. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1562. world.multiplyToRef(transform, matrix);
  1563. matrix.multiplyToRef(viewportMatrix, matrix);
  1564. return Vector3.TransformCoordinates(vector, matrix);
  1565. };
  1566. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1567. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1568. world.multiplyToRef(transform, matrix);
  1569. matrix.invert();
  1570. source.x = source.x / viewportWidth * 2 - 1;
  1571. source.y = -(source.y / viewportHeight * 2 - 1);
  1572. var vector = Vector3.TransformCoordinates(source, matrix);
  1573. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1574. if (MathTools.WithinEpsilon(num, 1.0)) {
  1575. vector = vector.scale(1.0 / num);
  1576. }
  1577. return vector;
  1578. };
  1579. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1580. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1581. world.multiplyToRef(view, matrix);
  1582. matrix.multiplyToRef(projection, matrix);
  1583. matrix.invert();
  1584. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1585. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1586. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1587. if (MathTools.WithinEpsilon(num, 1.0)) {
  1588. vector = vector.scale(1.0 / num);
  1589. }
  1590. return vector;
  1591. };
  1592. Vector3.Minimize = function (left, right) {
  1593. var min = left.clone();
  1594. min.MinimizeInPlace(right);
  1595. return min;
  1596. };
  1597. Vector3.Maximize = function (left, right) {
  1598. var max = left.clone();
  1599. max.MaximizeInPlace(right);
  1600. return max;
  1601. };
  1602. /**
  1603. * Returns the distance (float) between the vectors "value1" and "value2".
  1604. */
  1605. Vector3.Distance = function (value1, value2) {
  1606. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1607. };
  1608. /**
  1609. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1610. */
  1611. Vector3.DistanceSquared = function (value1, value2) {
  1612. var x = value1.x - value2.x;
  1613. var y = value1.y - value2.y;
  1614. var z = value1.z - value2.z;
  1615. return (x * x) + (y * y) + (z * z);
  1616. };
  1617. /**
  1618. * Returns a new Vector3 located at the center between "value1" and "value2".
  1619. */
  1620. Vector3.Center = function (value1, value2) {
  1621. var center = value1.add(value2);
  1622. center.scaleInPlace(0.5);
  1623. return center;
  1624. };
  1625. /**
  1626. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1627. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1628. * to something in order to rotate it from its local system to the given target system.
  1629. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1630. * Returns a new Vector3.
  1631. */
  1632. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1633. var rotation = Vector3.Zero();
  1634. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1635. return rotation;
  1636. };
  1637. /**
  1638. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1639. */
  1640. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1641. var quat = MathTmp.Quaternion[0];
  1642. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1643. quat.toEulerAnglesToRef(ref);
  1644. };
  1645. return Vector3;
  1646. }());
  1647. BABYLON.Vector3 = Vector3;
  1648. //Vector4 class created for EulerAngle class conversion to Quaternion
  1649. var Vector4 = (function () {
  1650. /**
  1651. * Creates a Vector4 object from the passed floats.
  1652. */
  1653. function Vector4(x, y, z, w) {
  1654. this.x = x;
  1655. this.y = y;
  1656. this.z = z;
  1657. this.w = w;
  1658. }
  1659. /**
  1660. * Returns the string with the Vector4 coordinates.
  1661. */
  1662. Vector4.prototype.toString = function () {
  1663. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1664. };
  1665. /**
  1666. * Returns the string "Vector4".
  1667. */
  1668. Vector4.prototype.getClassName = function () {
  1669. return "Vector4";
  1670. };
  1671. /**
  1672. * Returns the Vector4 hash code.
  1673. */
  1674. Vector4.prototype.getHashCode = function () {
  1675. var hash = this.x || 0;
  1676. hash = (hash * 397) ^ (this.y || 0);
  1677. hash = (hash * 397) ^ (this.z || 0);
  1678. hash = (hash * 397) ^ (this.w || 0);
  1679. return hash;
  1680. };
  1681. // Operators
  1682. /**
  1683. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1684. */
  1685. Vector4.prototype.asArray = function () {
  1686. var result = [];
  1687. this.toArray(result, 0);
  1688. return result;
  1689. };
  1690. /**
  1691. * Populates the passed array from the passed index with the Vector4 coordinates.
  1692. * Returns the Vector4.
  1693. */
  1694. Vector4.prototype.toArray = function (array, index) {
  1695. if (index === undefined) {
  1696. index = 0;
  1697. }
  1698. array[index] = this.x;
  1699. array[index + 1] = this.y;
  1700. array[index + 2] = this.z;
  1701. array[index + 3] = this.w;
  1702. return this;
  1703. };
  1704. /**
  1705. * Adds the passed vector to the current Vector4.
  1706. * Returns the updated Vector4.
  1707. */
  1708. Vector4.prototype.addInPlace = function (otherVector) {
  1709. this.x += otherVector.x;
  1710. this.y += otherVector.y;
  1711. this.z += otherVector.z;
  1712. this.w += otherVector.w;
  1713. return this;
  1714. };
  1715. /**
  1716. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1717. */
  1718. Vector4.prototype.add = function (otherVector) {
  1719. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1720. };
  1721. /**
  1722. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1723. * Returns the current Vector4.
  1724. */
  1725. Vector4.prototype.addToRef = function (otherVector, result) {
  1726. result.x = this.x + otherVector.x;
  1727. result.y = this.y + otherVector.y;
  1728. result.z = this.z + otherVector.z;
  1729. result.w = this.w + otherVector.w;
  1730. return this;
  1731. };
  1732. /**
  1733. * Subtract in place the passed vector from the current Vector4.
  1734. * Returns the updated Vector4.
  1735. */
  1736. Vector4.prototype.subtractInPlace = function (otherVector) {
  1737. this.x -= otherVector.x;
  1738. this.y -= otherVector.y;
  1739. this.z -= otherVector.z;
  1740. this.w -= otherVector.w;
  1741. return this;
  1742. };
  1743. /**
  1744. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1745. */
  1746. Vector4.prototype.subtract = function (otherVector) {
  1747. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1748. };
  1749. /**
  1750. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1751. * Returns the current Vector4.
  1752. */
  1753. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1754. result.x = this.x - otherVector.x;
  1755. result.y = this.y - otherVector.y;
  1756. result.z = this.z - otherVector.z;
  1757. result.w = this.w - otherVector.w;
  1758. return this;
  1759. };
  1760. /**
  1761. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1762. */
  1763. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1764. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1765. };
  1766. /**
  1767. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1768. * Returns the current Vector4.
  1769. */
  1770. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1771. result.x = this.x - x;
  1772. result.y = this.y - y;
  1773. result.z = this.z - z;
  1774. result.w = this.w - w;
  1775. return this;
  1776. };
  1777. /**
  1778. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1779. */
  1780. Vector4.prototype.negate = function () {
  1781. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1782. };
  1783. /**
  1784. * Multiplies the current Vector4 coordinates by scale (float).
  1785. * Returns the updated Vector4.
  1786. */
  1787. Vector4.prototype.scaleInPlace = function (scale) {
  1788. this.x *= scale;
  1789. this.y *= scale;
  1790. this.z *= scale;
  1791. this.w *= scale;
  1792. return this;
  1793. };
  1794. /**
  1795. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1796. */
  1797. Vector4.prototype.scale = function (scale) {
  1798. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1799. };
  1800. /**
  1801. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1802. * Returns the current Vector4.
  1803. */
  1804. Vector4.prototype.scaleToRef = function (scale, result) {
  1805. result.x = this.x * scale;
  1806. result.y = this.y * scale;
  1807. result.z = this.z * scale;
  1808. result.w = this.w * scale;
  1809. return this;
  1810. };
  1811. /**
  1812. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1813. */
  1814. Vector4.prototype.equals = function (otherVector) {
  1815. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1816. };
  1817. /**
  1818. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1819. */
  1820. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1821. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1822. return otherVector
  1823. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1824. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1825. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1826. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1827. };
  1828. /**
  1829. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1830. */
  1831. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1832. return this.x === x && this.y === y && this.z === z && this.w === w;
  1833. };
  1834. /**
  1835. * Multiplies in place the current Vector4 by the passed one.
  1836. * Returns the updated Vector4.
  1837. */
  1838. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1839. this.x *= otherVector.x;
  1840. this.y *= otherVector.y;
  1841. this.z *= otherVector.z;
  1842. this.w *= otherVector.w;
  1843. return this;
  1844. };
  1845. /**
  1846. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1847. */
  1848. Vector4.prototype.multiply = function (otherVector) {
  1849. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1850. };
  1851. /**
  1852. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1853. * Returns the current Vector4.
  1854. */
  1855. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1856. result.x = this.x * otherVector.x;
  1857. result.y = this.y * otherVector.y;
  1858. result.z = this.z * otherVector.z;
  1859. result.w = this.w * otherVector.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1864. */
  1865. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1866. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1867. };
  1868. /**
  1869. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1870. */
  1871. Vector4.prototype.divide = function (otherVector) {
  1872. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1873. };
  1874. /**
  1875. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1876. * Returns the current Vector4.
  1877. */
  1878. Vector4.prototype.divideToRef = function (otherVector, result) {
  1879. result.x = this.x / otherVector.x;
  1880. result.y = this.y / otherVector.y;
  1881. result.z = this.z / otherVector.z;
  1882. result.w = this.w / otherVector.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1887. */
  1888. Vector4.prototype.MinimizeInPlace = function (other) {
  1889. if (other.x < this.x)
  1890. this.x = other.x;
  1891. if (other.y < this.y)
  1892. this.y = other.y;
  1893. if (other.z < this.z)
  1894. this.z = other.z;
  1895. if (other.w < this.w)
  1896. this.w = other.w;
  1897. return this;
  1898. };
  1899. /**
  1900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1901. */
  1902. Vector4.prototype.MaximizeInPlace = function (other) {
  1903. if (other.x > this.x)
  1904. this.x = other.x;
  1905. if (other.y > this.y)
  1906. this.y = other.y;
  1907. if (other.z > this.z)
  1908. this.z = other.z;
  1909. if (other.w > this.w)
  1910. this.w = other.w;
  1911. return this;
  1912. };
  1913. // Properties
  1914. /**
  1915. * Returns the Vector4 length (float).
  1916. */
  1917. Vector4.prototype.length = function () {
  1918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1919. };
  1920. /**
  1921. * Returns the Vector4 squared length (float).
  1922. */
  1923. Vector4.prototype.lengthSquared = function () {
  1924. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1925. };
  1926. // Methods
  1927. /**
  1928. * Normalizes in place the Vector4.
  1929. * Returns the updated Vector4.
  1930. */
  1931. Vector4.prototype.normalize = function () {
  1932. var len = this.length();
  1933. if (len === 0)
  1934. return this;
  1935. var num = 1.0 / len;
  1936. this.x *= num;
  1937. this.y *= num;
  1938. this.z *= num;
  1939. this.w *= num;
  1940. return this;
  1941. };
  1942. /**
  1943. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1944. */
  1945. Vector4.prototype.toVector3 = function () {
  1946. return new Vector3(this.x, this.y, this.z);
  1947. };
  1948. /**
  1949. * Returns a new Vector4 copied from the current one.
  1950. */
  1951. Vector4.prototype.clone = function () {
  1952. return new Vector4(this.x, this.y, this.z, this.w);
  1953. };
  1954. /**
  1955. * Updates the current Vector4 with the passed one coordinates.
  1956. * Returns the updated Vector4.
  1957. */
  1958. Vector4.prototype.copyFrom = function (source) {
  1959. this.x = source.x;
  1960. this.y = source.y;
  1961. this.z = source.z;
  1962. this.w = source.w;
  1963. return this;
  1964. };
  1965. /**
  1966. * Updates the current Vector4 coordinates with the passed floats.
  1967. * Returns the updated Vector4.
  1968. */
  1969. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1970. this.x = x;
  1971. this.y = y;
  1972. this.z = z;
  1973. this.w = w;
  1974. return this;
  1975. };
  1976. /**
  1977. * Updates the current Vector4 coordinates with the passed floats.
  1978. * Returns the updated Vector4.
  1979. */
  1980. Vector4.prototype.set = function (x, y, z, w) {
  1981. return this.copyFromFloats(x, y, z, w);
  1982. };
  1983. // Statics
  1984. /**
  1985. * Returns a new Vector4 set from the starting index of the passed array.
  1986. */
  1987. Vector4.FromArray = function (array, offset) {
  1988. if (!offset) {
  1989. offset = 0;
  1990. }
  1991. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1992. };
  1993. /**
  1994. * Updates the passed vector "result" from the starting index of the passed array.
  1995. */
  1996. Vector4.FromArrayToRef = function (array, offset, result) {
  1997. result.x = array[offset];
  1998. result.y = array[offset + 1];
  1999. result.z = array[offset + 2];
  2000. result.w = array[offset + 3];
  2001. };
  2002. /**
  2003. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2004. */
  2005. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2006. result.x = array[offset];
  2007. result.y = array[offset + 1];
  2008. result.z = array[offset + 2];
  2009. result.w = array[offset + 3];
  2010. };
  2011. /**
  2012. * Updates the passed vector "result" coordinates from the passed floats.
  2013. */
  2014. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2015. result.x = x;
  2016. result.y = y;
  2017. result.z = z;
  2018. result.w = w;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2022. */
  2023. Vector4.Zero = function () {
  2024. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2025. };
  2026. /**
  2027. * Returns a new normalized Vector4 from the passed one.
  2028. */
  2029. Vector4.Normalize = function (vector) {
  2030. var result = Vector4.Zero();
  2031. Vector4.NormalizeToRef(vector, result);
  2032. return result;
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the normalization of the passed one.
  2036. */
  2037. Vector4.NormalizeToRef = function (vector, result) {
  2038. result.copyFrom(vector);
  2039. result.normalize();
  2040. };
  2041. Vector4.Minimize = function (left, right) {
  2042. var min = left.clone();
  2043. min.MinimizeInPlace(right);
  2044. return min;
  2045. };
  2046. Vector4.Maximize = function (left, right) {
  2047. var max = left.clone();
  2048. max.MaximizeInPlace(right);
  2049. return max;
  2050. };
  2051. /**
  2052. * Returns the distance (float) between the vectors "value1" and "value2".
  2053. */
  2054. Vector4.Distance = function (value1, value2) {
  2055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2056. };
  2057. /**
  2058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2059. */
  2060. Vector4.DistanceSquared = function (value1, value2) {
  2061. var x = value1.x - value2.x;
  2062. var y = value1.y - value2.y;
  2063. var z = value1.z - value2.z;
  2064. var w = value1.w - value2.w;
  2065. return (x * x) + (y * y) + (z * z) + (w * w);
  2066. };
  2067. /**
  2068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.Center = function (value1, value2) {
  2071. var center = value1.add(value2);
  2072. center.scaleInPlace(0.5);
  2073. return center;
  2074. };
  2075. /**
  2076. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2077. * This methods computes transformed normalized direction vectors only.
  2078. */
  2079. Vector4.TransformNormal = function (vector, transformation) {
  2080. var result = Vector4.Zero();
  2081. Vector4.TransformNormalToRef(vector, transformation, result);
  2082. return result;
  2083. };
  2084. /**
  2085. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2086. * This methods computes transformed normalized direction vectors only.
  2087. */
  2088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2092. result.x = x;
  2093. result.y = y;
  2094. result.z = z;
  2095. result.w = vector.w;
  2096. };
  2097. /**
  2098. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2099. * This methods computes transformed normalized direction vectors only.
  2100. */
  2101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2105. result.w = w;
  2106. };
  2107. return Vector4;
  2108. }());
  2109. BABYLON.Vector4 = Vector4;
  2110. var Size = (function () {
  2111. /**
  2112. * Creates a Size object from the passed width and height (floats).
  2113. */
  2114. function Size(width, height) {
  2115. this.width = width;
  2116. this.height = height;
  2117. }
  2118. // Returns a string with the Size width and height.
  2119. Size.prototype.toString = function () {
  2120. return "{W: " + this.width + ", H: " + this.height + "}";
  2121. };
  2122. /**
  2123. * Returns the string "Size"
  2124. */
  2125. Size.prototype.getClassName = function () {
  2126. return "Size";
  2127. };
  2128. /**
  2129. * Returns the Size hash code.
  2130. */
  2131. Size.prototype.getHashCode = function () {
  2132. var hash = this.width || 0;
  2133. hash = (hash * 397) ^ (this.height || 0);
  2134. return hash;
  2135. };
  2136. /**
  2137. * Updates the current size from the passed one.
  2138. * Returns the updated Size.
  2139. */
  2140. Size.prototype.copyFrom = function (src) {
  2141. this.width = src.width;
  2142. this.height = src.height;
  2143. };
  2144. /**
  2145. * Updates in place the current Size from the passed floats.
  2146. * Returns the updated Size.
  2147. */
  2148. Size.prototype.copyFromFloats = function (width, height) {
  2149. this.width = width;
  2150. this.height = height;
  2151. return this;
  2152. };
  2153. /**
  2154. * Updates in place the current Size from the passed floats.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.set = function (width, height) {
  2158. return this.copyFromFloats(width, height);
  2159. };
  2160. /**
  2161. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2162. */
  2163. Size.prototype.multiplyByFloats = function (w, h) {
  2164. return new Size(this.width * w, this.height * h);
  2165. };
  2166. /**
  2167. * Returns a new Size copied from the passed one.
  2168. */
  2169. Size.prototype.clone = function () {
  2170. return new Size(this.width, this.height);
  2171. };
  2172. /**
  2173. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2174. */
  2175. Size.prototype.equals = function (other) {
  2176. if (!other) {
  2177. return false;
  2178. }
  2179. return (this.width === other.width) && (this.height === other.height);
  2180. };
  2181. Object.defineProperty(Size.prototype, "surface", {
  2182. /**
  2183. * Returns the surface of the Size : width * height (float).
  2184. */
  2185. get: function () {
  2186. return this.width * this.height;
  2187. },
  2188. enumerable: true,
  2189. configurable: true
  2190. });
  2191. /**
  2192. * Returns a new Size set to (0.0, 0.0)
  2193. */
  2194. Size.Zero = function () {
  2195. return new Size(0.0, 0.0);
  2196. };
  2197. /**
  2198. * Returns a new Size set as the addition result of the current Size and the passed one.
  2199. */
  2200. Size.prototype.add = function (otherSize) {
  2201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2202. return r;
  2203. };
  2204. /**
  2205. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2206. */
  2207. Size.prototype.subtract = function (otherSize) {
  2208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2209. return r;
  2210. };
  2211. /**
  2212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2213. */
  2214. Size.Lerp = function (start, end, amount) {
  2215. var w = start.width + ((end.width - start.width) * amount);
  2216. var h = start.height + ((end.height - start.height) * amount);
  2217. return new Size(w, h);
  2218. };
  2219. return Size;
  2220. }());
  2221. BABYLON.Size = Size;
  2222. var Quaternion = (function () {
  2223. /**
  2224. * Creates a new Quaternion from the passed floats.
  2225. */
  2226. function Quaternion(x, y, z, w) {
  2227. if (x === void 0) { x = 0.0; }
  2228. if (y === void 0) { y = 0.0; }
  2229. if (z === void 0) { z = 0.0; }
  2230. if (w === void 0) { w = 1.0; }
  2231. this.x = x;
  2232. this.y = y;
  2233. this.z = z;
  2234. this.w = w;
  2235. }
  2236. /**
  2237. * Returns a string with the Quaternion coordinates.
  2238. */
  2239. Quaternion.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2241. };
  2242. /**
  2243. * Returns the string "Quaternion".
  2244. */
  2245. Quaternion.prototype.getClassName = function () {
  2246. return "Quaternion";
  2247. };
  2248. /**
  2249. * Returns the Quaternion hash code.
  2250. */
  2251. Quaternion.prototype.getHashCode = function () {
  2252. var hash = this.x || 0;
  2253. hash = (hash * 397) ^ (this.y || 0);
  2254. hash = (hash * 397) ^ (this.z || 0);
  2255. hash = (hash * 397) ^ (this.w || 0);
  2256. return hash;
  2257. };
  2258. /**
  2259. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2260. */
  2261. Quaternion.prototype.asArray = function () {
  2262. return [this.x, this.y, this.z, this.w];
  2263. };
  2264. /**
  2265. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2266. */
  2267. Quaternion.prototype.equals = function (otherQuaternion) {
  2268. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion copied from the current one.
  2272. */
  2273. Quaternion.prototype.clone = function () {
  2274. return new Quaternion(this.x, this.y, this.z, this.w);
  2275. };
  2276. /**
  2277. * Updates the current Quaternion from the passed one coordinates.
  2278. * Returns the updated Quaterion.
  2279. */
  2280. Quaternion.prototype.copyFrom = function (other) {
  2281. this.x = other.x;
  2282. this.y = other.y;
  2283. this.z = other.z;
  2284. this.w = other.w;
  2285. return this;
  2286. };
  2287. /**
  2288. * Updates the current Quaternion from the passed float coordinates.
  2289. * Returns the updated Quaterion.
  2290. */
  2291. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2292. this.x = x;
  2293. this.y = y;
  2294. this.z = z;
  2295. this.w = w;
  2296. return this;
  2297. };
  2298. /**
  2299. * Updates the current Quaternion from the passed float coordinates.
  2300. * Returns the updated Quaterion.
  2301. */
  2302. Quaternion.prototype.set = function (x, y, z, w) {
  2303. return this.copyFromFloats(x, y, z, w);
  2304. };
  2305. /**
  2306. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2307. */
  2308. Quaternion.prototype.add = function (other) {
  2309. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2310. };
  2311. /**
  2312. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2313. */
  2314. Quaternion.prototype.subtract = function (other) {
  2315. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2316. };
  2317. /**
  2318. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2319. */
  2320. Quaternion.prototype.scale = function (value) {
  2321. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2322. };
  2323. /**
  2324. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2325. */
  2326. Quaternion.prototype.multiply = function (q1) {
  2327. var result = new Quaternion(0, 0, 0, 1.0);
  2328. this.multiplyToRef(q1, result);
  2329. return result;
  2330. };
  2331. /**
  2332. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2333. * Returns the current Quaternion.
  2334. */
  2335. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2336. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2337. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2338. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2339. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2340. result.copyFromFloats(x, y, z, w);
  2341. return this;
  2342. };
  2343. /**
  2344. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2345. * Returns the updated Quaternion.
  2346. */
  2347. Quaternion.prototype.multiplyInPlace = function (q1) {
  2348. this.multiplyToRef(q1, this);
  2349. return this;
  2350. };
  2351. /**
  2352. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2353. * Returns the current Quaternion.
  2354. */
  2355. Quaternion.prototype.conjugateToRef = function (ref) {
  2356. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2357. return this;
  2358. };
  2359. /**
  2360. * Conjugates in place the current Quaternion.
  2361. * Returns the updated Quaternion.
  2362. */
  2363. Quaternion.prototype.conjugateInPlace = function () {
  2364. this.x *= -1;
  2365. this.y *= -1;
  2366. this.z *= -1;
  2367. return this;
  2368. };
  2369. /**
  2370. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugate = function () {
  2373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2374. return result;
  2375. };
  2376. /**
  2377. * Returns the Quaternion length (float).
  2378. */
  2379. Quaternion.prototype.length = function () {
  2380. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2381. };
  2382. /**
  2383. * Normalize in place the current Quaternion.
  2384. * Returns the updated Quaternion.
  2385. */
  2386. Quaternion.prototype.normalize = function () {
  2387. var length = 1.0 / this.length();
  2388. this.x *= length;
  2389. this.y *= length;
  2390. this.z *= length;
  2391. this.w *= length;
  2392. return this;
  2393. };
  2394. /**
  2395. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2396. */
  2397. Quaternion.prototype.toEulerAngles = function (order) {
  2398. if (order === void 0) { order = "YZX"; }
  2399. var result = Vector3.Zero();
  2400. this.toEulerAnglesToRef(result, order);
  2401. return result;
  2402. };
  2403. /**
  2404. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2405. * Returns the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var qz = this.z;
  2410. var qx = this.x;
  2411. var qy = this.y;
  2412. var qw = this.w;
  2413. var sqw = qw * qw;
  2414. var sqz = qz * qz;
  2415. var sqx = qx * qx;
  2416. var sqy = qy * qy;
  2417. var zAxisY = qy * qz - qx * qw;
  2418. var limit = .4999999;
  2419. if (zAxisY < -limit) {
  2420. result.y = 2 * Math.atan2(qy, qw);
  2421. result.x = Math.PI / 2;
  2422. result.z = 0;
  2423. }
  2424. else if (zAxisY > limit) {
  2425. result.y = 2 * Math.atan2(qy, qw);
  2426. result.x = -Math.PI / 2;
  2427. result.z = 0;
  2428. }
  2429. else {
  2430. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2431. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2432. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2433. }
  2434. return this;
  2435. };
  2436. /**
  2437. * Updates the passed rotation matrix with the current Quaternion values.
  2438. * Returns the current Quaternion.
  2439. */
  2440. Quaternion.prototype.toRotationMatrix = function (result) {
  2441. var xx = this.x * this.x;
  2442. var yy = this.y * this.y;
  2443. var zz = this.z * this.z;
  2444. var xy = this.x * this.y;
  2445. var zw = this.z * this.w;
  2446. var zx = this.z * this.x;
  2447. var yw = this.y * this.w;
  2448. var yz = this.y * this.z;
  2449. var xw = this.x * this.w;
  2450. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2451. result.m[1] = 2.0 * (xy + zw);
  2452. result.m[2] = 2.0 * (zx - yw);
  2453. result.m[3] = 0;
  2454. result.m[4] = 2.0 * (xy - zw);
  2455. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2456. result.m[6] = 2.0 * (yz + xw);
  2457. result.m[7] = 0;
  2458. result.m[8] = 2.0 * (zx + yw);
  2459. result.m[9] = 2.0 * (yz - xw);
  2460. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2461. result.m[11] = 0;
  2462. result.m[12] = 0;
  2463. result.m[13] = 0;
  2464. result.m[14] = 0;
  2465. result.m[15] = 1.0;
  2466. result._markAsUpdated();
  2467. return this;
  2468. };
  2469. /**
  2470. * Updates the current Quaternion from the passed rotation matrix values.
  2471. * Returns the updated Quaternion.
  2472. */
  2473. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2474. Quaternion.FromRotationMatrixToRef(matrix, this);
  2475. return this;
  2476. };
  2477. // Statics
  2478. /**
  2479. * Returns a new Quaternion set from the passed rotation matrix values.
  2480. */
  2481. Quaternion.FromRotationMatrix = function (matrix) {
  2482. var result = new Quaternion();
  2483. Quaternion.FromRotationMatrixToRef(matrix, result);
  2484. return result;
  2485. };
  2486. /**
  2487. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2488. */
  2489. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2490. var data = matrix.m;
  2491. var m11 = data[0], m12 = data[4], m13 = data[8];
  2492. var m21 = data[1], m22 = data[5], m23 = data[9];
  2493. var m31 = data[2], m32 = data[6], m33 = data[10];
  2494. var trace = m11 + m22 + m33;
  2495. var s;
  2496. if (trace > 0) {
  2497. s = 0.5 / Math.sqrt(trace + 1.0);
  2498. result.w = 0.25 / s;
  2499. result.x = (m32 - m23) * s;
  2500. result.y = (m13 - m31) * s;
  2501. result.z = (m21 - m12) * s;
  2502. }
  2503. else if (m11 > m22 && m11 > m33) {
  2504. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2505. result.w = (m32 - m23) / s;
  2506. result.x = 0.25 * s;
  2507. result.y = (m12 + m21) / s;
  2508. result.z = (m13 + m31) / s;
  2509. }
  2510. else if (m22 > m33) {
  2511. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2512. result.w = (m13 - m31) / s;
  2513. result.x = (m12 + m21) / s;
  2514. result.y = 0.25 * s;
  2515. result.z = (m23 + m32) / s;
  2516. }
  2517. else {
  2518. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2519. result.w = (m21 - m12) / s;
  2520. result.x = (m13 + m31) / s;
  2521. result.y = (m23 + m32) / s;
  2522. result.z = 0.25 * s;
  2523. }
  2524. };
  2525. /**
  2526. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2527. */
  2528. Quaternion.Zero = function () {
  2529. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2530. };
  2531. /**
  2532. * Returns a new Quaternion as the inverted current Quaternion.
  2533. */
  2534. Quaternion.Inverse = function (q) {
  2535. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2536. };
  2537. /**
  2538. * Returns the identity Quaternion.
  2539. */
  2540. Quaternion.Identity = function () {
  2541. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2542. };
  2543. Quaternion.IsIdentity = function (quaternion) {
  2544. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2545. };
  2546. /**
  2547. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2548. */
  2549. Quaternion.RotationAxis = function (axis, angle) {
  2550. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2551. };
  2552. /**
  2553. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2554. */
  2555. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2556. var sin = Math.sin(angle / 2);
  2557. axis.normalize();
  2558. result.w = Math.cos(angle / 2);
  2559. result.x = axis.x * sin;
  2560. result.y = axis.y * sin;
  2561. result.z = axis.z * sin;
  2562. return result;
  2563. };
  2564. /**
  2565. * Retuns a new Quaternion set from the starting index of the passed array.
  2566. */
  2567. Quaternion.FromArray = function (array, offset) {
  2568. if (!offset) {
  2569. offset = 0;
  2570. }
  2571. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2572. };
  2573. /**
  2574. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2575. */
  2576. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2577. var q = new Quaternion();
  2578. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2579. return q;
  2580. };
  2581. /**
  2582. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2583. */
  2584. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2585. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2586. var halfRoll = roll * 0.5;
  2587. var halfPitch = pitch * 0.5;
  2588. var halfYaw = yaw * 0.5;
  2589. var sinRoll = Math.sin(halfRoll);
  2590. var cosRoll = Math.cos(halfRoll);
  2591. var sinPitch = Math.sin(halfPitch);
  2592. var cosPitch = Math.cos(halfPitch);
  2593. var sinYaw = Math.sin(halfYaw);
  2594. var cosYaw = Math.cos(halfYaw);
  2595. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2596. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2597. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2598. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2599. };
  2600. /**
  2601. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2602. */
  2603. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2604. var result = new Quaternion();
  2605. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2606. return result;
  2607. };
  2608. /**
  2609. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2610. */
  2611. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2612. // Produces a quaternion from Euler angles in the z-x-z orientation
  2613. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2614. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2615. var halfBeta = beta * 0.5;
  2616. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2617. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2618. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2619. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2620. };
  2621. /**
  2622. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2623. * cf to Vector3.RotationFromAxis() documentation.
  2624. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2625. */
  2626. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2627. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2628. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2629. return quat;
  2630. };
  2631. /**
  2632. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2637. var rotMat = MathTmp.Matrix[0];
  2638. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2639. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2640. };
  2641. Quaternion.Slerp = function (left, right, amount) {
  2642. var result = Quaternion.Identity();
  2643. Quaternion.SlerpToRef(left, right, amount, result);
  2644. return result;
  2645. };
  2646. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2647. var num2;
  2648. var num3;
  2649. var num = amount;
  2650. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2651. var flag = false;
  2652. if (num4 < 0) {
  2653. flag = true;
  2654. num4 = -num4;
  2655. }
  2656. if (num4 > 0.999999) {
  2657. num3 = 1 - num;
  2658. num2 = flag ? -num : num;
  2659. }
  2660. else {
  2661. var num5 = Math.acos(num4);
  2662. var num6 = (1.0 / Math.sin(num5));
  2663. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2664. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2665. }
  2666. result.x = (num3 * left.x) + (num2 * right.x);
  2667. result.y = (num3 * left.y) + (num2 * right.y);
  2668. result.z = (num3 * left.z) + (num2 * right.z);
  2669. result.w = (num3 * left.w) + (num2 * right.w);
  2670. };
  2671. return Quaternion;
  2672. }());
  2673. BABYLON.Quaternion = Quaternion;
  2674. var Matrix = (function () {
  2675. function Matrix() {
  2676. this.m = new Float32Array(16);
  2677. this._markAsUpdated();
  2678. }
  2679. Matrix.prototype._markAsUpdated = function () {
  2680. this.updateFlag = Matrix._updateFlagSeed++;
  2681. };
  2682. // Properties
  2683. /**
  2684. * Boolean : True is the matrix is the identity matrix
  2685. */
  2686. Matrix.prototype.isIdentity = function () {
  2687. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2688. return false;
  2689. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2690. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2691. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2692. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2693. return false;
  2694. return true;
  2695. };
  2696. /**
  2697. * Returns the matrix determinant (float).
  2698. */
  2699. Matrix.prototype.determinant = function () {
  2700. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2701. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2702. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2703. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2704. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2705. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2706. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2707. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2708. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2709. };
  2710. // Methods
  2711. /**
  2712. * Returns the matrix underlying array.
  2713. */
  2714. Matrix.prototype.toArray = function () {
  2715. return this.m;
  2716. };
  2717. /**
  2718. * Returns the matrix underlying array.
  2719. */
  2720. Matrix.prototype.asArray = function () {
  2721. return this.toArray();
  2722. };
  2723. /**
  2724. * Inverts in place the Matrix.
  2725. * Returns the Matrix inverted.
  2726. */
  2727. Matrix.prototype.invert = function () {
  2728. this.invertToRef(this);
  2729. return this;
  2730. };
  2731. /**
  2732. * Sets all the matrix elements to zero.
  2733. * Returns the Matrix.
  2734. */
  2735. Matrix.prototype.reset = function () {
  2736. for (var index = 0; index < 16; index++) {
  2737. this.m[index] = 0.0;
  2738. }
  2739. this._markAsUpdated();
  2740. return this;
  2741. };
  2742. /**
  2743. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2744. */
  2745. Matrix.prototype.add = function (other) {
  2746. var result = new Matrix();
  2747. this.addToRef(other, result);
  2748. return result;
  2749. };
  2750. /**
  2751. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2752. * Returns the Matrix.
  2753. */
  2754. Matrix.prototype.addToRef = function (other, result) {
  2755. for (var index = 0; index < 16; index++) {
  2756. result.m[index] = this.m[index] + other.m[index];
  2757. }
  2758. result._markAsUpdated();
  2759. return this;
  2760. };
  2761. /**
  2762. * Adds in place the passed matrix to the current Matrix.
  2763. * Returns the updated Matrix.
  2764. */
  2765. Matrix.prototype.addToSelf = function (other) {
  2766. for (var index = 0; index < 16; index++) {
  2767. this.m[index] += other.m[index];
  2768. }
  2769. this._markAsUpdated();
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets the passed matrix with the current inverted Matrix.
  2774. * Returns the unmodified current Matrix.
  2775. */
  2776. Matrix.prototype.invertToRef = function (other) {
  2777. var l1 = this.m[0];
  2778. var l2 = this.m[1];
  2779. var l3 = this.m[2];
  2780. var l4 = this.m[3];
  2781. var l5 = this.m[4];
  2782. var l6 = this.m[5];
  2783. var l7 = this.m[6];
  2784. var l8 = this.m[7];
  2785. var l9 = this.m[8];
  2786. var l10 = this.m[9];
  2787. var l11 = this.m[10];
  2788. var l12 = this.m[11];
  2789. var l13 = this.m[12];
  2790. var l14 = this.m[13];
  2791. var l15 = this.m[14];
  2792. var l16 = this.m[15];
  2793. var l17 = (l11 * l16) - (l12 * l15);
  2794. var l18 = (l10 * l16) - (l12 * l14);
  2795. var l19 = (l10 * l15) - (l11 * l14);
  2796. var l20 = (l9 * l16) - (l12 * l13);
  2797. var l21 = (l9 * l15) - (l11 * l13);
  2798. var l22 = (l9 * l14) - (l10 * l13);
  2799. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2800. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2801. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2802. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2803. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2804. var l28 = (l7 * l16) - (l8 * l15);
  2805. var l29 = (l6 * l16) - (l8 * l14);
  2806. var l30 = (l6 * l15) - (l7 * l14);
  2807. var l31 = (l5 * l16) - (l8 * l13);
  2808. var l32 = (l5 * l15) - (l7 * l13);
  2809. var l33 = (l5 * l14) - (l6 * l13);
  2810. var l34 = (l7 * l12) - (l8 * l11);
  2811. var l35 = (l6 * l12) - (l8 * l10);
  2812. var l36 = (l6 * l11) - (l7 * l10);
  2813. var l37 = (l5 * l12) - (l8 * l9);
  2814. var l38 = (l5 * l11) - (l7 * l9);
  2815. var l39 = (l5 * l10) - (l6 * l9);
  2816. other.m[0] = l23 * l27;
  2817. other.m[4] = l24 * l27;
  2818. other.m[8] = l25 * l27;
  2819. other.m[12] = l26 * l27;
  2820. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2821. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2822. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2823. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2824. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2825. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2826. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2827. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2828. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2829. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2830. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2831. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2832. other._markAsUpdated();
  2833. return this;
  2834. };
  2835. /**
  2836. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2837. * Returns the updated Matrix.
  2838. */
  2839. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2840. this.m[12] = x;
  2841. this.m[13] = y;
  2842. this.m[14] = z;
  2843. this._markAsUpdated();
  2844. return this;
  2845. };
  2846. /**
  2847. * Inserts the translation vector in the current Matrix.
  2848. * Returns the updated Matrix.
  2849. */
  2850. Matrix.prototype.setTranslation = function (vector3) {
  2851. this.m[12] = vector3.x;
  2852. this.m[13] = vector3.y;
  2853. this.m[14] = vector3.z;
  2854. this._markAsUpdated();
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 as the extracted translation from the Matrix.
  2859. */
  2860. Matrix.prototype.getTranslation = function () {
  2861. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2862. };
  2863. /**
  2864. * Fill a Vector3 with the extracted translation from the Matrix.
  2865. */
  2866. Matrix.prototype.getTranslationToRef = function (result) {
  2867. result.x = this.m[12];
  2868. result.y = this.m[13];
  2869. result.z = this.m[14];
  2870. return this;
  2871. };
  2872. /**
  2873. * Remove rotation and scaling part from the Matrix.
  2874. * Returns the updated Matrix.
  2875. */
  2876. Matrix.prototype.removeRotationAndScaling = function () {
  2877. this.setRowFromFloats(0, 1, 0, 0, 0);
  2878. this.setRowFromFloats(1, 0, 1, 0, 0);
  2879. this.setRowFromFloats(2, 0, 0, 1, 0);
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2884. */
  2885. Matrix.prototype.multiply = function (other) {
  2886. var result = new Matrix();
  2887. this.multiplyToRef(other, result);
  2888. return result;
  2889. };
  2890. /**
  2891. * Updates the current Matrix from the passed one values.
  2892. * Returns the updated Matrix.
  2893. */
  2894. Matrix.prototype.copyFrom = function (other) {
  2895. for (var index = 0; index < 16; index++) {
  2896. this.m[index] = other.m[index];
  2897. }
  2898. this._markAsUpdated();
  2899. return this;
  2900. };
  2901. /**
  2902. * Populates the passed array from the starting index with the Matrix values.
  2903. * Returns the Matrix.
  2904. */
  2905. Matrix.prototype.copyToArray = function (array, offset) {
  2906. if (offset === void 0) { offset = 0; }
  2907. for (var index = 0; index < 16; index++) {
  2908. array[offset + index] = this.m[index];
  2909. }
  2910. return this;
  2911. };
  2912. /**
  2913. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2914. */
  2915. Matrix.prototype.multiplyToRef = function (other, result) {
  2916. this.multiplyToArray(other, result.m, 0);
  2917. result._markAsUpdated();
  2918. return this;
  2919. };
  2920. /**
  2921. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2922. */
  2923. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2924. var tm0 = this.m[0];
  2925. var tm1 = this.m[1];
  2926. var tm2 = this.m[2];
  2927. var tm3 = this.m[3];
  2928. var tm4 = this.m[4];
  2929. var tm5 = this.m[5];
  2930. var tm6 = this.m[6];
  2931. var tm7 = this.m[7];
  2932. var tm8 = this.m[8];
  2933. var tm9 = this.m[9];
  2934. var tm10 = this.m[10];
  2935. var tm11 = this.m[11];
  2936. var tm12 = this.m[12];
  2937. var tm13 = this.m[13];
  2938. var tm14 = this.m[14];
  2939. var tm15 = this.m[15];
  2940. var om0 = other.m[0];
  2941. var om1 = other.m[1];
  2942. var om2 = other.m[2];
  2943. var om3 = other.m[3];
  2944. var om4 = other.m[4];
  2945. var om5 = other.m[5];
  2946. var om6 = other.m[6];
  2947. var om7 = other.m[7];
  2948. var om8 = other.m[8];
  2949. var om9 = other.m[9];
  2950. var om10 = other.m[10];
  2951. var om11 = other.m[11];
  2952. var om12 = other.m[12];
  2953. var om13 = other.m[13];
  2954. var om14 = other.m[14];
  2955. var om15 = other.m[15];
  2956. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2957. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2958. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2959. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2960. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2961. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2962. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2963. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2964. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2965. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2966. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2967. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2968. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2969. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2970. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2971. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2972. return this;
  2973. };
  2974. /**
  2975. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2976. */
  2977. Matrix.prototype.equals = function (value) {
  2978. return value &&
  2979. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2980. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2981. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2982. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2983. };
  2984. /**
  2985. * Returns a new Matrix from the current Matrix.
  2986. */
  2987. Matrix.prototype.clone = function () {
  2988. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  2989. };
  2990. /**
  2991. * Returns the string "Matrix"
  2992. */
  2993. Matrix.prototype.getClassName = function () {
  2994. return "Matrix";
  2995. };
  2996. /**
  2997. * Returns the Matrix hash code.
  2998. */
  2999. Matrix.prototype.getHashCode = function () {
  3000. var hash = this.m[0] || 0;
  3001. for (var i = 1; i < 16; i++) {
  3002. hash = (hash * 397) ^ (this.m[i] || 0);
  3003. }
  3004. return hash;
  3005. };
  3006. /**
  3007. * Decomposes the current Matrix into :
  3008. * - a scale vector3 passed as a reference to update,
  3009. * - a rotation quaternion passed as a reference to update,
  3010. * - a translation vector3 passed as a reference to update.
  3011. * Returns the boolean `true`.
  3012. */
  3013. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3014. translation.x = this.m[12];
  3015. translation.y = this.m[13];
  3016. translation.z = this.m[14];
  3017. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3018. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3019. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3020. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3021. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3022. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3023. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3024. rotation.x = 0;
  3025. rotation.y = 0;
  3026. rotation.z = 0;
  3027. rotation.w = 1;
  3028. return false;
  3029. }
  3030. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3031. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3032. return true;
  3033. };
  3034. /**
  3035. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3036. */
  3037. Matrix.prototype.getRotationMatrix = function () {
  3038. var result = Matrix.Identity();
  3039. this.getRotationMatrixToRef(result);
  3040. return result;
  3041. };
  3042. /**
  3043. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3044. * Returns the current Matrix.
  3045. */
  3046. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3047. var m = this.m;
  3048. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3049. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3050. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3051. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3052. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3053. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3054. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3055. return this;
  3056. };
  3057. // Statics
  3058. /**
  3059. * Returns a new Matrix set from the starting index of the passed array.
  3060. */
  3061. Matrix.FromArray = function (array, offset) {
  3062. var result = new Matrix();
  3063. if (!offset) {
  3064. offset = 0;
  3065. }
  3066. Matrix.FromArrayToRef(array, offset, result);
  3067. return result;
  3068. };
  3069. /**
  3070. * Sets the passed "result" matrix from the starting index of the passed array.
  3071. */
  3072. Matrix.FromArrayToRef = function (array, offset, result) {
  3073. for (var index = 0; index < 16; index++) {
  3074. result.m[index] = array[index + offset];
  3075. }
  3076. result._markAsUpdated();
  3077. };
  3078. /**
  3079. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3080. */
  3081. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3082. for (var index = 0; index < 16; index++) {
  3083. result.m[index] = array[index + offset] * scale;
  3084. }
  3085. result._markAsUpdated();
  3086. };
  3087. /**
  3088. * Sets the passed matrix "result" with the 16 passed floats.
  3089. */
  3090. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3091. result.m[0] = initialM11;
  3092. result.m[1] = initialM12;
  3093. result.m[2] = initialM13;
  3094. result.m[3] = initialM14;
  3095. result.m[4] = initialM21;
  3096. result.m[5] = initialM22;
  3097. result.m[6] = initialM23;
  3098. result.m[7] = initialM24;
  3099. result.m[8] = initialM31;
  3100. result.m[9] = initialM32;
  3101. result.m[10] = initialM33;
  3102. result.m[11] = initialM34;
  3103. result.m[12] = initialM41;
  3104. result.m[13] = initialM42;
  3105. result.m[14] = initialM43;
  3106. result.m[15] = initialM44;
  3107. result._markAsUpdated();
  3108. };
  3109. /**
  3110. * Returns the index-th row of the current matrix as a new Vector4.
  3111. */
  3112. Matrix.prototype.getRow = function (index) {
  3113. if (index < 0 || index > 3) {
  3114. return null;
  3115. }
  3116. var i = index * 4;
  3117. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3118. };
  3119. /**
  3120. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3121. * Returns the updated Matrix.
  3122. */
  3123. Matrix.prototype.setRow = function (index, row) {
  3124. if (index < 0 || index > 3) {
  3125. return this;
  3126. }
  3127. var i = index * 4;
  3128. this.m[i + 0] = row.x;
  3129. this.m[i + 1] = row.y;
  3130. this.m[i + 2] = row.z;
  3131. this.m[i + 3] = row.w;
  3132. this._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3137. * Returns the updated Matrix.
  3138. */
  3139. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3140. if (index < 0 || index > 3) {
  3141. return this;
  3142. }
  3143. var i = index * 4;
  3144. this.m[i + 0] = x;
  3145. this.m[i + 1] = y;
  3146. this.m[i + 2] = z;
  3147. this.m[i + 3] = w;
  3148. this._markAsUpdated();
  3149. return this;
  3150. };
  3151. /**
  3152. * Returns a new Matrix set from the 16 passed floats.
  3153. */
  3154. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3155. var result = new Matrix();
  3156. result.m[0] = initialM11;
  3157. result.m[1] = initialM12;
  3158. result.m[2] = initialM13;
  3159. result.m[3] = initialM14;
  3160. result.m[4] = initialM21;
  3161. result.m[5] = initialM22;
  3162. result.m[6] = initialM23;
  3163. result.m[7] = initialM24;
  3164. result.m[8] = initialM31;
  3165. result.m[9] = initialM32;
  3166. result.m[10] = initialM33;
  3167. result.m[11] = initialM34;
  3168. result.m[12] = initialM41;
  3169. result.m[13] = initialM42;
  3170. result.m[14] = initialM43;
  3171. result.m[15] = initialM44;
  3172. return result;
  3173. };
  3174. /**
  3175. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3176. */
  3177. Matrix.Compose = function (scale, rotation, translation) {
  3178. var result = Matrix.Identity();
  3179. Matrix.ComposeToRef(scale, rotation, translation, result);
  3180. return result;
  3181. };
  3182. /**
  3183. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3184. */
  3185. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3186. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3187. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3188. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3189. result.setTranslation(translation);
  3190. };
  3191. /**
  3192. * Returns a new indentity Matrix.
  3193. */
  3194. Matrix.Identity = function () {
  3195. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3196. };
  3197. /**
  3198. * Sets the passed "result" as an identity matrix.
  3199. */
  3200. Matrix.IdentityToRef = function (result) {
  3201. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3202. };
  3203. /**
  3204. * Returns a new zero Matrix.
  3205. */
  3206. Matrix.Zero = function () {
  3207. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new rotation matrix for "angle" radians around the X axis.
  3211. */
  3212. Matrix.RotationX = function (angle) {
  3213. var result = new Matrix();
  3214. Matrix.RotationXToRef(angle, result);
  3215. return result;
  3216. };
  3217. /**
  3218. * Returns a new Matrix as the passed inverted one.
  3219. */
  3220. Matrix.Invert = function (source) {
  3221. var result = new Matrix();
  3222. source.invertToRef(result);
  3223. return result;
  3224. };
  3225. /**
  3226. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3227. */
  3228. Matrix.RotationXToRef = function (angle, result) {
  3229. var s = Math.sin(angle);
  3230. var c = Math.cos(angle);
  3231. result.m[0] = 1.0;
  3232. result.m[15] = 1.0;
  3233. result.m[5] = c;
  3234. result.m[10] = c;
  3235. result.m[9] = -s;
  3236. result.m[6] = s;
  3237. result.m[1] = 0.0;
  3238. result.m[2] = 0.0;
  3239. result.m[3] = 0.0;
  3240. result.m[4] = 0.0;
  3241. result.m[7] = 0.0;
  3242. result.m[8] = 0.0;
  3243. result.m[11] = 0.0;
  3244. result.m[12] = 0.0;
  3245. result.m[13] = 0.0;
  3246. result.m[14] = 0.0;
  3247. result._markAsUpdated();
  3248. };
  3249. /**
  3250. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3251. */
  3252. Matrix.RotationY = function (angle) {
  3253. var result = new Matrix();
  3254. Matrix.RotationYToRef(angle, result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3259. */
  3260. Matrix.RotationYToRef = function (angle, result) {
  3261. var s = Math.sin(angle);
  3262. var c = Math.cos(angle);
  3263. result.m[5] = 1.0;
  3264. result.m[15] = 1.0;
  3265. result.m[0] = c;
  3266. result.m[2] = -s;
  3267. result.m[8] = s;
  3268. result.m[10] = c;
  3269. result.m[1] = 0.0;
  3270. result.m[3] = 0.0;
  3271. result.m[4] = 0.0;
  3272. result.m[6] = 0.0;
  3273. result.m[7] = 0.0;
  3274. result.m[9] = 0.0;
  3275. result.m[11] = 0.0;
  3276. result.m[12] = 0.0;
  3277. result.m[13] = 0.0;
  3278. result.m[14] = 0.0;
  3279. result._markAsUpdated();
  3280. };
  3281. /**
  3282. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3283. */
  3284. Matrix.RotationZ = function (angle) {
  3285. var result = new Matrix();
  3286. Matrix.RotationZToRef(angle, result);
  3287. return result;
  3288. };
  3289. /**
  3290. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3291. */
  3292. Matrix.RotationZToRef = function (angle, result) {
  3293. var s = Math.sin(angle);
  3294. var c = Math.cos(angle);
  3295. result.m[10] = 1.0;
  3296. result.m[15] = 1.0;
  3297. result.m[0] = c;
  3298. result.m[1] = s;
  3299. result.m[4] = -s;
  3300. result.m[5] = c;
  3301. result.m[2] = 0.0;
  3302. result.m[3] = 0.0;
  3303. result.m[6] = 0.0;
  3304. result.m[7] = 0.0;
  3305. result.m[8] = 0.0;
  3306. result.m[9] = 0.0;
  3307. result.m[11] = 0.0;
  3308. result.m[12] = 0.0;
  3309. result.m[13] = 0.0;
  3310. result.m[14] = 0.0;
  3311. result._markAsUpdated();
  3312. };
  3313. /**
  3314. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3315. */
  3316. Matrix.RotationAxis = function (axis, angle) {
  3317. var result = Matrix.Zero();
  3318. Matrix.RotationAxisToRef(axis, angle, result);
  3319. return result;
  3320. };
  3321. /**
  3322. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3323. */
  3324. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3325. var s = Math.sin(-angle);
  3326. var c = Math.cos(-angle);
  3327. var c1 = 1 - c;
  3328. axis.normalize();
  3329. result.m[0] = (axis.x * axis.x) * c1 + c;
  3330. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3331. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3332. result.m[3] = 0.0;
  3333. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3334. result.m[5] = (axis.y * axis.y) * c1 + c;
  3335. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3336. result.m[7] = 0.0;
  3337. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3338. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3339. result.m[10] = (axis.z * axis.z) * c1 + c;
  3340. result.m[11] = 0.0;
  3341. result.m[15] = 1.0;
  3342. result._markAsUpdated();
  3343. };
  3344. /**
  3345. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3346. */
  3347. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3348. var result = new Matrix();
  3349. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3350. return result;
  3351. };
  3352. /**
  3353. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3354. */
  3355. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3356. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3357. this._tempQuaternion.toRotationMatrix(result);
  3358. };
  3359. /**
  3360. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3361. */
  3362. Matrix.Scaling = function (x, y, z) {
  3363. var result = Matrix.Zero();
  3364. Matrix.ScalingToRef(x, y, z, result);
  3365. return result;
  3366. };
  3367. /**
  3368. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3369. */
  3370. Matrix.ScalingToRef = function (x, y, z, result) {
  3371. result.m[0] = x;
  3372. result.m[1] = 0.0;
  3373. result.m[2] = 0.0;
  3374. result.m[3] = 0.0;
  3375. result.m[4] = 0.0;
  3376. result.m[5] = y;
  3377. result.m[6] = 0.0;
  3378. result.m[7] = 0.0;
  3379. result.m[8] = 0.0;
  3380. result.m[9] = 0.0;
  3381. result.m[10] = z;
  3382. result.m[11] = 0.0;
  3383. result.m[12] = 0.0;
  3384. result.m[13] = 0.0;
  3385. result.m[14] = 0.0;
  3386. result.m[15] = 1.0;
  3387. result._markAsUpdated();
  3388. };
  3389. /**
  3390. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3391. */
  3392. Matrix.Translation = function (x, y, z) {
  3393. var result = Matrix.Identity();
  3394. Matrix.TranslationToRef(x, y, z, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3399. */
  3400. Matrix.TranslationToRef = function (x, y, z, result) {
  3401. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3402. };
  3403. /**
  3404. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3405. */
  3406. Matrix.Lerp = function (startValue, endValue, gradient) {
  3407. var result = Matrix.Zero();
  3408. for (var index = 0; index < 16; index++) {
  3409. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3410. }
  3411. result._markAsUpdated();
  3412. return result;
  3413. };
  3414. /**
  3415. * Returns a new Matrix whose values are computed by :
  3416. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3417. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3418. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3419. */
  3420. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3421. var startScale = new Vector3(0, 0, 0);
  3422. var startRotation = new Quaternion();
  3423. var startTranslation = new Vector3(0, 0, 0);
  3424. startValue.decompose(startScale, startRotation, startTranslation);
  3425. var endScale = new Vector3(0, 0, 0);
  3426. var endRotation = new Quaternion();
  3427. var endTranslation = new Vector3(0, 0, 0);
  3428. endValue.decompose(endScale, endRotation, endTranslation);
  3429. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3430. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3431. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3432. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3433. };
  3434. /**
  3435. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3436. * This methods works for a Left-Handed system.
  3437. */
  3438. Matrix.LookAtLH = function (eye, target, up) {
  3439. var result = Matrix.Zero();
  3440. Matrix.LookAtLHToRef(eye, target, up, result);
  3441. return result;
  3442. };
  3443. /**
  3444. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3445. * This methods works for a Left-Handed system.
  3446. */
  3447. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3448. // Z axis
  3449. target.subtractToRef(eye, this._zAxis);
  3450. this._zAxis.normalize();
  3451. // X axis
  3452. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3453. if (this._xAxis.lengthSquared() === 0) {
  3454. this._xAxis.x = 1.0;
  3455. }
  3456. else {
  3457. this._xAxis.normalize();
  3458. }
  3459. // Y axis
  3460. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3461. this._yAxis.normalize();
  3462. // Eye angles
  3463. var ex = -Vector3.Dot(this._xAxis, eye);
  3464. var ey = -Vector3.Dot(this._yAxis, eye);
  3465. var ez = -Vector3.Dot(this._zAxis, eye);
  3466. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3467. };
  3468. /**
  3469. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3470. * This methods works for a Right-Handed system.
  3471. */
  3472. Matrix.LookAtRH = function (eye, target, up) {
  3473. var result = Matrix.Zero();
  3474. Matrix.LookAtRHToRef(eye, target, up, result);
  3475. return result;
  3476. };
  3477. /**
  3478. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3479. * This methods works for a Left-Handed system.
  3480. */
  3481. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3482. // Z axis
  3483. eye.subtractToRef(target, this._zAxis);
  3484. this._zAxis.normalize();
  3485. // X axis
  3486. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3487. if (this._xAxis.lengthSquared() === 0) {
  3488. this._xAxis.x = 1.0;
  3489. }
  3490. else {
  3491. this._xAxis.normalize();
  3492. }
  3493. // Y axis
  3494. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3495. this._yAxis.normalize();
  3496. // Eye angles
  3497. var ex = -Vector3.Dot(this._xAxis, eye);
  3498. var ey = -Vector3.Dot(this._yAxis, eye);
  3499. var ez = -Vector3.Dot(this._zAxis, eye);
  3500. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3501. };
  3502. /**
  3503. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3504. */
  3505. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3506. var matrix = Matrix.Zero();
  3507. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3508. return matrix;
  3509. };
  3510. /**
  3511. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3512. */
  3513. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3514. var n = znear;
  3515. var f = zfar;
  3516. var a = 2.0 / width;
  3517. var b = 2.0 / height;
  3518. var c = 2.0 / (f - n);
  3519. var d = -(f + n) / (f - n);
  3520. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3521. };
  3522. /**
  3523. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3524. */
  3525. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3526. var matrix = Matrix.Zero();
  3527. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3528. return matrix;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3532. */
  3533. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3534. var n = znear;
  3535. var f = zfar;
  3536. var a = 2.0 / (right - left);
  3537. var b = 2.0 / (top - bottom);
  3538. var c = 2.0 / (f - n);
  3539. var d = -(f + n) / (f - n);
  3540. var i0 = (left + right) / (left - right);
  3541. var i1 = (top + bottom) / (bottom - top);
  3542. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3543. };
  3544. /**
  3545. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3546. */
  3547. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3548. var matrix = Matrix.Zero();
  3549. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3550. return matrix;
  3551. };
  3552. /**
  3553. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3554. */
  3555. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3556. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3557. result.m[10] *= -1.0;
  3558. };
  3559. /**
  3560. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3561. */
  3562. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3563. var matrix = Matrix.Zero();
  3564. var n = znear;
  3565. var f = zfar;
  3566. var a = 2.0 * n / width;
  3567. var b = 2.0 * n / height;
  3568. var c = (f + n) / (f - n);
  3569. var d = -2.0 * f * n / (f - n);
  3570. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3571. return matrix;
  3572. };
  3573. /**
  3574. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3575. */
  3576. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3583. */
  3584. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3585. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3586. var n = znear;
  3587. var f = zfar;
  3588. var t = 1.0 / (Math.tan(fov * 0.5));
  3589. var a = isVerticalFovFixed ? (t / aspect) : t;
  3590. var b = isVerticalFovFixed ? t : (t * aspect);
  3591. var c = (f + n) / (f - n);
  3592. var d = -2.0 * f * n / (f - n);
  3593. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3597. */
  3598. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3605. */
  3606. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3607. //alternatively this could be expressed as:
  3608. // m = PerspectiveFovLHToRef
  3609. // m[10] *= -1.0;
  3610. // m[11] *= -1.0;
  3611. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3612. var n = znear;
  3613. var f = zfar;
  3614. var t = 1.0 / (Math.tan(fov * 0.5));
  3615. var a = isVerticalFovFixed ? (t / aspect) : t;
  3616. var b = isVerticalFovFixed ? t : (t * aspect);
  3617. var c = -(f + n) / (f - n);
  3618. var d = -2 * f * n / (f - n);
  3619. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3620. };
  3621. /**
  3622. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3623. */
  3624. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3625. if (rightHanded === void 0) { rightHanded = false; }
  3626. var rightHandedFactor = rightHanded ? -1 : 1;
  3627. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3628. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3629. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3630. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3631. var xScale = 2.0 / (leftTan + rightTan);
  3632. var yScale = 2.0 / (upTan + downTan);
  3633. result.m[0] = xScale;
  3634. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3635. result.m[5] = yScale;
  3636. result.m[6] = result.m[7] = 0.0;
  3637. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3638. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3639. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3640. result.m[10] = -zfar / (znear - zfar);
  3641. result.m[11] = 1.0 * rightHandedFactor;
  3642. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3643. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3644. // result.m[14] = (znear * zfar) / (znear - zfar);
  3645. result._markAsUpdated();
  3646. };
  3647. /**
  3648. * Returns the final transformation matrix : world * view * projection * viewport
  3649. */
  3650. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3651. var cw = viewport.width;
  3652. var ch = viewport.height;
  3653. var cx = viewport.x;
  3654. var cy = viewport.y;
  3655. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3656. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3657. };
  3658. /**
  3659. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3660. */
  3661. Matrix.GetAsMatrix2x2 = function (matrix) {
  3662. return new Float32Array([
  3663. matrix.m[0], matrix.m[1],
  3664. matrix.m[4], matrix.m[5]
  3665. ]);
  3666. };
  3667. /**
  3668. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3669. */
  3670. Matrix.GetAsMatrix3x3 = function (matrix) {
  3671. return new Float32Array([
  3672. matrix.m[0], matrix.m[1], matrix.m[2],
  3673. matrix.m[4], matrix.m[5], matrix.m[6],
  3674. matrix.m[8], matrix.m[9], matrix.m[10]
  3675. ]);
  3676. };
  3677. /**
  3678. * Compute the transpose of the passed Matrix.
  3679. * Returns a new Matrix.
  3680. */
  3681. Matrix.Transpose = function (matrix) {
  3682. var result = new Matrix();
  3683. result.m[0] = matrix.m[0];
  3684. result.m[1] = matrix.m[4];
  3685. result.m[2] = matrix.m[8];
  3686. result.m[3] = matrix.m[12];
  3687. result.m[4] = matrix.m[1];
  3688. result.m[5] = matrix.m[5];
  3689. result.m[6] = matrix.m[9];
  3690. result.m[7] = matrix.m[13];
  3691. result.m[8] = matrix.m[2];
  3692. result.m[9] = matrix.m[6];
  3693. result.m[10] = matrix.m[10];
  3694. result.m[11] = matrix.m[14];
  3695. result.m[12] = matrix.m[3];
  3696. result.m[13] = matrix.m[7];
  3697. result.m[14] = matrix.m[11];
  3698. result.m[15] = matrix.m[15];
  3699. return result;
  3700. };
  3701. /**
  3702. * Returns a new Matrix as the reflection matrix across the passed plane.
  3703. */
  3704. Matrix.Reflection = function (plane) {
  3705. var matrix = new Matrix();
  3706. Matrix.ReflectionToRef(plane, matrix);
  3707. return matrix;
  3708. };
  3709. /**
  3710. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3711. */
  3712. Matrix.ReflectionToRef = function (plane, result) {
  3713. plane.normalize();
  3714. var x = plane.normal.x;
  3715. var y = plane.normal.y;
  3716. var z = plane.normal.z;
  3717. var temp = -2 * x;
  3718. var temp2 = -2 * y;
  3719. var temp3 = -2 * z;
  3720. result.m[0] = (temp * x) + 1;
  3721. result.m[1] = temp2 * x;
  3722. result.m[2] = temp3 * x;
  3723. result.m[3] = 0.0;
  3724. result.m[4] = temp * y;
  3725. result.m[5] = (temp2 * y) + 1;
  3726. result.m[6] = temp3 * y;
  3727. result.m[7] = 0.0;
  3728. result.m[8] = temp * z;
  3729. result.m[9] = temp2 * z;
  3730. result.m[10] = (temp3 * z) + 1;
  3731. result.m[11] = 0.0;
  3732. result.m[12] = temp * plane.d;
  3733. result.m[13] = temp2 * plane.d;
  3734. result.m[14] = temp3 * plane.d;
  3735. result.m[15] = 1.0;
  3736. result._markAsUpdated();
  3737. };
  3738. /**
  3739. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3740. */
  3741. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3742. result.m[0] = xaxis.x;
  3743. result.m[1] = xaxis.y;
  3744. result.m[2] = xaxis.z;
  3745. result.m[3] = 0.0;
  3746. result.m[4] = yaxis.x;
  3747. result.m[5] = yaxis.y;
  3748. result.m[6] = yaxis.z;
  3749. result.m[7] = 0.0;
  3750. result.m[8] = zaxis.x;
  3751. result.m[9] = zaxis.y;
  3752. result.m[10] = zaxis.z;
  3753. result.m[11] = 0.0;
  3754. result.m[12] = 0.0;
  3755. result.m[13] = 0.0;
  3756. result.m[14] = 0.0;
  3757. result.m[15] = 1.0;
  3758. result._markAsUpdated();
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3762. */
  3763. Matrix.FromQuaternionToRef = function (quat, result) {
  3764. var xx = quat.x * quat.x;
  3765. var yy = quat.y * quat.y;
  3766. var zz = quat.z * quat.z;
  3767. var xy = quat.x * quat.y;
  3768. var zw = quat.z * quat.w;
  3769. var zx = quat.z * quat.x;
  3770. var yw = quat.y * quat.w;
  3771. var yz = quat.y * quat.z;
  3772. var xw = quat.x * quat.w;
  3773. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3774. result.m[1] = 2.0 * (xy + zw);
  3775. result.m[2] = 2.0 * (zx - yw);
  3776. result.m[3] = 0.0;
  3777. result.m[4] = 2.0 * (xy - zw);
  3778. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3779. result.m[6] = 2.0 * (yz + xw);
  3780. result.m[7] = 0.0;
  3781. result.m[8] = 2.0 * (zx + yw);
  3782. result.m[9] = 2.0 * (yz - xw);
  3783. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3784. result.m[11] = 0.0;
  3785. result.m[12] = 0.0;
  3786. result.m[13] = 0.0;
  3787. result.m[14] = 0.0;
  3788. result.m[15] = 1.0;
  3789. result._markAsUpdated();
  3790. };
  3791. return Matrix;
  3792. }());
  3793. Matrix._tempQuaternion = new Quaternion();
  3794. Matrix._xAxis = Vector3.Zero();
  3795. Matrix._yAxis = Vector3.Zero();
  3796. Matrix._zAxis = Vector3.Zero();
  3797. Matrix._updateFlagSeed = 0;
  3798. BABYLON.Matrix = Matrix;
  3799. var Plane = (function () {
  3800. /**
  3801. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3802. */
  3803. function Plane(a, b, c, d) {
  3804. this.normal = new Vector3(a, b, c);
  3805. this.d = d;
  3806. }
  3807. /**
  3808. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3809. */
  3810. Plane.prototype.asArray = function () {
  3811. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3812. };
  3813. // Methods
  3814. /**
  3815. * Returns a new plane copied from the current Plane.
  3816. */
  3817. Plane.prototype.clone = function () {
  3818. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3819. };
  3820. /**
  3821. * Returns the string "Plane".
  3822. */
  3823. Plane.prototype.getClassName = function () {
  3824. return "Plane";
  3825. };
  3826. /**
  3827. * Returns the Plane hash code.
  3828. */
  3829. Plane.prototype.getHashCode = function () {
  3830. var hash = this.normal.getHashCode();
  3831. hash = (hash * 397) ^ (this.d || 0);
  3832. return hash;
  3833. };
  3834. /**
  3835. * Normalize the current Plane in place.
  3836. * Returns the updated Plane.
  3837. */
  3838. Plane.prototype.normalize = function () {
  3839. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3840. var magnitude = 0.0;
  3841. if (norm !== 0) {
  3842. magnitude = 1.0 / norm;
  3843. }
  3844. this.normal.x *= magnitude;
  3845. this.normal.y *= magnitude;
  3846. this.normal.z *= magnitude;
  3847. this.d *= magnitude;
  3848. return this;
  3849. };
  3850. /**
  3851. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3852. */
  3853. Plane.prototype.transform = function (transformation) {
  3854. var transposedMatrix = Matrix.Transpose(transformation);
  3855. var x = this.normal.x;
  3856. var y = this.normal.y;
  3857. var z = this.normal.z;
  3858. var d = this.d;
  3859. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3860. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3861. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3862. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3863. return new Plane(normalX, normalY, normalZ, finalD);
  3864. };
  3865. /**
  3866. * Returns the dot product (float) of the point coordinates and the plane normal.
  3867. */
  3868. Plane.prototype.dotCoordinate = function (point) {
  3869. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3870. };
  3871. /**
  3872. * Updates the current Plane from the plane defined by the three passed points.
  3873. * Returns the updated Plane.
  3874. */
  3875. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3876. var x1 = point2.x - point1.x;
  3877. var y1 = point2.y - point1.y;
  3878. var z1 = point2.z - point1.z;
  3879. var x2 = point3.x - point1.x;
  3880. var y2 = point3.y - point1.y;
  3881. var z2 = point3.z - point1.z;
  3882. var yz = (y1 * z2) - (z1 * y2);
  3883. var xz = (z1 * x2) - (x1 * z2);
  3884. var xy = (x1 * y2) - (y1 * x2);
  3885. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3886. var invPyth;
  3887. if (pyth !== 0) {
  3888. invPyth = 1.0 / pyth;
  3889. }
  3890. else {
  3891. invPyth = 0.0;
  3892. }
  3893. this.normal.x = yz * invPyth;
  3894. this.normal.y = xz * invPyth;
  3895. this.normal.z = xy * invPyth;
  3896. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3897. return this;
  3898. };
  3899. /**
  3900. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3901. */
  3902. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3903. var dot = Vector3.Dot(this.normal, direction);
  3904. return (dot <= epsilon);
  3905. };
  3906. /**
  3907. * Returns the signed distance (float) from the passed point to the Plane.
  3908. */
  3909. Plane.prototype.signedDistanceTo = function (point) {
  3910. return Vector3.Dot(point, this.normal) + this.d;
  3911. };
  3912. // Statics
  3913. /**
  3914. * Returns a new Plane from the passed array.
  3915. */
  3916. Plane.FromArray = function (array) {
  3917. return new Plane(array[0], array[1], array[2], array[3]);
  3918. };
  3919. /**
  3920. * Returns a new Plane defined by the three passed points.
  3921. */
  3922. Plane.FromPoints = function (point1, point2, point3) {
  3923. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3924. result.copyFromPoints(point1, point2, point3);
  3925. return result;
  3926. };
  3927. /**
  3928. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3929. * Note : the vector "normal" is updated because normalized.
  3930. */
  3931. Plane.FromPositionAndNormal = function (origin, normal) {
  3932. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3933. normal.normalize();
  3934. result.normal = normal;
  3935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3936. return result;
  3937. };
  3938. /**
  3939. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3940. */
  3941. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3942. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3943. return Vector3.Dot(point, normal) + d;
  3944. };
  3945. return Plane;
  3946. }());
  3947. BABYLON.Plane = Plane;
  3948. var Viewport = (function () {
  3949. /**
  3950. * Creates a Viewport object located at (x, y) and sized (width, height).
  3951. */
  3952. function Viewport(x, y, width, height) {
  3953. this.x = x;
  3954. this.y = y;
  3955. this.width = width;
  3956. this.height = height;
  3957. }
  3958. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3959. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3960. };
  3961. /**
  3962. * Returns a new Viewport copied from the current one.
  3963. */
  3964. Viewport.prototype.clone = function () {
  3965. return new Viewport(this.x, this.y, this.width, this.height);
  3966. };
  3967. return Viewport;
  3968. }());
  3969. BABYLON.Viewport = Viewport;
  3970. var Frustum = (function () {
  3971. function Frustum() {
  3972. }
  3973. /**
  3974. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3975. */
  3976. Frustum.GetPlanes = function (transform) {
  3977. var frustumPlanes = [];
  3978. for (var index = 0; index < 6; index++) {
  3979. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3980. }
  3981. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3982. return frustumPlanes;
  3983. };
  3984. /**
  3985. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3986. */
  3987. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3988. // Near
  3989. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3990. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3991. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3992. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3993. frustumPlanes[0].normalize();
  3994. // Far
  3995. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3996. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3997. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3998. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3999. frustumPlanes[1].normalize();
  4000. // Left
  4001. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4002. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4003. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4004. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4005. frustumPlanes[2].normalize();
  4006. // Right
  4007. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4008. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4009. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4010. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4011. frustumPlanes[3].normalize();
  4012. // Top
  4013. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4014. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4015. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4016. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4017. frustumPlanes[4].normalize();
  4018. // Bottom
  4019. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4020. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4021. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4022. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4023. frustumPlanes[5].normalize();
  4024. };
  4025. return Frustum;
  4026. }());
  4027. BABYLON.Frustum = Frustum;
  4028. var Space;
  4029. (function (Space) {
  4030. Space[Space["LOCAL"] = 0] = "LOCAL";
  4031. Space[Space["WORLD"] = 1] = "WORLD";
  4032. Space[Space["BONE"] = 2] = "BONE";
  4033. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4034. var Axis = (function () {
  4035. function Axis() {
  4036. }
  4037. return Axis;
  4038. }());
  4039. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4040. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4041. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4042. BABYLON.Axis = Axis;
  4043. ;
  4044. var BezierCurve = (function () {
  4045. function BezierCurve() {
  4046. }
  4047. /**
  4048. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4049. */
  4050. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4051. // Extract X (which is equal to time here)
  4052. var f0 = 1 - 3 * x2 + 3 * x1;
  4053. var f1 = 3 * x2 - 6 * x1;
  4054. var f2 = 3 * x1;
  4055. var refinedT = t;
  4056. for (var i = 0; i < 5; i++) {
  4057. var refinedT2 = refinedT * refinedT;
  4058. var refinedT3 = refinedT2 * refinedT;
  4059. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4060. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4061. refinedT -= (x - t) * slope;
  4062. refinedT = Math.min(1, Math.max(0, refinedT));
  4063. }
  4064. // Resolve cubic bezier for the given x
  4065. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4066. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4067. Math.pow(refinedT, 3);
  4068. };
  4069. return BezierCurve;
  4070. }());
  4071. BABYLON.BezierCurve = BezierCurve;
  4072. var Orientation;
  4073. (function (Orientation) {
  4074. Orientation[Orientation["CW"] = 0] = "CW";
  4075. Orientation[Orientation["CCW"] = 1] = "CCW";
  4076. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4077. var Angle = (function () {
  4078. /**
  4079. * Creates an Angle object of "radians" radians (float).
  4080. */
  4081. function Angle(radians) {
  4082. var _this = this;
  4083. /**
  4084. * Returns the Angle value in degrees (float).
  4085. */
  4086. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4087. /**
  4088. * Returns the Angle value in radians (float).
  4089. */
  4090. this.radians = function () { return _this._radians; };
  4091. this._radians = radians;
  4092. if (this._radians < 0.0)
  4093. this._radians += (2.0 * Math.PI);
  4094. }
  4095. /**
  4096. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4097. */
  4098. Angle.BetweenTwoPoints = function (a, b) {
  4099. var delta = b.subtract(a);
  4100. var theta = Math.atan2(delta.y, delta.x);
  4101. return new Angle(theta);
  4102. };
  4103. /**
  4104. * Returns a new Angle object from the passed float in radians.
  4105. */
  4106. Angle.FromRadians = function (radians) {
  4107. return new Angle(radians);
  4108. };
  4109. /**
  4110. * Returns a new Angle object from the passed float in degrees.
  4111. */
  4112. Angle.FromDegrees = function (degrees) {
  4113. return new Angle(degrees * Math.PI / 180.0);
  4114. };
  4115. return Angle;
  4116. }());
  4117. BABYLON.Angle = Angle;
  4118. var Arc2 = (function () {
  4119. /**
  4120. * Creates an Arc object from the three passed points : start, middle and end.
  4121. */
  4122. function Arc2(startPoint, midPoint, endPoint) {
  4123. this.startPoint = startPoint;
  4124. this.midPoint = midPoint;
  4125. this.endPoint = endPoint;
  4126. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4127. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4128. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4129. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4130. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4131. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4132. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4133. var a1 = this.startAngle.degrees();
  4134. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4135. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4136. // angles correction
  4137. if (a2 - a1 > +180.0)
  4138. a2 -= 360.0;
  4139. if (a2 - a1 < -180.0)
  4140. a2 += 360.0;
  4141. if (a3 - a2 > +180.0)
  4142. a3 -= 360.0;
  4143. if (a3 - a2 < -180.0)
  4144. a3 += 360.0;
  4145. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4146. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4147. }
  4148. return Arc2;
  4149. }());
  4150. BABYLON.Arc2 = Arc2;
  4151. var Path2 = (function () {
  4152. /**
  4153. * Creates a Path2 object from the starting 2D coordinates x and y.
  4154. */
  4155. function Path2(x, y) {
  4156. this._points = new Array();
  4157. this._length = 0.0;
  4158. this.closed = false;
  4159. this._points.push(new Vector2(x, y));
  4160. }
  4161. /**
  4162. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4163. * Returns the updated Path2.
  4164. */
  4165. Path2.prototype.addLineTo = function (x, y) {
  4166. if (closed) {
  4167. //Tools.Error("cannot add lines to closed paths");
  4168. return this;
  4169. }
  4170. var newPoint = new Vector2(x, y);
  4171. var previousPoint = this._points[this._points.length - 1];
  4172. this._points.push(newPoint);
  4173. this._length += newPoint.subtract(previousPoint).length();
  4174. return this;
  4175. };
  4176. /**
  4177. * 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.
  4178. * Returns the updated Path2.
  4179. */
  4180. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4181. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4182. if (closed) {
  4183. //Tools.Error("cannot add arcs to closed paths");
  4184. return this;
  4185. }
  4186. var startPoint = this._points[this._points.length - 1];
  4187. var midPoint = new Vector2(midX, midY);
  4188. var endPoint = new Vector2(endX, endY);
  4189. var arc = new Arc2(startPoint, midPoint, endPoint);
  4190. var increment = arc.angle.radians() / numberOfSegments;
  4191. if (arc.orientation === Orientation.CW)
  4192. increment *= -1;
  4193. var currentAngle = arc.startAngle.radians() + increment;
  4194. for (var i = 0; i < numberOfSegments; i++) {
  4195. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4196. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4197. this.addLineTo(x, y);
  4198. currentAngle += increment;
  4199. }
  4200. return this;
  4201. };
  4202. /**
  4203. * Closes the Path2.
  4204. * Returns the Path2.
  4205. */
  4206. Path2.prototype.close = function () {
  4207. this.closed = true;
  4208. return this;
  4209. };
  4210. /**
  4211. * Returns the Path2 total length (float).
  4212. */
  4213. Path2.prototype.length = function () {
  4214. var result = this._length;
  4215. if (!this.closed) {
  4216. var lastPoint = this._points[this._points.length - 1];
  4217. var firstPoint = this._points[0];
  4218. result += (firstPoint.subtract(lastPoint).length());
  4219. }
  4220. return result;
  4221. };
  4222. /**
  4223. * Returns the Path2 internal array of points.
  4224. */
  4225. Path2.prototype.getPoints = function () {
  4226. return this._points;
  4227. };
  4228. /**
  4229. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4230. */
  4231. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4232. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4233. //Tools.Error("normalized length position should be between 0 and 1.");
  4234. return Vector2.Zero();
  4235. }
  4236. var lengthPosition = normalizedLengthPosition * this.length();
  4237. var previousOffset = 0;
  4238. for (var i = 0; i < this._points.length; i++) {
  4239. var j = (i + 1) % this._points.length;
  4240. var a = this._points[i];
  4241. var b = this._points[j];
  4242. var bToA = b.subtract(a);
  4243. var nextOffset = (bToA.length() + previousOffset);
  4244. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4245. var dir = bToA.normalize();
  4246. var localOffset = lengthPosition - previousOffset;
  4247. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4248. }
  4249. previousOffset = nextOffset;
  4250. }
  4251. //Tools.Error("internal error");
  4252. return Vector2.Zero();
  4253. };
  4254. /**
  4255. * Returns a new Path2 starting at the coordinates (x, y).
  4256. */
  4257. Path2.StartingAt = function (x, y) {
  4258. return new Path2(x, y);
  4259. };
  4260. return Path2;
  4261. }());
  4262. BABYLON.Path2 = Path2;
  4263. var Path3D = (function () {
  4264. /**
  4265. * new Path3D(path, normal, raw)
  4266. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4267. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4268. * path : an array of Vector3, the curve axis of the Path3D
  4269. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4270. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4271. */
  4272. function Path3D(path, firstNormal, raw) {
  4273. this.path = path;
  4274. this._curve = new Array();
  4275. this._distances = new Array();
  4276. this._tangents = new Array();
  4277. this._normals = new Array();
  4278. this._binormals = new Array();
  4279. for (var p = 0; p < path.length; p++) {
  4280. this._curve[p] = path[p].clone(); // hard copy
  4281. }
  4282. this._raw = raw || false;
  4283. this._compute(firstNormal);
  4284. }
  4285. /**
  4286. * Returns the Path3D array of successive Vector3 designing its curve.
  4287. */
  4288. Path3D.prototype.getCurve = function () {
  4289. return this._curve;
  4290. };
  4291. /**
  4292. * Returns an array populated with tangent vectors on each Path3D curve point.
  4293. */
  4294. Path3D.prototype.getTangents = function () {
  4295. return this._tangents;
  4296. };
  4297. /**
  4298. * Returns an array populated with normal vectors on each Path3D curve point.
  4299. */
  4300. Path3D.prototype.getNormals = function () {
  4301. return this._normals;
  4302. };
  4303. /**
  4304. * Returns an array populated with binormal vectors on each Path3D curve point.
  4305. */
  4306. Path3D.prototype.getBinormals = function () {
  4307. return this._binormals;
  4308. };
  4309. /**
  4310. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4311. */
  4312. Path3D.prototype.getDistances = function () {
  4313. return this._distances;
  4314. };
  4315. /**
  4316. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4317. * Returns the same object updated.
  4318. */
  4319. Path3D.prototype.update = function (path, firstNormal) {
  4320. for (var p = 0; p < path.length; p++) {
  4321. this._curve[p].x = path[p].x;
  4322. this._curve[p].y = path[p].y;
  4323. this._curve[p].z = path[p].z;
  4324. }
  4325. this._compute(firstNormal);
  4326. return this;
  4327. };
  4328. // private function compute() : computes tangents, normals and binormals
  4329. Path3D.prototype._compute = function (firstNormal) {
  4330. var l = this._curve.length;
  4331. // first and last tangents
  4332. this._tangents[0] = this._getFirstNonNullVector(0);
  4333. if (!this._raw) {
  4334. this._tangents[0].normalize();
  4335. }
  4336. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4337. if (!this._raw) {
  4338. this._tangents[l - 1].normalize();
  4339. }
  4340. // normals and binormals at first point : arbitrary vector with _normalVector()
  4341. var tg0 = this._tangents[0];
  4342. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4343. this._normals[0] = pp0;
  4344. if (!this._raw) {
  4345. this._normals[0].normalize();
  4346. }
  4347. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4348. if (!this._raw) {
  4349. this._binormals[0].normalize();
  4350. }
  4351. this._distances[0] = 0.0;
  4352. // normals and binormals : next points
  4353. var prev; // previous vector (segment)
  4354. var cur; // current vector (segment)
  4355. var curTang; // current tangent
  4356. // previous normal
  4357. var prevBinor; // previous binormal
  4358. for (var i = 1; i < l; i++) {
  4359. // tangents
  4360. prev = this._getLastNonNullVector(i);
  4361. if (i < l - 1) {
  4362. cur = this._getFirstNonNullVector(i);
  4363. this._tangents[i] = prev.add(cur);
  4364. this._tangents[i].normalize();
  4365. }
  4366. this._distances[i] = this._distances[i - 1] + prev.length();
  4367. // normals and binormals
  4368. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4369. curTang = this._tangents[i];
  4370. prevBinor = this._binormals[i - 1];
  4371. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4372. if (!this._raw) {
  4373. this._normals[i].normalize();
  4374. }
  4375. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4376. if (!this._raw) {
  4377. this._binormals[i].normalize();
  4378. }
  4379. }
  4380. };
  4381. // private function getFirstNonNullVector(index)
  4382. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4383. Path3D.prototype._getFirstNonNullVector = function (index) {
  4384. var i = 1;
  4385. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4386. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4387. i++;
  4388. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4389. }
  4390. return nNVector;
  4391. };
  4392. // private function getLastNonNullVector(index)
  4393. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4394. Path3D.prototype._getLastNonNullVector = function (index) {
  4395. var i = 1;
  4396. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4397. while (nLVector.length() === 0 && index > i + 1) {
  4398. i++;
  4399. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4400. }
  4401. return nLVector;
  4402. };
  4403. // private function normalVector(v0, vt, va) :
  4404. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4405. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4406. Path3D.prototype._normalVector = function (v0, vt, va) {
  4407. var normal0;
  4408. var tgl = vt.length();
  4409. if (tgl === 0.0) {
  4410. tgl = 1.0;
  4411. }
  4412. if (va === undefined || va === null) {
  4413. var point;
  4414. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4415. point = new Vector3(0.0, -1.0, 0.0);
  4416. }
  4417. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4418. point = new Vector3(1.0, 0.0, 0.0);
  4419. }
  4420. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4421. point = new Vector3(0.0, 0.0, 1.0);
  4422. }
  4423. normal0 = Vector3.Cross(vt, point);
  4424. }
  4425. else {
  4426. normal0 = Vector3.Cross(vt, va);
  4427. Vector3.CrossToRef(normal0, vt, normal0);
  4428. }
  4429. normal0.normalize();
  4430. return normal0;
  4431. };
  4432. return Path3D;
  4433. }());
  4434. BABYLON.Path3D = Path3D;
  4435. var Curve3 = (function () {
  4436. /**
  4437. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4438. * A Curve3 is designed from a series of successive Vector3.
  4439. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4440. */
  4441. function Curve3(points) {
  4442. this._length = 0.0;
  4443. this._points = points;
  4444. this._length = this._computeLength(points);
  4445. }
  4446. /**
  4447. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4448. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4449. * @param v1 (Vector3) the control point
  4450. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4451. * @param nbPoints (integer) the wanted number of points in the curve
  4452. */
  4453. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4454. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4455. var bez = new Array();
  4456. var equation = function (t, val0, val1, val2) {
  4457. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4458. return res;
  4459. };
  4460. for (var i = 0; i <= nbPoints; i++) {
  4461. 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)));
  4462. }
  4463. return new Curve3(bez);
  4464. };
  4465. /**
  4466. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4467. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4468. * @param v1 (Vector3) the first control point
  4469. * @param v2 (Vector3) the second control point
  4470. * @param v3 (Vector3) the end point of the Cubic Bezier
  4471. * @param nbPoints (integer) the wanted number of points in the curve
  4472. */
  4473. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4474. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4475. var bez = new Array();
  4476. var equation = function (t, val0, val1, val2, val3) {
  4477. 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;
  4478. return res;
  4479. };
  4480. for (var i = 0; i <= nbPoints; i++) {
  4481. 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)));
  4482. }
  4483. return new Curve3(bez);
  4484. };
  4485. /**
  4486. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4487. * @param p1 (Vector3) the origin point of the Hermite Spline
  4488. * @param t1 (Vector3) the tangent vector at the origin point
  4489. * @param p2 (Vector3) the end point of the Hermite Spline
  4490. * @param t2 (Vector3) the tangent vector at the end point
  4491. * @param nbPoints (integer) the wanted number of points in the curve
  4492. */
  4493. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4494. var hermite = new Array();
  4495. var step = 1.0 / nbPoints;
  4496. for (var i = 0; i <= nbPoints; i++) {
  4497. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4498. }
  4499. return new Curve3(hermite);
  4500. };
  4501. /**
  4502. * Returns a Curve3 object along a CatmullRom Spline curve :
  4503. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4504. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4505. */
  4506. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4507. var totalPoints = new Array();
  4508. totalPoints.push(points[0].clone());
  4509. Array.prototype.push.apply(totalPoints, points);
  4510. totalPoints.push(points[points.length - 1].clone());
  4511. var catmullRom = new Array();
  4512. var step = 1.0 / nbPoints;
  4513. for (var i = 0; i < totalPoints.length - 3; i++) {
  4514. var amount = 0.0;
  4515. for (var c = 0; c < nbPoints; c++) {
  4516. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4517. amount += step;
  4518. }
  4519. }
  4520. i--;
  4521. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4522. return new Curve3(catmullRom);
  4523. };
  4524. /**
  4525. * Returns the Curve3 stored array of successive Vector3
  4526. */
  4527. Curve3.prototype.getPoints = function () {
  4528. return this._points;
  4529. };
  4530. /**
  4531. * Returns the computed length (float) of the curve.
  4532. */
  4533. Curve3.prototype.length = function () {
  4534. return this._length;
  4535. };
  4536. /**
  4537. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4538. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4539. * curveA and curveB keep unchanged.
  4540. */
  4541. Curve3.prototype.continue = function (curve) {
  4542. var lastPoint = this._points[this._points.length - 1];
  4543. var continuedPoints = this._points.slice();
  4544. var curvePoints = curve.getPoints();
  4545. for (var i = 1; i < curvePoints.length; i++) {
  4546. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4547. }
  4548. var continuedCurve = new Curve3(continuedPoints);
  4549. return continuedCurve;
  4550. };
  4551. Curve3.prototype._computeLength = function (path) {
  4552. var l = 0;
  4553. for (var i = 1; i < path.length; i++) {
  4554. l += (path[i].subtract(path[i - 1])).length();
  4555. }
  4556. return l;
  4557. };
  4558. return Curve3;
  4559. }());
  4560. BABYLON.Curve3 = Curve3;
  4561. // SphericalHarmonics
  4562. var SphericalHarmonics = (function () {
  4563. function SphericalHarmonics() {
  4564. this.L00 = Vector3.Zero();
  4565. this.L1_1 = Vector3.Zero();
  4566. this.L10 = Vector3.Zero();
  4567. this.L11 = Vector3.Zero();
  4568. this.L2_2 = Vector3.Zero();
  4569. this.L2_1 = Vector3.Zero();
  4570. this.L20 = Vector3.Zero();
  4571. this.L21 = Vector3.Zero();
  4572. this.L22 = Vector3.Zero();
  4573. }
  4574. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4575. var colorVector = new Vector3(color.r, color.g, color.b);
  4576. var c = colorVector.scale(deltaSolidAngle);
  4577. this.L00 = this.L00.add(c.scale(0.282095));
  4578. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4579. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4580. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4581. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4582. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4583. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4584. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4585. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4586. };
  4587. SphericalHarmonics.prototype.scale = function (scale) {
  4588. this.L00 = this.L00.scale(scale);
  4589. this.L1_1 = this.L1_1.scale(scale);
  4590. this.L10 = this.L10.scale(scale);
  4591. this.L11 = this.L11.scale(scale);
  4592. this.L2_2 = this.L2_2.scale(scale);
  4593. this.L2_1 = this.L2_1.scale(scale);
  4594. this.L20 = this.L20.scale(scale);
  4595. this.L21 = this.L21.scale(scale);
  4596. this.L22 = this.L22.scale(scale);
  4597. };
  4598. return SphericalHarmonics;
  4599. }());
  4600. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4601. // SphericalPolynomial
  4602. var SphericalPolynomial = (function () {
  4603. function SphericalPolynomial() {
  4604. this.x = Vector3.Zero();
  4605. this.y = Vector3.Zero();
  4606. this.z = Vector3.Zero();
  4607. this.xx = Vector3.Zero();
  4608. this.yy = Vector3.Zero();
  4609. this.zz = Vector3.Zero();
  4610. this.xy = Vector3.Zero();
  4611. this.yz = Vector3.Zero();
  4612. this.zx = Vector3.Zero();
  4613. }
  4614. SphericalPolynomial.prototype.addAmbient = function (color) {
  4615. var colorVector = new Vector3(color.r, color.g, color.b);
  4616. this.xx = this.xx.add(colorVector);
  4617. this.yy = this.yy.add(colorVector);
  4618. this.zz = this.zz.add(colorVector);
  4619. };
  4620. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4621. var result = new SphericalPolynomial();
  4622. result.x = harmonics.L11.scale(1.02333);
  4623. result.y = harmonics.L1_1.scale(1.02333);
  4624. result.z = harmonics.L10.scale(1.02333);
  4625. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4626. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4627. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4628. result.yz = harmonics.L2_1.scale(0.858086);
  4629. result.zx = harmonics.L21.scale(0.858086);
  4630. result.xy = harmonics.L2_2.scale(0.858086);
  4631. return result;
  4632. };
  4633. return SphericalPolynomial;
  4634. }());
  4635. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4636. // Vertex formats
  4637. var PositionNormalVertex = (function () {
  4638. function PositionNormalVertex(position, normal) {
  4639. if (position === void 0) { position = Vector3.Zero(); }
  4640. if (normal === void 0) { normal = Vector3.Up(); }
  4641. this.position = position;
  4642. this.normal = normal;
  4643. }
  4644. PositionNormalVertex.prototype.clone = function () {
  4645. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4646. };
  4647. return PositionNormalVertex;
  4648. }());
  4649. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4650. var PositionNormalTextureVertex = (function () {
  4651. function PositionNormalTextureVertex(position, normal, uv) {
  4652. if (position === void 0) { position = Vector3.Zero(); }
  4653. if (normal === void 0) { normal = Vector3.Up(); }
  4654. if (uv === void 0) { uv = Vector2.Zero(); }
  4655. this.position = position;
  4656. this.normal = normal;
  4657. this.uv = uv;
  4658. }
  4659. PositionNormalTextureVertex.prototype.clone = function () {
  4660. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4661. };
  4662. return PositionNormalTextureVertex;
  4663. }());
  4664. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4665. // Temporary pre-allocated objects for engine internal use
  4666. // usage in any internal function :
  4667. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4668. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4669. var Tmp = (function () {
  4670. function Tmp() {
  4671. }
  4672. return Tmp;
  4673. }());
  4674. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4675. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4676. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4677. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4678. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4679. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4680. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4681. Matrix.Zero(), Matrix.Zero(),
  4682. Matrix.Zero(), Matrix.Zero(),
  4683. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4684. BABYLON.Tmp = Tmp;
  4685. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4686. var MathTmp = (function () {
  4687. function MathTmp() {
  4688. }
  4689. return MathTmp;
  4690. }());
  4691. MathTmp.Vector3 = [Vector3.Zero()];
  4692. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4693. MathTmp.Quaternion = [Quaternion.Zero()];
  4694. })(BABYLON || (BABYLON = {}));
  4695. //# sourceMappingURL=babylon.math.js.map
  4696. //# sourceMappingURL=babylon.mixins.js.map
  4697. var BABYLON;
  4698. (function (BABYLON) {
  4699. function generateSerializableMember(type, sourceName) {
  4700. return function (target, propertyKey) {
  4701. if (!target.__serializableMembers) {
  4702. target.__serializableMembers = {};
  4703. }
  4704. if (!target.__serializableMembers[propertyKey]) {
  4705. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4706. }
  4707. };
  4708. }
  4709. function generateExpandMember(setCallback) {
  4710. return function (target, propertyKey) {
  4711. if (setCallback) {
  4712. var key = "_" + propertyKey;
  4713. Object.defineProperty(target, propertyKey, {
  4714. get: function () {
  4715. return this[key];
  4716. },
  4717. set: function (value) {
  4718. if (this[key] === value) {
  4719. return;
  4720. }
  4721. this[key] = value;
  4722. target[setCallback].apply(this);
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. }
  4728. };
  4729. }
  4730. function expandToProperty(callback) {
  4731. return generateExpandMember(callback);
  4732. }
  4733. BABYLON.expandToProperty = expandToProperty;
  4734. function serialize(sourceName) {
  4735. return generateSerializableMember(0, sourceName); // value member
  4736. }
  4737. BABYLON.serialize = serialize;
  4738. function serializeAsTexture(sourceName) {
  4739. return generateSerializableMember(1, sourceName); // texture member
  4740. }
  4741. BABYLON.serializeAsTexture = serializeAsTexture;
  4742. function serializeAsColor3(sourceName) {
  4743. return generateSerializableMember(2, sourceName); // color3 member
  4744. }
  4745. BABYLON.serializeAsColor3 = serializeAsColor3;
  4746. function serializeAsFresnelParameters(sourceName) {
  4747. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4748. }
  4749. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4750. function serializeAsVector2(sourceName) {
  4751. return generateSerializableMember(4, sourceName); // vector2 member
  4752. }
  4753. BABYLON.serializeAsVector2 = serializeAsVector2;
  4754. function serializeAsVector3(sourceName) {
  4755. return generateSerializableMember(5, sourceName); // vector3 member
  4756. }
  4757. BABYLON.serializeAsVector3 = serializeAsVector3;
  4758. function serializeAsMeshReference(sourceName) {
  4759. return generateSerializableMember(6, sourceName); // mesh reference member
  4760. }
  4761. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4762. function serializeAsColorCurves(sourceName) {
  4763. return generateSerializableMember(7, sourceName); // color curves
  4764. }
  4765. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4766. var SerializationHelper = (function () {
  4767. function SerializationHelper() {
  4768. }
  4769. SerializationHelper.Serialize = function (entity, serializationObject) {
  4770. if (!serializationObject) {
  4771. serializationObject = {};
  4772. }
  4773. // Tags
  4774. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4775. // Properties
  4776. for (var property in entity.__serializableMembers) {
  4777. var propertyDescriptor = entity.__serializableMembers[property];
  4778. var targetPropertyName = propertyDescriptor.sourceName || property;
  4779. var propertyType = propertyDescriptor.type;
  4780. var sourceProperty = entity[property];
  4781. if (sourceProperty !== undefined && sourceProperty !== null) {
  4782. switch (propertyType) {
  4783. case 0:
  4784. serializationObject[targetPropertyName] = sourceProperty;
  4785. break;
  4786. case 1:
  4787. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4788. break;
  4789. case 2:
  4790. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4791. break;
  4792. case 3:
  4793. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4794. break;
  4795. case 4:
  4796. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4797. break;
  4798. case 5:
  4799. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4800. break;
  4801. case 6:
  4802. serializationObject[targetPropertyName] = sourceProperty.id;
  4803. break;
  4804. case 7:
  4805. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4806. break;
  4807. }
  4808. }
  4809. }
  4810. return serializationObject;
  4811. };
  4812. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4813. var destination = creationFunction();
  4814. // Tags
  4815. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4816. // Properties
  4817. for (var property in destination.__serializableMembers) {
  4818. var propertyDescriptor = destination.__serializableMembers[property];
  4819. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4820. var propertyType = propertyDescriptor.type;
  4821. if (sourceProperty !== undefined && sourceProperty !== null) {
  4822. switch (propertyType) {
  4823. case 0:
  4824. destination[property] = sourceProperty;
  4825. break;
  4826. case 1:
  4827. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4828. break;
  4829. case 2:
  4830. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4831. break;
  4832. case 3:
  4833. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4834. break;
  4835. case 4:
  4836. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4837. break;
  4838. case 5:
  4839. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4840. break;
  4841. case 6:
  4842. destination[property] = scene.getLastMeshByID(sourceProperty);
  4843. break;
  4844. case 7:
  4845. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4846. break;
  4847. }
  4848. }
  4849. }
  4850. return destination;
  4851. };
  4852. SerializationHelper.Clone = function (creationFunction, source) {
  4853. var destination = creationFunction();
  4854. // Tags
  4855. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4856. // Properties
  4857. for (var property in destination.__serializableMembers) {
  4858. var propertyDescriptor = destination.__serializableMembers[property];
  4859. var sourceProperty = source[property];
  4860. var propertyType = propertyDescriptor.type;
  4861. if (sourceProperty !== undefined && sourceProperty !== null) {
  4862. switch (propertyType) {
  4863. case 0: // Value
  4864. case 6:
  4865. destination[property] = sourceProperty;
  4866. break;
  4867. case 1: // Texture
  4868. case 2: // Color3
  4869. case 3: // FresnelParameters
  4870. case 4: // Vector2
  4871. case 5: // Vector3
  4872. case 7:
  4873. destination[property] = sourceProperty.clone();
  4874. break;
  4875. }
  4876. }
  4877. }
  4878. return destination;
  4879. };
  4880. return SerializationHelper;
  4881. }());
  4882. BABYLON.SerializationHelper = SerializationHelper;
  4883. })(BABYLON || (BABYLON = {}));
  4884. //# sourceMappingURL=babylon.decorators.js.map
  4885. var BABYLON;
  4886. (function (BABYLON) {
  4887. /**
  4888. * A class serves as a medium between the observable and its observers
  4889. */
  4890. var EventState = (function () {
  4891. /**
  4892. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4893. */
  4894. function EventState(mask, skipNextObservers) {
  4895. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4896. this.initalize(mask, skipNextObservers);
  4897. }
  4898. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4899. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4900. this.mask = mask;
  4901. this.skipNextObservers = skipNextObservers;
  4902. return this;
  4903. };
  4904. return EventState;
  4905. }());
  4906. BABYLON.EventState = EventState;
  4907. /**
  4908. * Represent an Observer registered to a given Observable object.
  4909. */
  4910. var Observer = (function () {
  4911. function Observer(callback, mask) {
  4912. this.callback = callback;
  4913. this.mask = mask;
  4914. }
  4915. return Observer;
  4916. }());
  4917. BABYLON.Observer = Observer;
  4918. /**
  4919. * The Observable class is a simple implementation of the Observable pattern.
  4920. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4921. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4922. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4923. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4924. */
  4925. var Observable = (function () {
  4926. function Observable() {
  4927. this._observers = new Array();
  4928. this._eventState = new EventState(0);
  4929. }
  4930. /**
  4931. * Create a new Observer with the specified callback
  4932. * @param callback the callback that will be executed for that Observer
  4933. * @param mask the mask used to filter observers
  4934. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  4935. */
  4936. Observable.prototype.add = function (callback, mask, insertFirst) {
  4937. if (mask === void 0) { mask = -1; }
  4938. if (insertFirst === void 0) { insertFirst = false; }
  4939. if (!callback) {
  4940. return null;
  4941. }
  4942. var observer = new Observer(callback, mask);
  4943. if (insertFirst) {
  4944. this._observers.unshift(observer);
  4945. }
  4946. else {
  4947. this._observers.push(observer);
  4948. }
  4949. return observer;
  4950. };
  4951. /**
  4952. * Remove an Observer from the Observable object
  4953. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4954. */
  4955. Observable.prototype.remove = function (observer) {
  4956. var index = this._observers.indexOf(observer);
  4957. if (index !== -1) {
  4958. this._observers.splice(index, 1);
  4959. return true;
  4960. }
  4961. return false;
  4962. };
  4963. /**
  4964. * Remove a callback from the Observable object
  4965. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4966. */
  4967. Observable.prototype.removeCallback = function (callback) {
  4968. for (var index = 0; index < this._observers.length; index++) {
  4969. if (this._observers[index].callback === callback) {
  4970. this._observers.splice(index, 1);
  4971. return true;
  4972. }
  4973. }
  4974. return false;
  4975. };
  4976. /**
  4977. * Notify all Observers by calling their respective callback with the given data
  4978. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4979. * @param eventData
  4980. * @param mask
  4981. */
  4982. Observable.prototype.notifyObservers = function (eventData, mask) {
  4983. if (mask === void 0) { mask = -1; }
  4984. var state = this._eventState;
  4985. state.mask = mask;
  4986. state.skipNextObservers = false;
  4987. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4988. var obs = _a[_i];
  4989. if (obs.mask & mask) {
  4990. obs.callback(eventData, state);
  4991. }
  4992. if (state.skipNextObservers) {
  4993. return false;
  4994. }
  4995. }
  4996. return true;
  4997. };
  4998. /**
  4999. * return true is the Observable has at least one Observer registered
  5000. */
  5001. Observable.prototype.hasObservers = function () {
  5002. return this._observers.length > 0;
  5003. };
  5004. /**
  5005. * Clear the list of observers
  5006. */
  5007. Observable.prototype.clear = function () {
  5008. this._observers = new Array();
  5009. };
  5010. /**
  5011. * Clone the current observable
  5012. */
  5013. Observable.prototype.clone = function () {
  5014. var result = new Observable();
  5015. result._observers = this._observers.slice(0);
  5016. return result;
  5017. };
  5018. /**
  5019. * Does this observable handles observer registered with a given mask
  5020. * @param {number} trigger - the mask to be tested
  5021. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5022. **/
  5023. Observable.prototype.hasSpecificMask = function (mask) {
  5024. if (mask === void 0) { mask = -1; }
  5025. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5026. var obs = _a[_i];
  5027. if (obs.mask & mask && obs.mask === mask) {
  5028. return true;
  5029. }
  5030. }
  5031. return false;
  5032. };
  5033. return Observable;
  5034. }());
  5035. BABYLON.Observable = Observable;
  5036. })(BABYLON || (BABYLON = {}));
  5037. //# sourceMappingURL=babylon.observable.js.map
  5038. var BABYLON;
  5039. (function (BABYLON) {
  5040. var Database = (function () {
  5041. function Database(urlToScene, callbackManifestChecked) {
  5042. // Handling various flavors of prefixed version of IndexedDB
  5043. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  5044. this.callbackManifestChecked = callbackManifestChecked;
  5045. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  5046. this.db = null;
  5047. this.enableSceneOffline = false;
  5048. this.enableTexturesOffline = false;
  5049. this.manifestVersionFound = 0;
  5050. this.mustUpdateRessources = false;
  5051. this.hasReachedQuota = false;
  5052. if (!Database.IDBStorageEnabled) {
  5053. this.callbackManifestChecked(true);
  5054. }
  5055. else {
  5056. this.checkManifestFile();
  5057. }
  5058. }
  5059. Database.prototype.checkManifestFile = function () {
  5060. var _this = this;
  5061. function noManifestFile() {
  5062. that.enableSceneOffline = false;
  5063. that.enableTexturesOffline = false;
  5064. that.callbackManifestChecked(false);
  5065. }
  5066. var that = this;
  5067. var timeStampUsed = false;
  5068. var manifestURL = this.currentSceneUrl + ".manifest";
  5069. var xhr = new XMLHttpRequest();
  5070. if (navigator.onLine) {
  5071. // Adding a timestamp to by-pass browsers' cache
  5072. timeStampUsed = true;
  5073. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5074. }
  5075. xhr.open("GET", manifestURL, true);
  5076. xhr.addEventListener("load", function () {
  5077. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5078. try {
  5079. var manifestFile = JSON.parse(xhr.response);
  5080. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5081. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5082. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5083. _this.manifestVersionFound = manifestFile.version;
  5084. }
  5085. if (_this.callbackManifestChecked) {
  5086. _this.callbackManifestChecked(true);
  5087. }
  5088. }
  5089. catch (ex) {
  5090. noManifestFile();
  5091. }
  5092. }
  5093. else {
  5094. noManifestFile();
  5095. }
  5096. }, false);
  5097. xhr.addEventListener("error", function (event) {
  5098. if (timeStampUsed) {
  5099. timeStampUsed = false;
  5100. // Let's retry without the timeStamp
  5101. // It could fail when coupled with HTML5 Offline API
  5102. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5103. xhr.open("GET", retryManifestURL, true);
  5104. xhr.send();
  5105. }
  5106. else {
  5107. noManifestFile();
  5108. }
  5109. }, false);
  5110. try {
  5111. xhr.send();
  5112. }
  5113. catch (ex) {
  5114. BABYLON.Tools.Error("Error on XHR send request.");
  5115. that.callbackManifestChecked(false);
  5116. }
  5117. };
  5118. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5119. var _this = this;
  5120. function handleError() {
  5121. that.isSupported = false;
  5122. if (errorCallback)
  5123. errorCallback();
  5124. }
  5125. var that = this;
  5126. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5127. // Your browser doesn't support IndexedDB
  5128. this.isSupported = false;
  5129. if (errorCallback)
  5130. errorCallback();
  5131. }
  5132. else {
  5133. // If the DB hasn't been opened or created yet
  5134. if (!this.db) {
  5135. this.hasReachedQuota = false;
  5136. this.isSupported = true;
  5137. var request = this.idbFactory.open("babylonjs", 1);
  5138. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5139. request.onerror = function (event) {
  5140. handleError();
  5141. };
  5142. // executes when a version change transaction cannot complete due to other active transactions
  5143. request.onblocked = function (event) {
  5144. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5145. handleError();
  5146. };
  5147. // DB has been opened successfully
  5148. request.onsuccess = function (event) {
  5149. _this.db = request.result;
  5150. successCallback();
  5151. };
  5152. // Initialization of the DB. Creating Scenes & Textures stores
  5153. request.onupgradeneeded = function (event) {
  5154. _this.db = (event.target).result;
  5155. try {
  5156. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5157. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5158. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5159. }
  5160. catch (ex) {
  5161. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5162. handleError();
  5163. }
  5164. };
  5165. }
  5166. else {
  5167. if (successCallback)
  5168. successCallback();
  5169. }
  5170. }
  5171. };
  5172. Database.prototype.loadImageFromDB = function (url, image) {
  5173. var _this = this;
  5174. var completeURL = Database.ReturnFullUrlLocation(url);
  5175. var saveAndLoadImage = function () {
  5176. if (!_this.hasReachedQuota && _this.db !== null) {
  5177. // the texture is not yet in the DB, let's try to save it
  5178. _this._saveImageIntoDBAsync(completeURL, image);
  5179. }
  5180. else {
  5181. image.src = url;
  5182. }
  5183. };
  5184. if (!this.mustUpdateRessources) {
  5185. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5186. }
  5187. else {
  5188. saveAndLoadImage();
  5189. }
  5190. };
  5191. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5192. if (this.isSupported && this.db !== null) {
  5193. var texture;
  5194. var transaction = this.db.transaction(["textures"]);
  5195. transaction.onabort = function (event) {
  5196. image.src = url;
  5197. };
  5198. transaction.oncomplete = function (event) {
  5199. var blobTextureURL;
  5200. if (texture) {
  5201. var URL = window.URL || window.webkitURL;
  5202. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5203. image.onerror = function () {
  5204. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5205. image.src = url;
  5206. };
  5207. image.src = blobTextureURL;
  5208. }
  5209. else {
  5210. notInDBCallback();
  5211. }
  5212. };
  5213. var getRequest = transaction.objectStore("textures").get(url);
  5214. getRequest.onsuccess = function (event) {
  5215. texture = (event.target).result;
  5216. };
  5217. getRequest.onerror = function (event) {
  5218. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5219. image.src = url;
  5220. };
  5221. }
  5222. else {
  5223. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5224. image.src = url;
  5225. }
  5226. };
  5227. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5228. var _this = this;
  5229. if (this.isSupported) {
  5230. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5231. var generateBlobUrl = function () {
  5232. var blobTextureURL;
  5233. if (blob) {
  5234. var URL = window.URL || window.webkitURL;
  5235. try {
  5236. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5237. }
  5238. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5239. catch (ex) {
  5240. blobTextureURL = URL.createObjectURL(blob);
  5241. }
  5242. }
  5243. image.src = blobTextureURL;
  5244. };
  5245. if (Database.IsUASupportingBlobStorage) {
  5246. var xhr = new XMLHttpRequest(), blob;
  5247. xhr.open("GET", url, true);
  5248. xhr.responseType = "blob";
  5249. xhr.addEventListener("load", function () {
  5250. if (xhr.status === 200) {
  5251. // Blob as response (XHR2)
  5252. blob = xhr.response;
  5253. var transaction = _this.db.transaction(["textures"], "readwrite");
  5254. // the transaction could abort because of a QuotaExceededError error
  5255. transaction.onabort = function (event) {
  5256. try {
  5257. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5258. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5259. _this.hasReachedQuota = true;
  5260. }
  5261. }
  5262. catch (ex) { }
  5263. generateBlobUrl();
  5264. };
  5265. transaction.oncomplete = function (event) {
  5266. generateBlobUrl();
  5267. };
  5268. var newTexture = { textureUrl: url, data: blob };
  5269. try {
  5270. // Put the blob into the dabase
  5271. var addRequest = transaction.objectStore("textures").put(newTexture);
  5272. addRequest.onsuccess = function (event) {
  5273. };
  5274. addRequest.onerror = function (event) {
  5275. generateBlobUrl();
  5276. };
  5277. }
  5278. catch (ex) {
  5279. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5280. if (ex.code === 25) {
  5281. Database.IsUASupportingBlobStorage = false;
  5282. }
  5283. image.src = url;
  5284. }
  5285. }
  5286. else {
  5287. image.src = url;
  5288. }
  5289. }, false);
  5290. xhr.addEventListener("error", function (event) {
  5291. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5292. image.src = url;
  5293. }, false);
  5294. xhr.send();
  5295. }
  5296. else {
  5297. image.src = url;
  5298. }
  5299. }
  5300. else {
  5301. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5302. image.src = url;
  5303. }
  5304. };
  5305. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5306. var _this = this;
  5307. var updateVersion = function (event) {
  5308. // the version is not yet in the DB or we need to update it
  5309. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5310. };
  5311. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5312. };
  5313. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5314. var _this = this;
  5315. if (this.isSupported) {
  5316. var version;
  5317. try {
  5318. var transaction = this.db.transaction(["versions"]);
  5319. transaction.oncomplete = function (event) {
  5320. if (version) {
  5321. // If the version in the JSON file is > than the version in DB
  5322. if (_this.manifestVersionFound > version.data) {
  5323. _this.mustUpdateRessources = true;
  5324. updateInDBCallback();
  5325. }
  5326. else {
  5327. callback(version.data);
  5328. }
  5329. }
  5330. else {
  5331. _this.mustUpdateRessources = true;
  5332. updateInDBCallback();
  5333. }
  5334. };
  5335. transaction.onabort = function (event) {
  5336. callback(-1);
  5337. };
  5338. var getRequest = transaction.objectStore("versions").get(url);
  5339. getRequest.onsuccess = function (event) {
  5340. version = (event.target).result;
  5341. };
  5342. getRequest.onerror = function (event) {
  5343. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5344. callback(-1);
  5345. };
  5346. }
  5347. catch (ex) {
  5348. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5349. callback(-1);
  5350. }
  5351. }
  5352. else {
  5353. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5354. callback(-1);
  5355. }
  5356. };
  5357. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5358. var _this = this;
  5359. if (this.isSupported && !this.hasReachedQuota) {
  5360. try {
  5361. // Open a transaction to the database
  5362. var transaction = this.db.transaction(["versions"], "readwrite");
  5363. // the transaction could abort because of a QuotaExceededError error
  5364. transaction.onabort = function (event) {
  5365. try {
  5366. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5367. _this.hasReachedQuota = true;
  5368. }
  5369. }
  5370. catch (ex) { }
  5371. callback(-1);
  5372. };
  5373. transaction.oncomplete = function (event) {
  5374. callback(_this.manifestVersionFound);
  5375. };
  5376. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5377. // Put the scene into the database
  5378. var addRequest = transaction.objectStore("versions").put(newVersion);
  5379. addRequest.onsuccess = function (event) {
  5380. };
  5381. addRequest.onerror = function (event) {
  5382. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5383. };
  5384. }
  5385. catch (ex) {
  5386. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5387. callback(-1);
  5388. }
  5389. }
  5390. else {
  5391. callback(-1);
  5392. }
  5393. };
  5394. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5395. var _this = this;
  5396. var completeUrl = Database.ReturnFullUrlLocation(url);
  5397. var saveAndLoadFile = function (event) {
  5398. // the scene is not yet in the DB, let's try to save it
  5399. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5400. };
  5401. this._checkVersionFromDB(completeUrl, function (version) {
  5402. if (version !== -1) {
  5403. if (!_this.mustUpdateRessources) {
  5404. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5405. }
  5406. else {
  5407. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5408. }
  5409. }
  5410. else {
  5411. errorCallback();
  5412. }
  5413. });
  5414. };
  5415. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5416. if (this.isSupported) {
  5417. var targetStore;
  5418. if (url.indexOf(".babylon") !== -1) {
  5419. targetStore = "scenes";
  5420. }
  5421. else {
  5422. targetStore = "textures";
  5423. }
  5424. var file;
  5425. var transaction = this.db.transaction([targetStore]);
  5426. transaction.oncomplete = function (event) {
  5427. if (file) {
  5428. callback(file.data);
  5429. }
  5430. else {
  5431. notInDBCallback();
  5432. }
  5433. };
  5434. transaction.onabort = function (event) {
  5435. notInDBCallback();
  5436. };
  5437. var getRequest = transaction.objectStore(targetStore).get(url);
  5438. getRequest.onsuccess = function (event) {
  5439. file = (event.target).result;
  5440. };
  5441. getRequest.onerror = function (event) {
  5442. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5443. notInDBCallback();
  5444. };
  5445. }
  5446. else {
  5447. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5448. callback();
  5449. }
  5450. };
  5451. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5452. var _this = this;
  5453. if (this.isSupported) {
  5454. var targetStore;
  5455. if (url.indexOf(".babylon") !== -1) {
  5456. targetStore = "scenes";
  5457. }
  5458. else {
  5459. targetStore = "textures";
  5460. }
  5461. // Create XHR
  5462. var xhr = new XMLHttpRequest(), fileData;
  5463. xhr.open("GET", url, true);
  5464. if (useArrayBuffer) {
  5465. xhr.responseType = "arraybuffer";
  5466. }
  5467. xhr.onprogress = progressCallback;
  5468. xhr.addEventListener("load", function () {
  5469. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5470. // Blob as response (XHR2)
  5471. //fileData = xhr.responseText;
  5472. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5473. if (!_this.hasReachedQuota) {
  5474. // Open a transaction to the database
  5475. var transaction = _this.db.transaction([targetStore], "readwrite");
  5476. // the transaction could abort because of a QuotaExceededError error
  5477. transaction.onabort = function (event) {
  5478. try {
  5479. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5480. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5481. _this.hasReachedQuota = true;
  5482. }
  5483. }
  5484. catch (ex) { }
  5485. callback(fileData);
  5486. };
  5487. transaction.oncomplete = function (event) {
  5488. callback(fileData);
  5489. };
  5490. var newFile;
  5491. if (targetStore === "scenes") {
  5492. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5493. }
  5494. else {
  5495. newFile = { textureUrl: url, data: fileData };
  5496. }
  5497. try {
  5498. // Put the scene into the database
  5499. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5500. addRequest.onsuccess = function (event) {
  5501. };
  5502. addRequest.onerror = function (event) {
  5503. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5504. };
  5505. }
  5506. catch (ex) {
  5507. callback(fileData);
  5508. }
  5509. }
  5510. else {
  5511. callback(fileData);
  5512. }
  5513. }
  5514. else {
  5515. callback();
  5516. }
  5517. }, false);
  5518. xhr.addEventListener("error", function (event) {
  5519. BABYLON.Tools.Error("error on XHR request.");
  5520. callback();
  5521. }, false);
  5522. xhr.send();
  5523. }
  5524. else {
  5525. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5526. callback();
  5527. }
  5528. };
  5529. return Database;
  5530. }());
  5531. Database.IsUASupportingBlobStorage = true;
  5532. Database.IDBStorageEnabled = true;
  5533. Database.parseURL = function (url) {
  5534. var a = document.createElement('a');
  5535. a.href = url;
  5536. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5537. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5538. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5539. return absLocation;
  5540. };
  5541. Database.ReturnFullUrlLocation = function (url) {
  5542. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5543. return (Database.parseURL(window.location.href) + url);
  5544. }
  5545. else {
  5546. return url;
  5547. }
  5548. };
  5549. BABYLON.Database = Database;
  5550. })(BABYLON || (BABYLON = {}));
  5551. //# sourceMappingURL=babylon.database.js.map
  5552. var BABYLON;
  5553. (function (BABYLON) {
  5554. var Internals;
  5555. (function (Internals) {
  5556. /*
  5557. * Based on jsTGALoader - Javascript loader for TGA file
  5558. * By Vincent Thibault
  5559. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5560. */
  5561. var TGATools = (function () {
  5562. function TGATools() {
  5563. }
  5564. TGATools.GetTGAHeader = function (data) {
  5565. var offset = 0;
  5566. var header = {
  5567. id_length: data[offset++],
  5568. colormap_type: data[offset++],
  5569. image_type: data[offset++],
  5570. colormap_index: data[offset++] | data[offset++] << 8,
  5571. colormap_length: data[offset++] | data[offset++] << 8,
  5572. colormap_size: data[offset++],
  5573. origin: [
  5574. data[offset++] | data[offset++] << 8,
  5575. data[offset++] | data[offset++] << 8
  5576. ],
  5577. width: data[offset++] | data[offset++] << 8,
  5578. height: data[offset++] | data[offset++] << 8,
  5579. pixel_size: data[offset++],
  5580. flags: data[offset++]
  5581. };
  5582. return header;
  5583. };
  5584. TGATools.UploadContent = function (gl, data) {
  5585. // Not enough data to contain header ?
  5586. if (data.length < 19) {
  5587. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5588. return;
  5589. }
  5590. // Read Header
  5591. var offset = 18;
  5592. var header = TGATools.GetTGAHeader(data);
  5593. // Assume it's a valid Targa file.
  5594. if (header.id_length + offset > data.length) {
  5595. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5596. return;
  5597. }
  5598. // Skip not needed data
  5599. offset += header.id_length;
  5600. var use_rle = false;
  5601. var use_pal = false;
  5602. var use_rgb = false;
  5603. var use_grey = false;
  5604. // Get some informations.
  5605. switch (header.image_type) {
  5606. case TGATools._TYPE_RLE_INDEXED:
  5607. use_rle = true;
  5608. case TGATools._TYPE_INDEXED:
  5609. use_pal = true;
  5610. break;
  5611. case TGATools._TYPE_RLE_RGB:
  5612. use_rle = true;
  5613. case TGATools._TYPE_RGB:
  5614. use_rgb = true;
  5615. break;
  5616. case TGATools._TYPE_RLE_GREY:
  5617. use_rle = true;
  5618. case TGATools._TYPE_GREY:
  5619. use_grey = true;
  5620. break;
  5621. }
  5622. var pixel_data;
  5623. var numAlphaBits = header.flags & 0xf;
  5624. var pixel_size = header.pixel_size >> 3;
  5625. var pixel_total = header.width * header.height * pixel_size;
  5626. // Read palettes
  5627. var palettes;
  5628. if (use_pal) {
  5629. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5630. }
  5631. // Read LRE
  5632. if (use_rle) {
  5633. pixel_data = new Uint8Array(pixel_total);
  5634. var c, count, i;
  5635. var localOffset = 0;
  5636. var pixels = new Uint8Array(pixel_size);
  5637. while (offset < pixel_total && localOffset < pixel_total) {
  5638. c = data[offset++];
  5639. count = (c & 0x7f) + 1;
  5640. // RLE pixels
  5641. if (c & 0x80) {
  5642. // Bind pixel tmp array
  5643. for (i = 0; i < pixel_size; ++i) {
  5644. pixels[i] = data[offset++];
  5645. }
  5646. // Copy pixel array
  5647. for (i = 0; i < count; ++i) {
  5648. pixel_data.set(pixels, localOffset + i * pixel_size);
  5649. }
  5650. localOffset += pixel_size * count;
  5651. }
  5652. else {
  5653. count *= pixel_size;
  5654. for (i = 0; i < count; ++i) {
  5655. pixel_data[localOffset + i] = data[offset++];
  5656. }
  5657. localOffset += count;
  5658. }
  5659. }
  5660. }
  5661. else {
  5662. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5663. }
  5664. // Load to texture
  5665. var x_start, y_start, x_step, y_step, y_end, x_end;
  5666. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5667. default:
  5668. case TGATools._ORIGIN_UL:
  5669. x_start = 0;
  5670. x_step = 1;
  5671. x_end = header.width;
  5672. y_start = 0;
  5673. y_step = 1;
  5674. y_end = header.height;
  5675. break;
  5676. case TGATools._ORIGIN_BL:
  5677. x_start = 0;
  5678. x_step = 1;
  5679. x_end = header.width;
  5680. y_start = header.height - 1;
  5681. y_step = -1;
  5682. y_end = -1;
  5683. break;
  5684. case TGATools._ORIGIN_UR:
  5685. x_start = header.width - 1;
  5686. x_step = -1;
  5687. x_end = -1;
  5688. y_start = 0;
  5689. y_step = 1;
  5690. y_end = header.height;
  5691. break;
  5692. case TGATools._ORIGIN_BR:
  5693. x_start = header.width - 1;
  5694. x_step = -1;
  5695. x_end = -1;
  5696. y_start = header.height - 1;
  5697. y_step = -1;
  5698. y_end = -1;
  5699. break;
  5700. }
  5701. // Load the specify method
  5702. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5703. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5704. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5705. };
  5706. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5707. var image = pixel_data, colormap = palettes;
  5708. var width = header.width, height = header.height;
  5709. var color, i = 0, x, y;
  5710. var imageData = new Uint8Array(width * height * 4);
  5711. for (y = y_start; y !== y_end; y += y_step) {
  5712. for (x = x_start; x !== x_end; x += x_step, i++) {
  5713. color = image[i];
  5714. imageData[(x + width * y) * 4 + 3] = 255;
  5715. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5716. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5717. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5718. }
  5719. }
  5720. return imageData;
  5721. };
  5722. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5723. var image = pixel_data;
  5724. var width = header.width, height = header.height;
  5725. var color, i = 0, x, y;
  5726. var imageData = new Uint8Array(width * height * 4);
  5727. for (y = y_start; y !== y_end; y += y_step) {
  5728. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5729. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5730. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5731. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5732. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5733. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5734. }
  5735. }
  5736. return imageData;
  5737. };
  5738. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5739. var image = pixel_data;
  5740. var width = header.width, height = header.height;
  5741. var i = 0, x, y;
  5742. var imageData = new Uint8Array(width * height * 4);
  5743. for (y = y_start; y !== y_end; y += y_step) {
  5744. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5745. imageData[(x + width * y) * 4 + 3] = 255;
  5746. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5747. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5748. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5749. }
  5750. }
  5751. return imageData;
  5752. };
  5753. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5754. var image = pixel_data;
  5755. var width = header.width, height = header.height;
  5756. var i = 0, x, y;
  5757. var imageData = new Uint8Array(width * height * 4);
  5758. for (y = y_start; y !== y_end; y += y_step) {
  5759. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5760. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5761. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5762. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5763. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5764. }
  5765. }
  5766. return imageData;
  5767. };
  5768. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5769. var image = pixel_data;
  5770. var width = header.width, height = header.height;
  5771. var color, i = 0, x, y;
  5772. var imageData = new Uint8Array(width * height * 4);
  5773. for (y = y_start; y !== y_end; y += y_step) {
  5774. for (x = x_start; x !== x_end; x += x_step, i++) {
  5775. color = image[i];
  5776. imageData[(x + width * y) * 4 + 0] = color;
  5777. imageData[(x + width * y) * 4 + 1] = color;
  5778. imageData[(x + width * y) * 4 + 2] = color;
  5779. imageData[(x + width * y) * 4 + 3] = 255;
  5780. }
  5781. }
  5782. return imageData;
  5783. };
  5784. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5785. var image = pixel_data;
  5786. var width = header.width, height = header.height;
  5787. var i = 0, x, y;
  5788. var imageData = new Uint8Array(width * height * 4);
  5789. for (y = y_start; y !== y_end; y += y_step) {
  5790. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5791. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5792. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5793. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5794. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5795. }
  5796. }
  5797. return imageData;
  5798. };
  5799. return TGATools;
  5800. }());
  5801. TGATools._TYPE_NO_DATA = 0;
  5802. TGATools._TYPE_INDEXED = 1;
  5803. TGATools._TYPE_RGB = 2;
  5804. TGATools._TYPE_GREY = 3;
  5805. TGATools._TYPE_RLE_INDEXED = 9;
  5806. TGATools._TYPE_RLE_RGB = 10;
  5807. TGATools._TYPE_RLE_GREY = 11;
  5808. TGATools._ORIGIN_MASK = 0x30;
  5809. TGATools._ORIGIN_SHIFT = 0x04;
  5810. TGATools._ORIGIN_BL = 0x00;
  5811. TGATools._ORIGIN_BR = 0x01;
  5812. TGATools._ORIGIN_UL = 0x02;
  5813. TGATools._ORIGIN_UR = 0x03;
  5814. Internals.TGATools = TGATools;
  5815. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5816. })(BABYLON || (BABYLON = {}));
  5817. //# sourceMappingURL=babylon.tga.js.map
  5818. var BABYLON;
  5819. (function (BABYLON) {
  5820. var SmartArray = (function () {
  5821. function SmartArray(capacity) {
  5822. this.length = 0;
  5823. this._duplicateId = 0;
  5824. this.data = new Array(capacity);
  5825. this._id = SmartArray._GlobalId++;
  5826. }
  5827. SmartArray.prototype.push = function (value) {
  5828. this.data[this.length++] = value;
  5829. if (this.length > this.data.length) {
  5830. this.data.length *= 2;
  5831. }
  5832. if (!value.__smartArrayFlags) {
  5833. value.__smartArrayFlags = {};
  5834. }
  5835. value.__smartArrayFlags[this._id] = this._duplicateId;
  5836. };
  5837. SmartArray.prototype.forEach = function (func) {
  5838. for (var index = 0; index < this.length; index++) {
  5839. func(this.data[index]);
  5840. }
  5841. };
  5842. SmartArray.prototype.pushNoDuplicate = function (value) {
  5843. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5844. return false;
  5845. }
  5846. this.push(value);
  5847. return true;
  5848. };
  5849. SmartArray.prototype.sort = function (compareFn) {
  5850. this.data.sort(compareFn);
  5851. };
  5852. SmartArray.prototype.reset = function () {
  5853. this.length = 0;
  5854. this._duplicateId++;
  5855. };
  5856. SmartArray.prototype.dispose = function () {
  5857. this.reset();
  5858. this.data.length = 0;
  5859. };
  5860. SmartArray.prototype.concat = function (array) {
  5861. if (array.length === 0) {
  5862. return;
  5863. }
  5864. if (this.length + array.length > this.data.length) {
  5865. this.data.length = (this.length + array.length) * 2;
  5866. }
  5867. for (var index = 0; index < array.length; index++) {
  5868. this.data[this.length++] = (array.data || array)[index];
  5869. }
  5870. };
  5871. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5872. if (array.length === 0) {
  5873. return;
  5874. }
  5875. if (this.length + array.length > this.data.length) {
  5876. this.data.length = (this.length + array.length) * 2;
  5877. }
  5878. for (var index = 0; index < array.length; index++) {
  5879. var item = (array.data || array)[index];
  5880. this.pushNoDuplicate(item);
  5881. }
  5882. };
  5883. SmartArray.prototype.indexOf = function (value) {
  5884. var position = this.data.indexOf(value);
  5885. if (position >= this.length) {
  5886. return -1;
  5887. }
  5888. return position;
  5889. };
  5890. SmartArray.prototype.contains = function (value) {
  5891. return this.data.indexOf(value) !== -1;
  5892. };
  5893. return SmartArray;
  5894. }());
  5895. // Statics
  5896. SmartArray._GlobalId = 0;
  5897. BABYLON.SmartArray = SmartArray;
  5898. })(BABYLON || (BABYLON = {}));
  5899. //# sourceMappingURL=babylon.smartArray.js.map
  5900. var BABYLON;
  5901. (function (BABYLON) {
  5902. /**
  5903. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5904. * The underlying implementation relies on an associative array to ensure the best performances.
  5905. * The value can be anything including 'null' but except 'undefined'
  5906. */
  5907. var StringDictionary = (function () {
  5908. function StringDictionary() {
  5909. this._count = 0;
  5910. this._data = {};
  5911. }
  5912. /**
  5913. * This will clear this dictionary and copy the content from the 'source' one.
  5914. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5915. * @param source the dictionary to take the content from and copy to this dictionary
  5916. */
  5917. StringDictionary.prototype.copyFrom = function (source) {
  5918. var _this = this;
  5919. this.clear();
  5920. source.forEach(function (t, v) { return _this.add(t, v); });
  5921. };
  5922. /**
  5923. * Get a value based from its key
  5924. * @param key the given key to get the matching value from
  5925. * @return the value if found, otherwise undefined is returned
  5926. */
  5927. StringDictionary.prototype.get = function (key) {
  5928. var val = this._data[key];
  5929. if (val !== undefined) {
  5930. return val;
  5931. }
  5932. return undefined;
  5933. };
  5934. /**
  5935. * Get a value from its key or add it if it doesn't exist.
  5936. * This method will ensure you that a given key/data will be present in the dictionary.
  5937. * @param key the given key to get the matching value from
  5938. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5939. * The factory will only be invoked if there's no data for the given key.
  5940. * @return the value corresponding to the key.
  5941. */
  5942. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5943. var val = this.get(key);
  5944. if (val !== undefined) {
  5945. return val;
  5946. }
  5947. val = factory(key);
  5948. if (val) {
  5949. this.add(key, val);
  5950. }
  5951. return val;
  5952. };
  5953. /**
  5954. * Get a value from its key if present in the dictionary otherwise add it
  5955. * @param key the key to get the value from
  5956. * @param val if there's no such key/value pair in the dictionary add it with this value
  5957. * @return the value corresponding to the key
  5958. */
  5959. StringDictionary.prototype.getOrAdd = function (key, val) {
  5960. var curVal = this.get(key);
  5961. if (curVal !== undefined) {
  5962. return curVal;
  5963. }
  5964. this.add(key, val);
  5965. return val;
  5966. };
  5967. /**
  5968. * Check if there's a given key in the dictionary
  5969. * @param key the key to check for
  5970. * @return true if the key is present, false otherwise
  5971. */
  5972. StringDictionary.prototype.contains = function (key) {
  5973. return this._data[key] !== undefined;
  5974. };
  5975. /**
  5976. * Add a new key and its corresponding value
  5977. * @param key the key to add
  5978. * @param value the value corresponding to the key
  5979. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  5980. */
  5981. StringDictionary.prototype.add = function (key, value) {
  5982. if (this._data[key] !== undefined) {
  5983. return false;
  5984. }
  5985. this._data[key] = value;
  5986. ++this._count;
  5987. return true;
  5988. };
  5989. StringDictionary.prototype.set = function (key, value) {
  5990. if (this._data[key] === undefined) {
  5991. return false;
  5992. }
  5993. this._data[key] = value;
  5994. return true;
  5995. };
  5996. /**
  5997. * Get the element of the given key and remove it from the dictionary
  5998. * @param key
  5999. */
  6000. StringDictionary.prototype.getAndRemove = function (key) {
  6001. var val = this.get(key);
  6002. if (val !== undefined) {
  6003. delete this._data[key];
  6004. --this._count;
  6005. return val;
  6006. }
  6007. return null;
  6008. };
  6009. /**
  6010. * Remove a key/value from the dictionary.
  6011. * @param key the key to remove
  6012. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  6013. */
  6014. StringDictionary.prototype.remove = function (key) {
  6015. if (this.contains(key)) {
  6016. delete this._data[key];
  6017. --this._count;
  6018. return true;
  6019. }
  6020. return false;
  6021. };
  6022. /**
  6023. * Clear the whole content of the dictionary
  6024. */
  6025. StringDictionary.prototype.clear = function () {
  6026. this._data = {};
  6027. this._count = 0;
  6028. };
  6029. Object.defineProperty(StringDictionary.prototype, "count", {
  6030. get: function () {
  6031. return this._count;
  6032. },
  6033. enumerable: true,
  6034. configurable: true
  6035. });
  6036. /**
  6037. * Execute a callback on each key/val of the dictionary.
  6038. * Note that you can remove any element in this dictionary in the callback implementation
  6039. * @param callback the callback to execute on a given key/value pair
  6040. */
  6041. StringDictionary.prototype.forEach = function (callback) {
  6042. for (var cur in this._data) {
  6043. var val = this._data[cur];
  6044. callback(cur, val);
  6045. }
  6046. };
  6047. /**
  6048. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  6049. * If the callback returns null or undefined the method will iterate to the next key/value pair
  6050. * Note that you can remove any element in this dictionary in the callback implementation
  6051. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  6052. */
  6053. StringDictionary.prototype.first = function (callback) {
  6054. for (var cur in this._data) {
  6055. var val = this._data[cur];
  6056. var res = callback(cur, val);
  6057. if (res) {
  6058. return res;
  6059. }
  6060. }
  6061. return null;
  6062. };
  6063. return StringDictionary;
  6064. }());
  6065. BABYLON.StringDictionary = StringDictionary;
  6066. })(BABYLON || (BABYLON = {}));
  6067. //# sourceMappingURL=babylon.stringDictionary.js.map
  6068. var BABYLON;
  6069. (function (BABYLON) {
  6070. // Screenshots
  6071. var screenshotCanvas;
  6072. var cloneValue = function (source, destinationObject) {
  6073. if (!source)
  6074. return null;
  6075. if (source instanceof BABYLON.Mesh) {
  6076. return null;
  6077. }
  6078. if (source instanceof BABYLON.SubMesh) {
  6079. return source.clone(destinationObject);
  6080. }
  6081. else if (source.clone) {
  6082. return source.clone();
  6083. }
  6084. return null;
  6085. };
  6086. var Tools = (function () {
  6087. function Tools() {
  6088. }
  6089. ;
  6090. Tools.Instantiate = function (className) {
  6091. var arr = className.split(".");
  6092. var fn = (window || this);
  6093. for (var i = 0, len = arr.length; i < len; i++) {
  6094. fn = fn[arr[i]];
  6095. }
  6096. if (typeof fn !== "function") {
  6097. return null;
  6098. }
  6099. return fn;
  6100. };
  6101. Tools.SetImmediate = function (action) {
  6102. if (window.setImmediate) {
  6103. window.setImmediate(action);
  6104. }
  6105. else {
  6106. setTimeout(action, 1);
  6107. }
  6108. };
  6109. Tools.IsExponentOfTwo = function (value) {
  6110. var count = 1;
  6111. do {
  6112. count *= 2;
  6113. } while (count < value);
  6114. return count === value;
  6115. };
  6116. Tools.GetExponentOfTwo = function (value, max) {
  6117. var count = 1;
  6118. do {
  6119. count *= 2;
  6120. } while (count < value);
  6121. if (count > max)
  6122. count = max;
  6123. return count;
  6124. };
  6125. Tools.GetFilename = function (path) {
  6126. var index = path.lastIndexOf("/");
  6127. if (index < 0)
  6128. return path;
  6129. return path.substring(index + 1);
  6130. };
  6131. Tools.GetDOMTextContent = function (element) {
  6132. var result = "";
  6133. var child = element.firstChild;
  6134. while (child) {
  6135. if (child.nodeType === 3) {
  6136. result += child.textContent;
  6137. }
  6138. child = child.nextSibling;
  6139. }
  6140. return result;
  6141. };
  6142. Tools.ToDegrees = function (angle) {
  6143. return angle * 180 / Math.PI;
  6144. };
  6145. Tools.ToRadians = function (angle) {
  6146. return angle * Math.PI / 180;
  6147. };
  6148. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6149. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6150. var output = "";
  6151. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6152. var i = 0;
  6153. var bytes = new Uint8Array(buffer);
  6154. while (i < bytes.length) {
  6155. chr1 = bytes[i++];
  6156. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6157. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6158. enc1 = chr1 >> 2;
  6159. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6160. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6161. enc4 = chr3 & 63;
  6162. if (isNaN(chr2)) {
  6163. enc3 = enc4 = 64;
  6164. }
  6165. else if (isNaN(chr3)) {
  6166. enc4 = 64;
  6167. }
  6168. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6169. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6170. }
  6171. return "data:image/png;base64," + output;
  6172. };
  6173. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6174. if (bias === void 0) { bias = null; }
  6175. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6176. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6177. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6178. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6179. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6180. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6181. }
  6182. if (bias) {
  6183. minimum.x -= minimum.x * bias.x + bias.y;
  6184. minimum.y -= minimum.y * bias.x + bias.y;
  6185. minimum.z -= minimum.z * bias.x + bias.y;
  6186. maximum.x += maximum.x * bias.x + bias.y;
  6187. maximum.y += maximum.y * bias.x + bias.y;
  6188. maximum.z += maximum.z * bias.x + bias.y;
  6189. }
  6190. return {
  6191. minimum: minimum,
  6192. maximum: maximum
  6193. };
  6194. };
  6195. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6196. if (bias === void 0) { bias = null; }
  6197. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6198. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6199. if (!stride) {
  6200. stride = 3;
  6201. }
  6202. for (var index = start; index < start + count; index++) {
  6203. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6204. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6205. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6206. }
  6207. if (bias) {
  6208. minimum.x -= minimum.x * bias.x + bias.y;
  6209. minimum.y -= minimum.y * bias.x + bias.y;
  6210. minimum.z -= minimum.z * bias.x + bias.y;
  6211. maximum.x += maximum.x * bias.x + bias.y;
  6212. maximum.y += maximum.y * bias.x + bias.y;
  6213. maximum.z += maximum.z * bias.x + bias.y;
  6214. }
  6215. return {
  6216. minimum: minimum,
  6217. maximum: maximum
  6218. };
  6219. };
  6220. Tools.Vector2ArrayFeeder = function (array) {
  6221. return function (index) {
  6222. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6223. var length = isFloatArray ? array.length / 2 : array.length;
  6224. if (index >= length) {
  6225. return null;
  6226. }
  6227. if (isFloatArray) {
  6228. var fa = array;
  6229. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6230. }
  6231. var a = array;
  6232. return a[index];
  6233. };
  6234. };
  6235. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6236. if (bias === void 0) { bias = null; }
  6237. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6238. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6239. var i = 0;
  6240. var cur = feeder(i++);
  6241. while (cur) {
  6242. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6243. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6244. cur = feeder(i++);
  6245. }
  6246. if (bias) {
  6247. minimum.x -= minimum.x * bias.x + bias.y;
  6248. minimum.y -= minimum.y * bias.x + bias.y;
  6249. maximum.x += maximum.x * bias.x + bias.y;
  6250. maximum.y += maximum.y * bias.x + bias.y;
  6251. }
  6252. return {
  6253. minimum: minimum,
  6254. maximum: maximum
  6255. };
  6256. };
  6257. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6258. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6259. return undefined;
  6260. return Array.isArray(obj) ? obj : [obj];
  6261. };
  6262. // Misc.
  6263. Tools.GetPointerPrefix = function () {
  6264. var eventPrefix = "pointer";
  6265. // Check if pointer events are supported
  6266. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6267. eventPrefix = "mouse";
  6268. }
  6269. return eventPrefix;
  6270. };
  6271. /**
  6272. * @param func - the function to be called
  6273. * @param requester - the object that will request the next frame. Falls back to window.
  6274. */
  6275. Tools.QueueNewFrame = function (func, requester) {
  6276. if (requester === void 0) { requester = window; }
  6277. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6278. /*if(requester.isPresenting) {
  6279. return;
  6280. } else*/ if (requester.requestAnimationFrame)
  6281. requester.requestAnimationFrame(func);
  6282. else if (requester.msRequestAnimationFrame)
  6283. requester.msRequestAnimationFrame(func);
  6284. else if (requester.webkitRequestAnimationFrame)
  6285. requester.webkitRequestAnimationFrame(func);
  6286. else if (requester.mozRequestAnimationFrame)
  6287. requester.mozRequestAnimationFrame(func);
  6288. else if (requester.oRequestAnimationFrame)
  6289. requester.oRequestAnimationFrame(func);
  6290. else {
  6291. window.setTimeout(func, 16);
  6292. }
  6293. };
  6294. Tools.RequestFullscreen = function (element) {
  6295. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6296. if (!requestFunction)
  6297. return;
  6298. requestFunction.call(element);
  6299. };
  6300. Tools.ExitFullscreen = function () {
  6301. if (document.exitFullscreen) {
  6302. document.exitFullscreen();
  6303. }
  6304. else if (document.mozCancelFullScreen) {
  6305. document.mozCancelFullScreen();
  6306. }
  6307. else if (document.webkitCancelFullScreen) {
  6308. document.webkitCancelFullScreen();
  6309. }
  6310. else if (document.msCancelFullScreen) {
  6311. document.msCancelFullScreen();
  6312. }
  6313. };
  6314. Tools.SetCorsBehavior = function (url, img) {
  6315. if (Tools.CorsBehavior) {
  6316. switch (typeof (Tools.CorsBehavior)) {
  6317. case "function":
  6318. var result = Tools.CorsBehavior(url);
  6319. if (result) {
  6320. img.crossOrigin = result;
  6321. }
  6322. break;
  6323. case "string":
  6324. default:
  6325. img.crossOrigin = Tools.CorsBehavior;
  6326. break;
  6327. }
  6328. }
  6329. };
  6330. // External files
  6331. Tools.CleanUrl = function (url) {
  6332. url = url.replace(/#/mg, "%23");
  6333. return url;
  6334. };
  6335. Tools.LoadImage = function (url, onload, onerror, database) {
  6336. if (url instanceof ArrayBuffer) {
  6337. url = Tools.EncodeArrayBufferTobase64(url);
  6338. }
  6339. url = Tools.CleanUrl(url);
  6340. var img = new Image();
  6341. if (url.substr(0, 5) !== "data:") {
  6342. Tools.SetCorsBehavior(url, img);
  6343. }
  6344. img.onload = function () {
  6345. onload(img);
  6346. };
  6347. img.onerror = function (err) {
  6348. Tools.Error("Error while trying to load image: " + url);
  6349. if (Tools.UseFallbackTexture) {
  6350. img.src = Tools.fallbackTexture;
  6351. onload(img);
  6352. }
  6353. else {
  6354. onerror();
  6355. }
  6356. };
  6357. var noIndexedDB = function () {
  6358. img.src = url;
  6359. };
  6360. var loadFromIndexedDB = function () {
  6361. database.loadImageFromDB(url, img);
  6362. };
  6363. //ANY database to do!
  6364. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6365. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6366. }
  6367. else {
  6368. if (url.indexOf("file:") === -1) {
  6369. noIndexedDB();
  6370. }
  6371. else {
  6372. var textureName = url.substring(5).toLowerCase();
  6373. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6374. try {
  6375. var blobURL;
  6376. try {
  6377. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6378. }
  6379. catch (ex) {
  6380. // Chrome doesn't support oneTimeOnly parameter
  6381. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6382. }
  6383. img.src = blobURL;
  6384. }
  6385. catch (e) {
  6386. img.src = null;
  6387. }
  6388. }
  6389. else {
  6390. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6391. img.src = Tools.fallbackTexture;
  6392. }
  6393. }
  6394. }
  6395. return img;
  6396. };
  6397. //ANY
  6398. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6399. url = Tools.CleanUrl(url);
  6400. var noIndexedDB = function () {
  6401. var request = new XMLHttpRequest();
  6402. var loadUrl = Tools.BaseUrl + url;
  6403. request.open('GET', loadUrl, true);
  6404. if (useArrayBuffer) {
  6405. request.responseType = "arraybuffer";
  6406. }
  6407. request.onprogress = progressCallBack;
  6408. request.onreadystatechange = function () {
  6409. if (request.readyState === 4) {
  6410. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6411. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6412. callback(!useArrayBuffer ? request.responseText : request.response);
  6413. }
  6414. else {
  6415. if (onError) {
  6416. onError();
  6417. }
  6418. else {
  6419. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6420. }
  6421. }
  6422. }
  6423. };
  6424. request.send(null);
  6425. };
  6426. var loadFromIndexedDB = function () {
  6427. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6428. };
  6429. if (url.indexOf("file:") !== -1) {
  6430. var fileName = url.substring(5).toLowerCase();
  6431. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6432. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6433. }
  6434. else {
  6435. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6436. }
  6437. }
  6438. else {
  6439. // Caching all files
  6440. if (database && database.enableSceneOffline) {
  6441. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6442. }
  6443. else {
  6444. noIndexedDB();
  6445. }
  6446. }
  6447. };
  6448. /**
  6449. * Load a script (identified by an url). When the url returns, the
  6450. * content of this file is added into a new script element, attached to the DOM (body element)
  6451. */
  6452. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6453. var head = document.getElementsByTagName('head')[0];
  6454. var script = document.createElement('script');
  6455. script.type = 'text/javascript';
  6456. script.src = scriptUrl;
  6457. var self = this;
  6458. script.onload = function () {
  6459. if (onSuccess) {
  6460. onSuccess();
  6461. }
  6462. };
  6463. script.onerror = function () {
  6464. if (onError) {
  6465. onError();
  6466. }
  6467. };
  6468. head.appendChild(script);
  6469. };
  6470. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6471. var reader = new FileReader();
  6472. reader.onload = function (e) {
  6473. //target doesn't have result from ts 1.3
  6474. callback(e.target['result']);
  6475. };
  6476. reader.onprogress = progressCallback;
  6477. reader.readAsDataURL(fileToLoad);
  6478. };
  6479. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6480. var reader = new FileReader();
  6481. reader.onerror = function (e) {
  6482. Tools.Log("Error while reading file: " + fileToLoad.name);
  6483. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6484. };
  6485. reader.onload = function (e) {
  6486. //target doesn't have result from ts 1.3
  6487. callback(e.target['result']);
  6488. };
  6489. reader.onprogress = progressCallBack;
  6490. if (!useArrayBuffer) {
  6491. // Asynchronous read
  6492. reader.readAsText(fileToLoad);
  6493. }
  6494. else {
  6495. reader.readAsArrayBuffer(fileToLoad);
  6496. }
  6497. };
  6498. //returns a downloadable url to a file content.
  6499. Tools.FileAsURL = function (content) {
  6500. var fileBlob = new Blob([content]);
  6501. var url = window.URL || window.webkitURL;
  6502. var link = url.createObjectURL(fileBlob);
  6503. return link;
  6504. };
  6505. // Misc.
  6506. Tools.Format = function (value, decimals) {
  6507. if (decimals === void 0) { decimals = 2; }
  6508. return value.toFixed(decimals);
  6509. };
  6510. Tools.CheckExtends = function (v, min, max) {
  6511. if (v.x < min.x)
  6512. min.x = v.x;
  6513. if (v.y < min.y)
  6514. min.y = v.y;
  6515. if (v.z < min.z)
  6516. min.z = v.z;
  6517. if (v.x > max.x)
  6518. max.x = v.x;
  6519. if (v.y > max.y)
  6520. max.y = v.y;
  6521. if (v.z > max.z)
  6522. max.z = v.z;
  6523. };
  6524. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6525. for (var prop in source) {
  6526. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6527. continue;
  6528. }
  6529. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6530. continue;
  6531. }
  6532. var sourceValue = source[prop];
  6533. var typeOfSourceValue = typeof sourceValue;
  6534. if (typeOfSourceValue === "function") {
  6535. continue;
  6536. }
  6537. if (typeOfSourceValue === "object") {
  6538. if (sourceValue instanceof Array) {
  6539. destination[prop] = [];
  6540. if (sourceValue.length > 0) {
  6541. if (typeof sourceValue[0] == "object") {
  6542. for (var index = 0; index < sourceValue.length; index++) {
  6543. var clonedValue = cloneValue(sourceValue[index], destination);
  6544. if (destination[prop].indexOf(clonedValue) === -1) {
  6545. destination[prop].push(clonedValue);
  6546. }
  6547. }
  6548. }
  6549. else {
  6550. destination[prop] = sourceValue.slice(0);
  6551. }
  6552. }
  6553. }
  6554. else {
  6555. destination[prop] = cloneValue(sourceValue, destination);
  6556. }
  6557. }
  6558. else {
  6559. destination[prop] = sourceValue;
  6560. }
  6561. }
  6562. };
  6563. Tools.IsEmpty = function (obj) {
  6564. for (var i in obj) {
  6565. return false;
  6566. }
  6567. return true;
  6568. };
  6569. Tools.RegisterTopRootEvents = function (events) {
  6570. for (var index = 0; index < events.length; index++) {
  6571. var event = events[index];
  6572. window.addEventListener(event.name, event.handler, false);
  6573. try {
  6574. if (window.parent) {
  6575. window.parent.addEventListener(event.name, event.handler, false);
  6576. }
  6577. }
  6578. catch (e) {
  6579. // Silently fails...
  6580. }
  6581. }
  6582. };
  6583. Tools.UnregisterTopRootEvents = function (events) {
  6584. for (var index = 0; index < events.length; index++) {
  6585. var event = events[index];
  6586. window.removeEventListener(event.name, event.handler);
  6587. try {
  6588. if (window.parent) {
  6589. window.parent.removeEventListener(event.name, event.handler);
  6590. }
  6591. }
  6592. catch (e) {
  6593. // Silently fails...
  6594. }
  6595. }
  6596. };
  6597. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6598. if (mimeType === void 0) { mimeType = "image/png"; }
  6599. // Read the contents of the framebuffer
  6600. var numberOfChannelsByLine = width * 4;
  6601. var halfHeight = height / 2;
  6602. //Reading datas from WebGL
  6603. var data = engine.readPixels(0, 0, width, height);
  6604. //To flip image on Y axis.
  6605. for (var i = 0; i < halfHeight; i++) {
  6606. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6607. var currentCell = j + i * numberOfChannelsByLine;
  6608. var targetLine = height - i - 1;
  6609. var targetCell = j + targetLine * numberOfChannelsByLine;
  6610. var temp = data[currentCell];
  6611. data[currentCell] = data[targetCell];
  6612. data[targetCell] = temp;
  6613. }
  6614. }
  6615. // Create a 2D canvas to store the result
  6616. if (!screenshotCanvas) {
  6617. screenshotCanvas = document.createElement('canvas');
  6618. }
  6619. screenshotCanvas.width = width;
  6620. screenshotCanvas.height = height;
  6621. var context = screenshotCanvas.getContext('2d');
  6622. // Copy the pixels to a 2D canvas
  6623. var imageData = context.createImageData(width, height);
  6624. var castData = (imageData.data);
  6625. castData.set(data);
  6626. context.putImageData(imageData, 0, 0);
  6627. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6628. };
  6629. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6630. if (mimeType === void 0) { mimeType = "image/png"; }
  6631. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6632. if (successCallback) {
  6633. successCallback(base64Image);
  6634. }
  6635. else {
  6636. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6637. if (("download" in document.createElement("a"))) {
  6638. var a = window.document.createElement("a");
  6639. a.href = base64Image;
  6640. var date = new Date();
  6641. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6642. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6643. window.document.body.appendChild(a);
  6644. a.addEventListener("click", function () {
  6645. a.parentElement.removeChild(a);
  6646. });
  6647. a.click();
  6648. //Or opening a new tab with the image if it is not possible to automatically start download.
  6649. }
  6650. else {
  6651. var newWindow = window.open("");
  6652. var img = newWindow.document.createElement("img");
  6653. img.src = base64Image;
  6654. newWindow.document.body.appendChild(img);
  6655. }
  6656. }
  6657. };
  6658. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6659. if (mimeType === void 0) { mimeType = "image/png"; }
  6660. var width;
  6661. var height;
  6662. // If a precision value is specified
  6663. if (size.precision) {
  6664. width = Math.round(engine.getRenderWidth() * size.precision);
  6665. height = Math.round(width / engine.getAspectRatio(camera));
  6666. }
  6667. else if (size.width && size.height) {
  6668. width = size.width;
  6669. height = size.height;
  6670. }
  6671. else if (size.width && !size.height) {
  6672. width = size.width;
  6673. height = Math.round(width / engine.getAspectRatio(camera));
  6674. }
  6675. else if (size.height && !size.width) {
  6676. height = size.height;
  6677. width = Math.round(height * engine.getAspectRatio(camera));
  6678. }
  6679. else if (!isNaN(size)) {
  6680. height = size;
  6681. width = size;
  6682. }
  6683. else {
  6684. Tools.Error("Invalid 'size' parameter !");
  6685. return;
  6686. }
  6687. if (!screenshotCanvas) {
  6688. screenshotCanvas = document.createElement('canvas');
  6689. }
  6690. screenshotCanvas.width = width;
  6691. screenshotCanvas.height = height;
  6692. var renderContext = screenshotCanvas.getContext("2d");
  6693. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6694. var newWidth = width;
  6695. var newHeight = newWidth / ratio;
  6696. if (newHeight > height) {
  6697. newHeight = height;
  6698. newWidth = newHeight * ratio;
  6699. }
  6700. var offsetX = Math.max(0, width - newWidth) / 2;
  6701. var offsetY = Math.max(0, height - newHeight) / 2;
  6702. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6703. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6704. };
  6705. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6706. if (mimeType === void 0) { mimeType = "image/png"; }
  6707. if (samples === void 0) { samples = 1; }
  6708. var width;
  6709. var height;
  6710. //If a precision value is specified
  6711. if (size.precision) {
  6712. width = Math.round(engine.getRenderWidth() * size.precision);
  6713. height = Math.round(width / engine.getAspectRatio(camera));
  6714. size = { width: width, height: height };
  6715. }
  6716. else if (size.width && size.height) {
  6717. width = size.width;
  6718. height = size.height;
  6719. }
  6720. else if (size.width && !size.height) {
  6721. width = size.width;
  6722. height = Math.round(width / engine.getAspectRatio(camera));
  6723. size = { width: width, height: height };
  6724. }
  6725. else if (size.height && !size.width) {
  6726. height = size.height;
  6727. width = Math.round(height * engine.getAspectRatio(camera));
  6728. size = { width: width, height: height };
  6729. }
  6730. else if (!isNaN(size)) {
  6731. height = size;
  6732. width = size;
  6733. }
  6734. else {
  6735. Tools.Error("Invalid 'size' parameter !");
  6736. return;
  6737. }
  6738. var scene = camera.getScene();
  6739. var previousCamera = null;
  6740. if (scene.activeCamera !== camera) {
  6741. previousCamera = scene.activeCamera;
  6742. scene.activeCamera = camera;
  6743. }
  6744. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6745. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6746. texture.renderList = scene.meshes;
  6747. texture.samples = samples;
  6748. texture.onAfterRenderObservable.add(function () {
  6749. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6750. });
  6751. scene.incrementRenderId();
  6752. scene.resetCachedMaterial();
  6753. texture.render(true);
  6754. texture.dispose();
  6755. if (previousCamera) {
  6756. scene.activeCamera = previousCamera;
  6757. }
  6758. camera.getProjectionMatrix(true); // Force cache refresh;
  6759. };
  6760. // XHR response validator for local file scenario
  6761. Tools.ValidateXHRData = function (xhr, dataType) {
  6762. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6763. if (dataType === void 0) { dataType = 7; }
  6764. try {
  6765. if (dataType & 1) {
  6766. if (xhr.responseText && xhr.responseText.length > 0) {
  6767. return true;
  6768. }
  6769. else if (dataType === 1) {
  6770. return false;
  6771. }
  6772. }
  6773. if (dataType & 2) {
  6774. // Check header width and height since there is no "TGA" magic number
  6775. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6776. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6777. return true;
  6778. }
  6779. else if (dataType === 2) {
  6780. return false;
  6781. }
  6782. }
  6783. if (dataType & 4) {
  6784. // Check for the "DDS" magic number
  6785. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6786. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6787. return true;
  6788. }
  6789. else {
  6790. return false;
  6791. }
  6792. }
  6793. }
  6794. catch (e) {
  6795. // Global protection
  6796. }
  6797. return false;
  6798. };
  6799. /**
  6800. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6801. * Be aware Math.random() could cause collisions, but:
  6802. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6803. */
  6804. Tools.RandomId = function () {
  6805. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6806. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6807. return v.toString(16);
  6808. });
  6809. };
  6810. Object.defineProperty(Tools, "NoneLogLevel", {
  6811. get: function () {
  6812. return Tools._NoneLogLevel;
  6813. },
  6814. enumerable: true,
  6815. configurable: true
  6816. });
  6817. Object.defineProperty(Tools, "MessageLogLevel", {
  6818. get: function () {
  6819. return Tools._MessageLogLevel;
  6820. },
  6821. enumerable: true,
  6822. configurable: true
  6823. });
  6824. Object.defineProperty(Tools, "WarningLogLevel", {
  6825. get: function () {
  6826. return Tools._WarningLogLevel;
  6827. },
  6828. enumerable: true,
  6829. configurable: true
  6830. });
  6831. Object.defineProperty(Tools, "ErrorLogLevel", {
  6832. get: function () {
  6833. return Tools._ErrorLogLevel;
  6834. },
  6835. enumerable: true,
  6836. configurable: true
  6837. });
  6838. Object.defineProperty(Tools, "AllLogLevel", {
  6839. get: function () {
  6840. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6841. },
  6842. enumerable: true,
  6843. configurable: true
  6844. });
  6845. Tools._AddLogEntry = function (entry) {
  6846. Tools._LogCache = entry + Tools._LogCache;
  6847. if (Tools.OnNewCacheEntry) {
  6848. Tools.OnNewCacheEntry(entry);
  6849. }
  6850. };
  6851. Tools._FormatMessage = function (message) {
  6852. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6853. var date = new Date();
  6854. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6855. };
  6856. Tools._LogDisabled = function (message) {
  6857. // nothing to do
  6858. };
  6859. Tools._LogEnabled = function (message) {
  6860. var formattedMessage = Tools._FormatMessage(message);
  6861. console.log("BJS - " + formattedMessage);
  6862. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6863. Tools._AddLogEntry(entry);
  6864. };
  6865. Tools._WarnDisabled = function (message) {
  6866. // nothing to do
  6867. };
  6868. Tools._WarnEnabled = function (message) {
  6869. var formattedMessage = Tools._FormatMessage(message);
  6870. console.warn("BJS - " + formattedMessage);
  6871. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6872. Tools._AddLogEntry(entry);
  6873. };
  6874. Tools._ErrorDisabled = function (message) {
  6875. // nothing to do
  6876. };
  6877. Tools._ErrorEnabled = function (message) {
  6878. Tools.errorsCount++;
  6879. var formattedMessage = Tools._FormatMessage(message);
  6880. console.error("BJS - " + formattedMessage);
  6881. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6882. Tools._AddLogEntry(entry);
  6883. };
  6884. Object.defineProperty(Tools, "LogCache", {
  6885. get: function () {
  6886. return Tools._LogCache;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Tools.ClearLogCache = function () {
  6892. Tools._LogCache = "";
  6893. Tools.errorsCount = 0;
  6894. };
  6895. Object.defineProperty(Tools, "LogLevels", {
  6896. set: function (level) {
  6897. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6898. Tools.Log = Tools._LogEnabled;
  6899. }
  6900. else {
  6901. Tools.Log = Tools._LogDisabled;
  6902. }
  6903. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6904. Tools.Warn = Tools._WarnEnabled;
  6905. }
  6906. else {
  6907. Tools.Warn = Tools._WarnDisabled;
  6908. }
  6909. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6910. Tools.Error = Tools._ErrorEnabled;
  6911. }
  6912. else {
  6913. Tools.Error = Tools._ErrorDisabled;
  6914. }
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6920. get: function () {
  6921. return Tools._PerformanceNoneLogLevel;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6927. get: function () {
  6928. return Tools._PerformanceUserMarkLogLevel;
  6929. },
  6930. enumerable: true,
  6931. configurable: true
  6932. });
  6933. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6934. get: function () {
  6935. return Tools._PerformanceConsoleLogLevel;
  6936. },
  6937. enumerable: true,
  6938. configurable: true
  6939. });
  6940. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6941. set: function (level) {
  6942. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6943. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6944. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6945. return;
  6946. }
  6947. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6948. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6949. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6950. return;
  6951. }
  6952. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6953. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6954. },
  6955. enumerable: true,
  6956. configurable: true
  6957. });
  6958. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6959. };
  6960. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6961. };
  6962. Tools._StartUserMark = function (counterName, condition) {
  6963. if (condition === void 0) { condition = true; }
  6964. if (!condition || !Tools._performance.mark) {
  6965. return;
  6966. }
  6967. Tools._performance.mark(counterName + "-Begin");
  6968. };
  6969. Tools._EndUserMark = function (counterName, condition) {
  6970. if (condition === void 0) { condition = true; }
  6971. if (!condition || !Tools._performance.mark) {
  6972. return;
  6973. }
  6974. Tools._performance.mark(counterName + "-End");
  6975. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6976. };
  6977. Tools._StartPerformanceConsole = function (counterName, condition) {
  6978. if (condition === void 0) { condition = true; }
  6979. if (!condition) {
  6980. return;
  6981. }
  6982. Tools._StartUserMark(counterName, condition);
  6983. if (console.time) {
  6984. console.time(counterName);
  6985. }
  6986. };
  6987. Tools._EndPerformanceConsole = function (counterName, condition) {
  6988. if (condition === void 0) { condition = true; }
  6989. if (!condition) {
  6990. return;
  6991. }
  6992. Tools._EndUserMark(counterName, condition);
  6993. if (console.time) {
  6994. console.timeEnd(counterName);
  6995. }
  6996. };
  6997. Object.defineProperty(Tools, "Now", {
  6998. get: function () {
  6999. if (window.performance && window.performance.now) {
  7000. return window.performance.now();
  7001. }
  7002. return new Date().getTime();
  7003. },
  7004. enumerable: true,
  7005. configurable: true
  7006. });
  7007. /**
  7008. * This method will return the name of the class used to create the instance of the given object.
  7009. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7010. * @param object the object to get the class name from
  7011. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7012. */
  7013. Tools.getClassName = function (object, isType) {
  7014. if (isType === void 0) { isType = false; }
  7015. var name = null;
  7016. if (!isType && object.getClassName) {
  7017. name = object.getClassName();
  7018. }
  7019. else {
  7020. if (object instanceof Object) {
  7021. var classObj = isType ? object : Object.getPrototypeOf(object);
  7022. name = classObj.constructor["__bjsclassName__"];
  7023. }
  7024. if (!name) {
  7025. name = typeof object;
  7026. }
  7027. }
  7028. return name;
  7029. };
  7030. Tools.first = function (array, predicate) {
  7031. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7032. var el = array_1[_i];
  7033. if (predicate(el)) {
  7034. return el;
  7035. }
  7036. }
  7037. };
  7038. /**
  7039. * This method will return the name of the full name of the class, including its owning module (if any).
  7040. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  7041. * @param object the object to get the class name from
  7042. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  7043. */
  7044. Tools.getFullClassName = function (object, isType) {
  7045. if (isType === void 0) { isType = false; }
  7046. var className = null;
  7047. var moduleName = null;
  7048. if (!isType && object.getClassName) {
  7049. className = object.getClassName();
  7050. }
  7051. else {
  7052. if (object instanceof Object) {
  7053. var classObj = isType ? object : Object.getPrototypeOf(object);
  7054. className = classObj.constructor["__bjsclassName__"];
  7055. moduleName = classObj.constructor["__bjsmoduleName__"];
  7056. }
  7057. if (!className) {
  7058. className = typeof object;
  7059. }
  7060. }
  7061. if (!className) {
  7062. return null;
  7063. }
  7064. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7065. };
  7066. /**
  7067. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  7068. * @param array
  7069. */
  7070. Tools.arrayOrStringFeeder = function (array) {
  7071. return function (index) {
  7072. if (index >= array.length) {
  7073. return null;
  7074. }
  7075. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7076. if (val && val.getHashCode) {
  7077. val = val.getHashCode();
  7078. }
  7079. if (typeof val === "string") {
  7080. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7081. }
  7082. return val;
  7083. };
  7084. };
  7085. /**
  7086. * Compute the hashCode of a stream of number
  7087. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7088. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7089. * @return the hash code computed
  7090. */
  7091. Tools.hashCodeFromStream = function (feeder) {
  7092. // Based from here: http://stackoverflow.com/a/7616484/802124
  7093. var hash = 0;
  7094. var index = 0;
  7095. var chr = feeder(index++);
  7096. while (chr != null) {
  7097. hash = ((hash << 5) - hash) + chr;
  7098. hash |= 0; // Convert to 32bit integer
  7099. chr = feeder(index++);
  7100. }
  7101. return hash;
  7102. };
  7103. return Tools;
  7104. }());
  7105. Tools.BaseUrl = "";
  7106. Tools.CorsBehavior = "anonymous";
  7107. Tools.UseFallbackTexture = true;
  7108. // Used in case of a texture loading problem
  7109. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  7110. // Logs
  7111. Tools._NoneLogLevel = 0;
  7112. Tools._MessageLogLevel = 1;
  7113. Tools._WarningLogLevel = 2;
  7114. Tools._ErrorLogLevel = 4;
  7115. Tools._LogCache = "";
  7116. Tools.errorsCount = 0;
  7117. Tools.Log = Tools._LogEnabled;
  7118. Tools.Warn = Tools._WarnEnabled;
  7119. Tools.Error = Tools._ErrorEnabled;
  7120. // Performances
  7121. Tools._PerformanceNoneLogLevel = 0;
  7122. Tools._PerformanceUserMarkLogLevel = 1;
  7123. Tools._PerformanceConsoleLogLevel = 2;
  7124. Tools._performance = window.performance;
  7125. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7126. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7127. BABYLON.Tools = Tools;
  7128. /**
  7129. * This class is used to track a performance counter which is number based.
  7130. * The user has access to many properties which give statistics of different nature
  7131. *
  7132. * The implementer can track two kinds of Performance Counter: time and count
  7133. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  7134. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  7135. */
  7136. var PerfCounter = (function () {
  7137. function PerfCounter() {
  7138. this._startMonitoringTime = 0;
  7139. this._min = 0;
  7140. this._max = 0;
  7141. this._average = 0;
  7142. this._lastSecAverage = 0;
  7143. this._current = 0;
  7144. this._totalValueCount = 0;
  7145. this._totalAccumulated = 0;
  7146. this._lastSecAccumulated = 0;
  7147. this._lastSecTime = 0;
  7148. this._lastSecValueCount = 0;
  7149. }
  7150. Object.defineProperty(PerfCounter.prototype, "min", {
  7151. /**
  7152. * Returns the smallest value ever
  7153. */
  7154. get: function () {
  7155. return this._min;
  7156. },
  7157. enumerable: true,
  7158. configurable: true
  7159. });
  7160. Object.defineProperty(PerfCounter.prototype, "max", {
  7161. /**
  7162. * Returns the biggest value ever
  7163. */
  7164. get: function () {
  7165. return this._max;
  7166. },
  7167. enumerable: true,
  7168. configurable: true
  7169. });
  7170. Object.defineProperty(PerfCounter.prototype, "average", {
  7171. /**
  7172. * Returns the average value since the performance counter is running
  7173. */
  7174. get: function () {
  7175. return this._average;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7181. /**
  7182. * Returns the average value of the last second the counter was monitored
  7183. */
  7184. get: function () {
  7185. return this._lastSecAverage;
  7186. },
  7187. enumerable: true,
  7188. configurable: true
  7189. });
  7190. Object.defineProperty(PerfCounter.prototype, "current", {
  7191. /**
  7192. * Returns the current value
  7193. */
  7194. get: function () {
  7195. return this._current;
  7196. },
  7197. enumerable: true,
  7198. configurable: true
  7199. });
  7200. Object.defineProperty(PerfCounter.prototype, "total", {
  7201. get: function () {
  7202. return this._totalAccumulated;
  7203. },
  7204. enumerable: true,
  7205. configurable: true
  7206. });
  7207. /**
  7208. * Call this method to start monitoring a new frame.
  7209. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  7210. */
  7211. PerfCounter.prototype.fetchNewFrame = function () {
  7212. this._totalValueCount++;
  7213. this._current = 0;
  7214. this._lastSecValueCount++;
  7215. };
  7216. /**
  7217. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7218. * @param newCount the count value to add to the monitored count
  7219. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  7220. */
  7221. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7222. if (!PerfCounter.Enabled) {
  7223. return;
  7224. }
  7225. this._current += newCount;
  7226. if (fetchResult) {
  7227. this._fetchResult();
  7228. }
  7229. };
  7230. /**
  7231. * Start monitoring this performance counter
  7232. */
  7233. PerfCounter.prototype.beginMonitoring = function () {
  7234. if (!PerfCounter.Enabled) {
  7235. return;
  7236. }
  7237. this._startMonitoringTime = Tools.Now;
  7238. };
  7239. /**
  7240. * Compute the time lapsed since the previous beginMonitoring() call.
  7241. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  7242. */
  7243. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7244. if (newFrame === void 0) { newFrame = true; }
  7245. if (!PerfCounter.Enabled) {
  7246. return;
  7247. }
  7248. if (newFrame) {
  7249. this.fetchNewFrame();
  7250. }
  7251. var currentTime = Tools.Now;
  7252. this._current = currentTime - this._startMonitoringTime;
  7253. if (newFrame) {
  7254. this._fetchResult();
  7255. }
  7256. };
  7257. PerfCounter.prototype._fetchResult = function () {
  7258. this._totalAccumulated += this._current;
  7259. this._lastSecAccumulated += this._current;
  7260. // Min/Max update
  7261. this._min = Math.min(this._min, this._current);
  7262. this._max = Math.max(this._max, this._current);
  7263. this._average = this._totalAccumulated / this._totalValueCount;
  7264. // Reset last sec?
  7265. var now = Tools.Now;
  7266. if ((now - this._lastSecTime) > 1000) {
  7267. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7268. this._lastSecTime = now;
  7269. this._lastSecAccumulated = 0;
  7270. this._lastSecValueCount = 0;
  7271. }
  7272. };
  7273. return PerfCounter;
  7274. }());
  7275. PerfCounter.Enabled = true;
  7276. BABYLON.PerfCounter = PerfCounter;
  7277. /**
  7278. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7279. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7280. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7281. * @param name The name of the class, case should be preserved
  7282. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7283. */
  7284. function className(name, module) {
  7285. return function (target) {
  7286. target["__bjsclassName__"] = name;
  7287. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7288. };
  7289. }
  7290. BABYLON.className = className;
  7291. /**
  7292. * An implementation of a loop for asynchronous functions.
  7293. */
  7294. var AsyncLoop = (function () {
  7295. /**
  7296. * Constroctor.
  7297. * @param iterations the number of iterations.
  7298. * @param _fn the function to run each iteration
  7299. * @param _successCallback the callback that will be called upon succesful execution
  7300. * @param offset starting offset.
  7301. */
  7302. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7303. if (offset === void 0) { offset = 0; }
  7304. this.iterations = iterations;
  7305. this._fn = _fn;
  7306. this._successCallback = _successCallback;
  7307. this.index = offset - 1;
  7308. this._done = false;
  7309. }
  7310. /**
  7311. * Execute the next iteration. Must be called after the last iteration was finished.
  7312. */
  7313. AsyncLoop.prototype.executeNext = function () {
  7314. if (!this._done) {
  7315. if (this.index + 1 < this.iterations) {
  7316. ++this.index;
  7317. this._fn(this);
  7318. }
  7319. else {
  7320. this.breakLoop();
  7321. }
  7322. }
  7323. };
  7324. /**
  7325. * Break the loop and run the success callback.
  7326. */
  7327. AsyncLoop.prototype.breakLoop = function () {
  7328. this._done = true;
  7329. this._successCallback();
  7330. };
  7331. /**
  7332. * Helper function
  7333. */
  7334. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7335. if (offset === void 0) { offset = 0; }
  7336. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7337. loop.executeNext();
  7338. return loop;
  7339. };
  7340. /**
  7341. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7342. * @param iterations total number of iterations
  7343. * @param syncedIterations number of synchronous iterations in each async iteration.
  7344. * @param fn the function to call each iteration.
  7345. * @param callback a success call back that will be called when iterating stops.
  7346. * @param breakFunction a break condition (optional)
  7347. * @param timeout timeout settings for the setTimeout function. default - 0.
  7348. * @constructor
  7349. */
  7350. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7351. if (timeout === void 0) { timeout = 0; }
  7352. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7353. if (breakFunction && breakFunction())
  7354. loop.breakLoop();
  7355. else {
  7356. setTimeout(function () {
  7357. for (var i = 0; i < syncedIterations; ++i) {
  7358. var iteration = (loop.index * syncedIterations) + i;
  7359. if (iteration >= iterations)
  7360. break;
  7361. fn(iteration);
  7362. if (breakFunction && breakFunction()) {
  7363. loop.breakLoop();
  7364. break;
  7365. }
  7366. }
  7367. loop.executeNext();
  7368. }, timeout);
  7369. }
  7370. }, callback);
  7371. };
  7372. return AsyncLoop;
  7373. }());
  7374. BABYLON.AsyncLoop = AsyncLoop;
  7375. })(BABYLON || (BABYLON = {}));
  7376. //# sourceMappingURL=babylon.tools.js.map
  7377. var BABYLON;
  7378. (function (BABYLON) {
  7379. var Internals;
  7380. (function (Internals) {
  7381. var _AlphaState = (function () {
  7382. /**
  7383. * Initializes the state.
  7384. */
  7385. function _AlphaState() {
  7386. this._isAlphaBlendDirty = false;
  7387. this._isBlendFunctionParametersDirty = false;
  7388. this._alphaBlend = false;
  7389. this._blendFunctionParameters = new Array(4);
  7390. this.reset();
  7391. }
  7392. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7393. get: function () {
  7394. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7395. },
  7396. enumerable: true,
  7397. configurable: true
  7398. });
  7399. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7400. get: function () {
  7401. return this._alphaBlend;
  7402. },
  7403. set: function (value) {
  7404. if (this._alphaBlend === value) {
  7405. return;
  7406. }
  7407. this._alphaBlend = value;
  7408. this._isAlphaBlendDirty = true;
  7409. },
  7410. enumerable: true,
  7411. configurable: true
  7412. });
  7413. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7414. if (this._blendFunctionParameters[0] === value0 &&
  7415. this._blendFunctionParameters[1] === value1 &&
  7416. this._blendFunctionParameters[2] === value2 &&
  7417. this._blendFunctionParameters[3] === value3) {
  7418. return;
  7419. }
  7420. this._blendFunctionParameters[0] = value0;
  7421. this._blendFunctionParameters[1] = value1;
  7422. this._blendFunctionParameters[2] = value2;
  7423. this._blendFunctionParameters[3] = value3;
  7424. this._isBlendFunctionParametersDirty = true;
  7425. };
  7426. _AlphaState.prototype.reset = function () {
  7427. this._alphaBlend = false;
  7428. this._blendFunctionParameters[0] = null;
  7429. this._blendFunctionParameters[1] = null;
  7430. this._blendFunctionParameters[2] = null;
  7431. this._blendFunctionParameters[3] = null;
  7432. this._isAlphaBlendDirty = true;
  7433. this._isBlendFunctionParametersDirty = false;
  7434. };
  7435. _AlphaState.prototype.apply = function (gl) {
  7436. if (!this.isDirty) {
  7437. return;
  7438. }
  7439. // Alpha blend
  7440. if (this._isAlphaBlendDirty) {
  7441. if (this._alphaBlend) {
  7442. gl.enable(gl.BLEND);
  7443. }
  7444. else {
  7445. gl.disable(gl.BLEND);
  7446. }
  7447. this._isAlphaBlendDirty = false;
  7448. }
  7449. // Alpha function
  7450. if (this._isBlendFunctionParametersDirty) {
  7451. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7452. this._isBlendFunctionParametersDirty = false;
  7453. }
  7454. };
  7455. return _AlphaState;
  7456. }());
  7457. Internals._AlphaState = _AlphaState;
  7458. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7459. })(BABYLON || (BABYLON = {}));
  7460. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7461. var BABYLON;
  7462. (function (BABYLON) {
  7463. var Internals;
  7464. (function (Internals) {
  7465. var _DepthCullingState = (function () {
  7466. /**
  7467. * Initializes the state.
  7468. */
  7469. function _DepthCullingState() {
  7470. this._isDepthTestDirty = false;
  7471. this._isDepthMaskDirty = false;
  7472. this._isDepthFuncDirty = false;
  7473. this._isCullFaceDirty = false;
  7474. this._isCullDirty = false;
  7475. this._isZOffsetDirty = false;
  7476. this.reset();
  7477. }
  7478. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7479. get: function () {
  7480. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7486. get: function () {
  7487. return this._zOffset;
  7488. },
  7489. set: function (value) {
  7490. if (this._zOffset === value) {
  7491. return;
  7492. }
  7493. this._zOffset = value;
  7494. this._isZOffsetDirty = true;
  7495. },
  7496. enumerable: true,
  7497. configurable: true
  7498. });
  7499. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7500. get: function () {
  7501. return this._cullFace;
  7502. },
  7503. set: function (value) {
  7504. if (this._cullFace === value) {
  7505. return;
  7506. }
  7507. this._cullFace = value;
  7508. this._isCullFaceDirty = true;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7514. get: function () {
  7515. return this._cull;
  7516. },
  7517. set: function (value) {
  7518. if (this._cull === value) {
  7519. return;
  7520. }
  7521. this._cull = value;
  7522. this._isCullDirty = true;
  7523. },
  7524. enumerable: true,
  7525. configurable: true
  7526. });
  7527. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7528. get: function () {
  7529. return this._depthFunc;
  7530. },
  7531. set: function (value) {
  7532. if (this._depthFunc === value) {
  7533. return;
  7534. }
  7535. this._depthFunc = value;
  7536. this._isDepthFuncDirty = true;
  7537. },
  7538. enumerable: true,
  7539. configurable: true
  7540. });
  7541. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7542. get: function () {
  7543. return this._depthMask;
  7544. },
  7545. set: function (value) {
  7546. if (this._depthMask === value) {
  7547. return;
  7548. }
  7549. this._depthMask = value;
  7550. this._isDepthMaskDirty = true;
  7551. },
  7552. enumerable: true,
  7553. configurable: true
  7554. });
  7555. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7556. get: function () {
  7557. return this._depthTest;
  7558. },
  7559. set: function (value) {
  7560. if (this._depthTest === value) {
  7561. return;
  7562. }
  7563. this._depthTest = value;
  7564. this._isDepthTestDirty = true;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. _DepthCullingState.prototype.reset = function () {
  7570. this._depthMask = true;
  7571. this._depthTest = true;
  7572. this._depthFunc = null;
  7573. this._cullFace = null;
  7574. this._cull = null;
  7575. this._zOffset = 0;
  7576. this._isDepthTestDirty = true;
  7577. this._isDepthMaskDirty = true;
  7578. this._isDepthFuncDirty = false;
  7579. this._isCullFaceDirty = false;
  7580. this._isCullDirty = false;
  7581. this._isZOffsetDirty = false;
  7582. };
  7583. _DepthCullingState.prototype.apply = function (gl) {
  7584. if (!this.isDirty) {
  7585. return;
  7586. }
  7587. // Cull
  7588. if (this._isCullDirty) {
  7589. if (this.cull) {
  7590. gl.enable(gl.CULL_FACE);
  7591. }
  7592. else {
  7593. gl.disable(gl.CULL_FACE);
  7594. }
  7595. this._isCullDirty = false;
  7596. }
  7597. // Cull face
  7598. if (this._isCullFaceDirty) {
  7599. gl.cullFace(this.cullFace);
  7600. this._isCullFaceDirty = false;
  7601. }
  7602. // Depth mask
  7603. if (this._isDepthMaskDirty) {
  7604. gl.depthMask(this.depthMask);
  7605. this._isDepthMaskDirty = false;
  7606. }
  7607. // Depth test
  7608. if (this._isDepthTestDirty) {
  7609. if (this.depthTest) {
  7610. gl.enable(gl.DEPTH_TEST);
  7611. }
  7612. else {
  7613. gl.disable(gl.DEPTH_TEST);
  7614. }
  7615. this._isDepthTestDirty = false;
  7616. }
  7617. // Depth func
  7618. if (this._isDepthFuncDirty) {
  7619. gl.depthFunc(this.depthFunc);
  7620. this._isDepthFuncDirty = false;
  7621. }
  7622. // zOffset
  7623. if (this._isZOffsetDirty) {
  7624. if (this.zOffset) {
  7625. gl.enable(gl.POLYGON_OFFSET_FILL);
  7626. gl.polygonOffset(this.zOffset, 0);
  7627. }
  7628. else {
  7629. gl.disable(gl.POLYGON_OFFSET_FILL);
  7630. }
  7631. this._isZOffsetDirty = false;
  7632. }
  7633. };
  7634. return _DepthCullingState;
  7635. }());
  7636. Internals._DepthCullingState = _DepthCullingState;
  7637. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7638. })(BABYLON || (BABYLON = {}));
  7639. //# sourceMappingURL=babylon.depthCullingState.js.map
  7640. var BABYLON;
  7641. (function (BABYLON) {
  7642. var Internals;
  7643. (function (Internals) {
  7644. var _StencilState = (function () {
  7645. function _StencilState() {
  7646. this._isStencilTestDirty = false;
  7647. this._isStencilMaskDirty = false;
  7648. this._isStencilFuncDirty = false;
  7649. this._isStencilOpDirty = false;
  7650. this.reset();
  7651. }
  7652. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7653. get: function () {
  7654. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7655. },
  7656. enumerable: true,
  7657. configurable: true
  7658. });
  7659. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7660. get: function () {
  7661. return this._stencilFunc;
  7662. },
  7663. set: function (value) {
  7664. if (this._stencilFunc === value) {
  7665. return;
  7666. }
  7667. this._stencilFunc = value;
  7668. this._isStencilFuncDirty = true;
  7669. },
  7670. enumerable: true,
  7671. configurable: true
  7672. });
  7673. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7674. get: function () {
  7675. return this._stencilFuncRef;
  7676. },
  7677. set: function (value) {
  7678. if (this._stencilFuncRef === value) {
  7679. return;
  7680. }
  7681. this._stencilFuncRef = value;
  7682. this._isStencilFuncDirty = true;
  7683. },
  7684. enumerable: true,
  7685. configurable: true
  7686. });
  7687. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7688. get: function () {
  7689. return this._stencilFuncMask;
  7690. },
  7691. set: function (value) {
  7692. if (this._stencilFuncMask === value) {
  7693. return;
  7694. }
  7695. this._stencilFuncMask = value;
  7696. this._isStencilFuncDirty = true;
  7697. },
  7698. enumerable: true,
  7699. configurable: true
  7700. });
  7701. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7702. get: function () {
  7703. return this._stencilOpStencilFail;
  7704. },
  7705. set: function (value) {
  7706. if (this._stencilOpStencilFail === value) {
  7707. return;
  7708. }
  7709. this._stencilOpStencilFail = value;
  7710. this._isStencilOpDirty = true;
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7716. get: function () {
  7717. return this._stencilOpDepthFail;
  7718. },
  7719. set: function (value) {
  7720. if (this._stencilOpDepthFail === value) {
  7721. return;
  7722. }
  7723. this._stencilOpDepthFail = value;
  7724. this._isStencilOpDirty = true;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7730. get: function () {
  7731. return this._stencilOpStencilDepthPass;
  7732. },
  7733. set: function (value) {
  7734. if (this._stencilOpStencilDepthPass === value) {
  7735. return;
  7736. }
  7737. this._stencilOpStencilDepthPass = value;
  7738. this._isStencilOpDirty = true;
  7739. },
  7740. enumerable: true,
  7741. configurable: true
  7742. });
  7743. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7744. get: function () {
  7745. return this._stencilMask;
  7746. },
  7747. set: function (value) {
  7748. if (this._stencilMask === value) {
  7749. return;
  7750. }
  7751. this._stencilMask = value;
  7752. this._isStencilMaskDirty = true;
  7753. },
  7754. enumerable: true,
  7755. configurable: true
  7756. });
  7757. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7758. get: function () {
  7759. return this._stencilTest;
  7760. },
  7761. set: function (value) {
  7762. if (this._stencilTest === value) {
  7763. return;
  7764. }
  7765. this._stencilTest = value;
  7766. this._isStencilTestDirty = true;
  7767. },
  7768. enumerable: true,
  7769. configurable: true
  7770. });
  7771. _StencilState.prototype.reset = function () {
  7772. this._stencilTest = false;
  7773. this._stencilMask = 0xFF;
  7774. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7775. this._stencilFuncRef = 1;
  7776. this._stencilFuncMask = 0xFF;
  7777. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7778. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7779. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7780. this._isStencilTestDirty = true;
  7781. this._isStencilMaskDirty = true;
  7782. this._isStencilFuncDirty = true;
  7783. this._isStencilOpDirty = true;
  7784. };
  7785. _StencilState.prototype.apply = function (gl) {
  7786. if (!this.isDirty) {
  7787. return;
  7788. }
  7789. // Stencil test
  7790. if (this._isStencilTestDirty) {
  7791. if (this.stencilTest) {
  7792. gl.enable(gl.STENCIL_TEST);
  7793. }
  7794. else {
  7795. gl.disable(gl.STENCIL_TEST);
  7796. }
  7797. this._isStencilTestDirty = false;
  7798. }
  7799. // Stencil mask
  7800. if (this._isStencilMaskDirty) {
  7801. gl.stencilMask(this.stencilMask);
  7802. this._isStencilMaskDirty = false;
  7803. }
  7804. // Stencil func
  7805. if (this._isStencilFuncDirty) {
  7806. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7807. this._isStencilFuncDirty = false;
  7808. }
  7809. // Stencil op
  7810. if (this._isStencilOpDirty) {
  7811. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7812. this._isStencilOpDirty = false;
  7813. }
  7814. };
  7815. return _StencilState;
  7816. }());
  7817. Internals._StencilState = _StencilState;
  7818. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7819. })(BABYLON || (BABYLON = {}));
  7820. //# sourceMappingURL=babylon.stencilState.js.map
  7821. var BABYLON;
  7822. (function (BABYLON) {
  7823. var DefaultLoadingScreen = (function () {
  7824. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  7825. if (_loadingText === void 0) { _loadingText = ""; }
  7826. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  7827. var _this = this;
  7828. this._renderingCanvas = _renderingCanvas;
  7829. this._loadingText = _loadingText;
  7830. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  7831. // Resize
  7832. this._resizeLoadingUI = function () {
  7833. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  7834. _this._loadingDiv.style.position = "absolute";
  7835. _this._loadingDiv.style.left = canvasRect.left + "px";
  7836. _this._loadingDiv.style.top = canvasRect.top + "px";
  7837. _this._loadingDiv.style.width = canvasRect.width + "px";
  7838. _this._loadingDiv.style.height = canvasRect.height + "px";
  7839. };
  7840. }
  7841. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  7842. var _this = this;
  7843. if (this._loadingDiv) {
  7844. // Do not add a loading screen if there is already one
  7845. return;
  7846. }
  7847. this._loadingDiv = document.createElement("div");
  7848. this._loadingDiv.id = "babylonjsLoadingDiv";
  7849. this._loadingDiv.style.opacity = "0";
  7850. this._loadingDiv.style.transition = "opacity 1.5s ease";
  7851. // Loading text
  7852. this._loadingTextDiv = document.createElement("div");
  7853. this._loadingTextDiv.style.position = "absolute";
  7854. this._loadingTextDiv.style.left = "0";
  7855. this._loadingTextDiv.style.top = "50%";
  7856. this._loadingTextDiv.style.marginTop = "80px";
  7857. this._loadingTextDiv.style.width = "100%";
  7858. this._loadingTextDiv.style.height = "20px";
  7859. this._loadingTextDiv.style.fontFamily = "Arial";
  7860. this._loadingTextDiv.style.fontSize = "14px";
  7861. this._loadingTextDiv.style.color = "white";
  7862. this._loadingTextDiv.style.textAlign = "center";
  7863. this._loadingTextDiv.innerHTML = "Loading";
  7864. this._loadingDiv.appendChild(this._loadingTextDiv);
  7865. //set the predefined text
  7866. this._loadingTextDiv.innerHTML = this._loadingText;
  7867. // Loading img
  7868. var imgBack = new Image();
  7869. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  7870. imgBack.style.position = "absolute";
  7871. imgBack.style.left = "50%";
  7872. imgBack.style.top = "50%";
  7873. imgBack.style.marginLeft = "-50px";
  7874. imgBack.style.marginTop = "-50px";
  7875. imgBack.style.transition = "transform 1.0s ease";
  7876. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  7877. var deg = 360;
  7878. var onTransitionEnd = function () {
  7879. deg += 360;
  7880. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  7881. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  7882. };
  7883. imgBack.addEventListener("transitionend", onTransitionEnd);
  7884. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  7885. this._loadingDiv.appendChild(imgBack);
  7886. // front image
  7887. var imgFront = new Image();
  7888. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  7889. imgFront.style.position = "absolute";
  7890. imgFront.style.left = "50%";
  7891. imgFront.style.top = "50%";
  7892. imgFront.style.marginLeft = "-50px";
  7893. imgFront.style.marginTop = "-50px";
  7894. this._loadingDiv.appendChild(imgFront);
  7895. this._resizeLoadingUI();
  7896. window.addEventListener("resize", this._resizeLoadingUI);
  7897. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  7898. document.body.appendChild(this._loadingDiv);
  7899. setTimeout(function () {
  7900. _this._loadingDiv.style.opacity = "1";
  7901. imgBack.style.transform = "rotateZ(360deg)";
  7902. imgBack.style.webkitTransform = "rotateZ(360deg)";
  7903. }, 0);
  7904. };
  7905. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  7906. var _this = this;
  7907. if (!this._loadingDiv) {
  7908. return;
  7909. }
  7910. var onTransitionEnd = function () {
  7911. if (!_this._loadingDiv) {
  7912. return;
  7913. }
  7914. document.body.removeChild(_this._loadingDiv);
  7915. window.removeEventListener("resize", _this._resizeLoadingUI);
  7916. _this._loadingDiv = null;
  7917. };
  7918. this._loadingDiv.style.opacity = "0";
  7919. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7920. };
  7921. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  7922. set: function (text) {
  7923. this._loadingText = text;
  7924. if (this._loadingTextDiv) {
  7925. this._loadingTextDiv.innerHTML = this._loadingText;
  7926. }
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  7932. get: function () {
  7933. return this._loadingDivBackgroundColor;
  7934. },
  7935. set: function (color) {
  7936. this._loadingDivBackgroundColor = color;
  7937. if (!this._loadingDiv) {
  7938. return;
  7939. }
  7940. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. return DefaultLoadingScreen;
  7946. }());
  7947. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  7948. })(BABYLON || (BABYLON = {}));
  7949. //# sourceMappingURL=babylon.loadingScreen.js.map
  7950. var BABYLON;
  7951. (function (BABYLON) {
  7952. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7953. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7954. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7955. gl.compileShader(shader);
  7956. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7957. throw new Error(gl.getShaderInfoLog(shader));
  7958. }
  7959. return shader;
  7960. };
  7961. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7962. var magFilter = gl.NEAREST;
  7963. var minFilter = gl.NEAREST;
  7964. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7965. magFilter = gl.LINEAR;
  7966. if (generateMipMaps) {
  7967. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7968. }
  7969. else {
  7970. minFilter = gl.LINEAR;
  7971. }
  7972. }
  7973. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7974. magFilter = gl.LINEAR;
  7975. if (generateMipMaps) {
  7976. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7977. }
  7978. else {
  7979. minFilter = gl.LINEAR;
  7980. }
  7981. }
  7982. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7983. magFilter = gl.NEAREST;
  7984. if (generateMipMaps) {
  7985. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7986. }
  7987. else {
  7988. minFilter = gl.NEAREST;
  7989. }
  7990. }
  7991. return {
  7992. min: minFilter,
  7993. mag: magFilter
  7994. };
  7995. };
  7996. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7998. var engine = scene.getEngine();
  7999. if (!engine) {
  8000. return;
  8001. }
  8002. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  8003. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  8004. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8005. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8006. texture._baseWidth = width;
  8007. texture._baseHeight = height;
  8008. texture._width = potWidth;
  8009. texture._height = potHeight;
  8010. texture.isReady = true;
  8011. processFunction(potWidth, potHeight);
  8012. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  8013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8015. if (!noMipmap && !isCompressed) {
  8016. gl.generateMipmap(gl.TEXTURE_2D);
  8017. }
  8018. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  8019. engine.resetTextureCache();
  8020. scene._removePendingData(texture);
  8021. texture.onLoadedCallbacks.forEach(function (callback) {
  8022. callback();
  8023. });
  8024. texture.onLoadedCallbacks = [];
  8025. };
  8026. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8027. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8028. var img;
  8029. var onload = function () {
  8030. loadedImages[index] = img;
  8031. loadedImages._internalCount++;
  8032. scene._removePendingData(img);
  8033. if (loadedImages._internalCount === 6) {
  8034. onfinish(loadedImages);
  8035. }
  8036. };
  8037. var onerror = function () {
  8038. scene._removePendingData(img);
  8039. if (onErrorCallBack) {
  8040. onErrorCallBack();
  8041. }
  8042. };
  8043. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8044. scene._addPendingData(img);
  8045. };
  8046. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  8047. if (onError === void 0) { onError = null; }
  8048. var loadedImages = [];
  8049. loadedImages._internalCount = 0;
  8050. for (var index = 0; index < 6; index++) {
  8051. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  8052. }
  8053. };
  8054. var InstancingAttributeInfo = (function () {
  8055. function InstancingAttributeInfo() {
  8056. }
  8057. return InstancingAttributeInfo;
  8058. }());
  8059. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8060. var EngineCapabilities = (function () {
  8061. function EngineCapabilities() {
  8062. }
  8063. return EngineCapabilities;
  8064. }());
  8065. BABYLON.EngineCapabilities = EngineCapabilities;
  8066. /**
  8067. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8068. */
  8069. var Engine = (function () {
  8070. /**
  8071. * @constructor
  8072. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  8073. * @param {boolean} [antialias] - enable antialias
  8074. * @param options - further options to be sent to the getContext function
  8075. */
  8076. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  8077. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8078. var _this = this;
  8079. // Public members
  8080. this.isFullscreen = false;
  8081. this.isPointerLock = false;
  8082. this.cullBackFaces = true;
  8083. this.renderEvenInBackground = true;
  8084. this.preventCacheWipeBetweenFrames = false;
  8085. // To enable/disable IDB support and avoid XHR on .manifest
  8086. this.enableOfflineSupport = true;
  8087. this.scenes = new Array();
  8088. this._windowIsBackground = false;
  8089. this._webGLVersion = 1.0;
  8090. this._badOS = false;
  8091. this._drawCalls = new BABYLON.PerfCounter();
  8092. this._renderingQueueLaunched = false;
  8093. this._activeRenderLoops = [];
  8094. // FPS
  8095. this.fpsRange = 60;
  8096. this.previousFramesDuration = [];
  8097. this.fps = 60;
  8098. this.deltaTime = 0;
  8099. // States
  8100. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8101. this._stencilState = new BABYLON.Internals._StencilState();
  8102. this._alphaState = new BABYLON.Internals._AlphaState();
  8103. this._alphaMode = Engine.ALPHA_DISABLE;
  8104. // Cache
  8105. this._loadedTexturesCache = new Array();
  8106. this._maxTextureChannels = 16;
  8107. this._activeTexturesCache = new Array(this._maxTextureChannels);
  8108. this._compiledEffects = {};
  8109. this._vertexAttribArraysEnabled = [];
  8110. this._uintIndicesCurrentlySet = false;
  8111. this._currentBoundBuffer = new Array();
  8112. this._currentBufferPointers = [];
  8113. this._currentInstanceLocations = new Array();
  8114. this._currentInstanceBuffers = new Array();
  8115. this._vaoRecordInProgress = false;
  8116. this._mustWipeVertexAttributes = false;
  8117. // Hardware supported Compressed Textures
  8118. this._texturesSupported = new Array();
  8119. this._onVRFullScreenTriggered = function () {
  8120. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  8121. //get the old size before we change
  8122. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8123. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8124. //get the width and height, change the render size
  8125. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  8126. var width, height;
  8127. _this.setHardwareScalingLevel(1);
  8128. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8129. }
  8130. else {
  8131. //When the specs are implemented, need to uncomment this.
  8132. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  8133. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8134. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8135. _this._vrDisplayEnabled = undefined;
  8136. }
  8137. };
  8138. this._renderingCanvas = canvas;
  8139. Engine.Instances.push(this);
  8140. this._externalData = new BABYLON.StringDictionary();
  8141. options = options || {};
  8142. if (antialias != null) {
  8143. options.antialias = antialias;
  8144. }
  8145. if (options.preserveDrawingBuffer === undefined) {
  8146. options.preserveDrawingBuffer = false;
  8147. }
  8148. if (options.audioEngine === undefined) {
  8149. options.audioEngine = true;
  8150. }
  8151. if (options.stencil === undefined) {
  8152. options.stencil = true;
  8153. }
  8154. // GL
  8155. if (!options.disableWebGL2Support) {
  8156. try {
  8157. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8158. if (this._gl) {
  8159. this._webGLVersion = 2.0;
  8160. }
  8161. }
  8162. catch (e) {
  8163. // Do nothing
  8164. }
  8165. }
  8166. if (!this._gl) {
  8167. if (!canvas) {
  8168. throw new Error("The provided canvas is null or undefined.");
  8169. }
  8170. try {
  8171. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8172. }
  8173. catch (e) {
  8174. throw new Error("WebGL not supported");
  8175. }
  8176. }
  8177. if (!this._gl) {
  8178. throw new Error("WebGL not supported");
  8179. }
  8180. this._onBlur = function () {
  8181. _this._windowIsBackground = true;
  8182. };
  8183. this._onFocus = function () {
  8184. _this._windowIsBackground = false;
  8185. };
  8186. window.addEventListener("blur", this._onBlur);
  8187. window.addEventListener("focus", this._onFocus);
  8188. // Viewport
  8189. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8190. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8191. this.resize();
  8192. // Caps
  8193. this._isStencilEnable = options.stencil;
  8194. this._caps = new EngineCapabilities();
  8195. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8196. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8197. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8198. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8199. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8200. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8201. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8202. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8203. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8204. // Infos
  8205. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8206. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8207. if (rendererInfo != null) {
  8208. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8209. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8210. }
  8211. if (!this._glVendor) {
  8212. this._glVendor = "Unknown vendor";
  8213. }
  8214. if (!this._glRenderer) {
  8215. this._glRenderer = "Unknown renderer";
  8216. }
  8217. // Extensions
  8218. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8219. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8220. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8221. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8222. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8223. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8224. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8225. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  8226. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8227. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8228. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8229. this._caps.highPrecisionShaderSupported = true;
  8230. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8231. // Checks if some of the format renders first to allow the use of webgl inspector.
  8232. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8233. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8234. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8235. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8236. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8237. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8238. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8239. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8240. // Vertex array object
  8241. if (this._webGLVersion > 1) {
  8242. this._caps.vertexArrayObject = true;
  8243. }
  8244. else {
  8245. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8246. if (vertexArrayObjectExtension != null) {
  8247. this._caps.vertexArrayObject = true;
  8248. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8249. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8250. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8251. }
  8252. else {
  8253. this._caps.vertexArrayObject = false;
  8254. }
  8255. }
  8256. // Instances count
  8257. if (this._webGLVersion > 1) {
  8258. this._caps.instancedArrays = true;
  8259. }
  8260. else {
  8261. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8262. if (instanceExtension != null) {
  8263. this._caps.instancedArrays = true;
  8264. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8265. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8266. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8267. }
  8268. else {
  8269. this._caps.instancedArrays = false;
  8270. }
  8271. }
  8272. // Intelligently add supported compressed formats in order to check for.
  8273. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8274. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8275. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8276. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8277. if (this._caps.astc)
  8278. this.texturesSupported.push('-astc.ktx');
  8279. if (this._caps.s3tc)
  8280. this.texturesSupported.push('-dxt.ktx');
  8281. if (this._caps.pvrtc)
  8282. this.texturesSupported.push('-pvrtc.ktx');
  8283. if (this._caps.etc2)
  8284. this.texturesSupported.push('-etc2.ktx');
  8285. if (this._caps.etc1)
  8286. this.texturesSupported.push('-etc1.ktx');
  8287. if (this._gl.getShaderPrecisionFormat) {
  8288. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8289. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8290. }
  8291. // Depth buffer
  8292. this.setDepthBuffer(true);
  8293. this.setDepthFunctionToLessOrEqual();
  8294. this.setDepthWrite(true);
  8295. // Fullscreen
  8296. this._onFullscreenChange = function () {
  8297. if (document.fullscreen !== undefined) {
  8298. _this.isFullscreen = document.fullscreen;
  8299. }
  8300. else if (document.mozFullScreen !== undefined) {
  8301. _this.isFullscreen = document.mozFullScreen;
  8302. }
  8303. else if (document.webkitIsFullScreen !== undefined) {
  8304. _this.isFullscreen = document.webkitIsFullScreen;
  8305. }
  8306. else if (document.msIsFullScreen !== undefined) {
  8307. _this.isFullscreen = document.msIsFullScreen;
  8308. }
  8309. // Pointer lock
  8310. if (_this.isFullscreen && _this._pointerLockRequested) {
  8311. canvas.requestPointerLock = canvas.requestPointerLock ||
  8312. canvas.msRequestPointerLock ||
  8313. canvas.mozRequestPointerLock ||
  8314. canvas.webkitRequestPointerLock;
  8315. if (canvas.requestPointerLock) {
  8316. canvas.requestPointerLock();
  8317. }
  8318. }
  8319. };
  8320. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8321. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8322. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8323. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8324. // Pointer lock
  8325. this._onPointerLockChange = function () {
  8326. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8327. document.webkitPointerLockElement === canvas ||
  8328. document.msPointerLockElement === canvas ||
  8329. document.pointerLockElement === canvas);
  8330. };
  8331. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8332. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8333. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8334. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8335. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8336. Engine.audioEngine = new BABYLON.AudioEngine();
  8337. }
  8338. //Load WebVR Devices
  8339. if (options.autoEnableWebVR) {
  8340. this.initWebVR();
  8341. }
  8342. //Detect if we are running on a faulty buggy OS.
  8343. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8344. //ua sniffing is the tool of the devil.
  8345. this._badOS = regexp.test(navigator.userAgent);
  8346. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8347. }
  8348. Object.defineProperty(Engine, "LastCreatedEngine", {
  8349. get: function () {
  8350. if (Engine.Instances.length === 0) {
  8351. return null;
  8352. }
  8353. return Engine.Instances[Engine.Instances.length - 1];
  8354. },
  8355. enumerable: true,
  8356. configurable: true
  8357. });
  8358. Object.defineProperty(Engine, "LastCreatedScene", {
  8359. get: function () {
  8360. var lastCreatedEngine = Engine.LastCreatedEngine;
  8361. if (!lastCreatedEngine) {
  8362. return null;
  8363. }
  8364. if (lastCreatedEngine.scenes.length === 0) {
  8365. return null;
  8366. }
  8367. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8368. },
  8369. enumerable: true,
  8370. configurable: true
  8371. });
  8372. /**
  8373. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8374. */
  8375. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8376. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8377. var engine = Engine.Instances[engineIndex];
  8378. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8379. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8380. }
  8381. }
  8382. };
  8383. Object.defineProperty(Engine, "NEVER", {
  8384. get: function () {
  8385. return Engine._NEVER;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Object.defineProperty(Engine, "ALWAYS", {
  8391. get: function () {
  8392. return Engine._ALWAYS;
  8393. },
  8394. enumerable: true,
  8395. configurable: true
  8396. });
  8397. Object.defineProperty(Engine, "LESS", {
  8398. get: function () {
  8399. return Engine._LESS;
  8400. },
  8401. enumerable: true,
  8402. configurable: true
  8403. });
  8404. Object.defineProperty(Engine, "EQUAL", {
  8405. get: function () {
  8406. return Engine._EQUAL;
  8407. },
  8408. enumerable: true,
  8409. configurable: true
  8410. });
  8411. Object.defineProperty(Engine, "LEQUAL", {
  8412. get: function () {
  8413. return Engine._LEQUAL;
  8414. },
  8415. enumerable: true,
  8416. configurable: true
  8417. });
  8418. Object.defineProperty(Engine, "GREATER", {
  8419. get: function () {
  8420. return Engine._GREATER;
  8421. },
  8422. enumerable: true,
  8423. configurable: true
  8424. });
  8425. Object.defineProperty(Engine, "GEQUAL", {
  8426. get: function () {
  8427. return Engine._GEQUAL;
  8428. },
  8429. enumerable: true,
  8430. configurable: true
  8431. });
  8432. Object.defineProperty(Engine, "NOTEQUAL", {
  8433. get: function () {
  8434. return Engine._NOTEQUAL;
  8435. },
  8436. enumerable: true,
  8437. configurable: true
  8438. });
  8439. Object.defineProperty(Engine, "KEEP", {
  8440. get: function () {
  8441. return Engine._KEEP;
  8442. },
  8443. enumerable: true,
  8444. configurable: true
  8445. });
  8446. Object.defineProperty(Engine, "REPLACE", {
  8447. get: function () {
  8448. return Engine._REPLACE;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine, "INCR", {
  8454. get: function () {
  8455. return Engine._INCR;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Object.defineProperty(Engine, "DECR", {
  8461. get: function () {
  8462. return Engine._DECR;
  8463. },
  8464. enumerable: true,
  8465. configurable: true
  8466. });
  8467. Object.defineProperty(Engine, "INVERT", {
  8468. get: function () {
  8469. return Engine._INVERT;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Object.defineProperty(Engine, "INCR_WRAP", {
  8475. get: function () {
  8476. return Engine._INCR_WRAP;
  8477. },
  8478. enumerable: true,
  8479. configurable: true
  8480. });
  8481. Object.defineProperty(Engine, "DECR_WRAP", {
  8482. get: function () {
  8483. return Engine._DECR_WRAP;
  8484. },
  8485. enumerable: true,
  8486. configurable: true
  8487. });
  8488. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8489. get: function () {
  8490. return Engine._ALPHA_DISABLE;
  8491. },
  8492. enumerable: true,
  8493. configurable: true
  8494. });
  8495. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8496. get: function () {
  8497. return Engine._ALPHA_ONEONE;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. Object.defineProperty(Engine, "ALPHA_ADD", {
  8503. get: function () {
  8504. return Engine._ALPHA_ADD;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8510. get: function () {
  8511. return Engine._ALPHA_COMBINE;
  8512. },
  8513. enumerable: true,
  8514. configurable: true
  8515. });
  8516. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8517. get: function () {
  8518. return Engine._ALPHA_SUBTRACT;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8524. get: function () {
  8525. return Engine._ALPHA_MULTIPLY;
  8526. },
  8527. enumerable: true,
  8528. configurable: true
  8529. });
  8530. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8531. get: function () {
  8532. return Engine._ALPHA_MAXIMIZED;
  8533. },
  8534. enumerable: true,
  8535. configurable: true
  8536. });
  8537. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8538. get: function () {
  8539. return Engine._ALPHA_PREMULTIPLIED;
  8540. },
  8541. enumerable: true,
  8542. configurable: true
  8543. });
  8544. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8545. get: function () {
  8546. return Engine._DELAYLOADSTATE_NONE;
  8547. },
  8548. enumerable: true,
  8549. configurable: true
  8550. });
  8551. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8552. get: function () {
  8553. return Engine._DELAYLOADSTATE_LOADED;
  8554. },
  8555. enumerable: true,
  8556. configurable: true
  8557. });
  8558. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8559. get: function () {
  8560. return Engine._DELAYLOADSTATE_LOADING;
  8561. },
  8562. enumerable: true,
  8563. configurable: true
  8564. });
  8565. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8566. get: function () {
  8567. return Engine._DELAYLOADSTATE_NOTLOADED;
  8568. },
  8569. enumerable: true,
  8570. configurable: true
  8571. });
  8572. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8573. get: function () {
  8574. return Engine._TEXTUREFORMAT_ALPHA;
  8575. },
  8576. enumerable: true,
  8577. configurable: true
  8578. });
  8579. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8580. get: function () {
  8581. return Engine._TEXTUREFORMAT_LUMINANCE;
  8582. },
  8583. enumerable: true,
  8584. configurable: true
  8585. });
  8586. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8587. get: function () {
  8588. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8589. },
  8590. enumerable: true,
  8591. configurable: true
  8592. });
  8593. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8594. get: function () {
  8595. return Engine._TEXTUREFORMAT_RGB;
  8596. },
  8597. enumerable: true,
  8598. configurable: true
  8599. });
  8600. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8601. get: function () {
  8602. return Engine._TEXTUREFORMAT_RGBA;
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8608. get: function () {
  8609. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8610. },
  8611. enumerable: true,
  8612. configurable: true
  8613. });
  8614. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8615. get: function () {
  8616. return Engine._TEXTURETYPE_FLOAT;
  8617. },
  8618. enumerable: true,
  8619. configurable: true
  8620. });
  8621. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8622. get: function () {
  8623. return Engine._TEXTURETYPE_HALF_FLOAT;
  8624. },
  8625. enumerable: true,
  8626. configurable: true
  8627. });
  8628. Object.defineProperty(Engine, "Version", {
  8629. get: function () {
  8630. return "3.0-alpha";
  8631. },
  8632. enumerable: true,
  8633. configurable: true
  8634. });
  8635. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8636. get: function () {
  8637. return this._texturesSupported;
  8638. },
  8639. enumerable: true,
  8640. configurable: true
  8641. });
  8642. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8643. get: function () {
  8644. return this._textureFormatInUse;
  8645. },
  8646. enumerable: true,
  8647. configurable: true
  8648. });
  8649. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8650. get: function () {
  8651. return this._webGLVersion;
  8652. },
  8653. enumerable: true,
  8654. configurable: true
  8655. });
  8656. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8657. /**
  8658. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8659. */
  8660. get: function () {
  8661. return this._isStencilEnable;
  8662. },
  8663. enumerable: true,
  8664. configurable: true
  8665. });
  8666. Engine.prototype._prepareWorkingCanvas = function () {
  8667. if (this._workingCanvas) {
  8668. return;
  8669. }
  8670. this._workingCanvas = document.createElement("canvas");
  8671. this._workingContext = this._workingCanvas.getContext("2d");
  8672. };
  8673. Engine.prototype.resetTextureCache = function () {
  8674. for (var index = 0; index < this._maxTextureChannels; index++) {
  8675. this._activeTexturesCache[index] = null;
  8676. }
  8677. };
  8678. Engine.prototype.getGlInfo = function () {
  8679. return {
  8680. vendor: this._glVendor,
  8681. renderer: this._glRenderer,
  8682. version: this._glVersion
  8683. };
  8684. };
  8685. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8686. if (useScreen === void 0) { useScreen = false; }
  8687. var viewport = camera.viewport;
  8688. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8689. };
  8690. Engine.prototype.getRenderWidth = function (useScreen) {
  8691. if (useScreen === void 0) { useScreen = false; }
  8692. if (!useScreen && this._currentRenderTarget) {
  8693. return this._currentRenderTarget._width;
  8694. }
  8695. return this._renderingCanvas.width;
  8696. };
  8697. Engine.prototype.getRenderHeight = function (useScreen) {
  8698. if (useScreen === void 0) { useScreen = false; }
  8699. if (!useScreen && this._currentRenderTarget) {
  8700. return this._currentRenderTarget._height;
  8701. }
  8702. return this._renderingCanvas.height;
  8703. };
  8704. Engine.prototype.getRenderingCanvas = function () {
  8705. return this._renderingCanvas;
  8706. };
  8707. Engine.prototype.getRenderingCanvasClientRect = function () {
  8708. return this._renderingCanvas.getBoundingClientRect();
  8709. };
  8710. Engine.prototype.setHardwareScalingLevel = function (level) {
  8711. this._hardwareScalingLevel = level;
  8712. this.resize();
  8713. };
  8714. Engine.prototype.getHardwareScalingLevel = function () {
  8715. return this._hardwareScalingLevel;
  8716. };
  8717. Engine.prototype.getLoadedTexturesCache = function () {
  8718. return this._loadedTexturesCache;
  8719. };
  8720. Engine.prototype.getCaps = function () {
  8721. return this._caps;
  8722. };
  8723. Object.defineProperty(Engine.prototype, "drawCalls", {
  8724. get: function () {
  8725. return this._drawCalls.current;
  8726. },
  8727. enumerable: true,
  8728. configurable: true
  8729. });
  8730. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8731. get: function () {
  8732. return this._drawCalls;
  8733. },
  8734. enumerable: true,
  8735. configurable: true
  8736. });
  8737. Engine.prototype.getDepthFunction = function () {
  8738. return this._depthCullingState.depthFunc;
  8739. };
  8740. Engine.prototype.setDepthFunction = function (depthFunc) {
  8741. this._depthCullingState.depthFunc = depthFunc;
  8742. };
  8743. Engine.prototype.setDepthFunctionToGreater = function () {
  8744. this._depthCullingState.depthFunc = this._gl.GREATER;
  8745. };
  8746. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8747. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8748. };
  8749. Engine.prototype.setDepthFunctionToLess = function () {
  8750. this._depthCullingState.depthFunc = this._gl.LESS;
  8751. };
  8752. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8753. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8754. };
  8755. Engine.prototype.getStencilBuffer = function () {
  8756. return this._stencilState.stencilTest;
  8757. };
  8758. Engine.prototype.setStencilBuffer = function (enable) {
  8759. this._stencilState.stencilTest = enable;
  8760. };
  8761. Engine.prototype.getStencilMask = function () {
  8762. return this._stencilState.stencilMask;
  8763. };
  8764. Engine.prototype.setStencilMask = function (mask) {
  8765. this._stencilState.stencilMask = mask;
  8766. };
  8767. Engine.prototype.getStencilFunction = function () {
  8768. return this._stencilState.stencilFunc;
  8769. };
  8770. Engine.prototype.getStencilFunctionReference = function () {
  8771. return this._stencilState.stencilFuncRef;
  8772. };
  8773. Engine.prototype.getStencilFunctionMask = function () {
  8774. return this._stencilState.stencilFuncMask;
  8775. };
  8776. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8777. this._stencilState.stencilFunc = stencilFunc;
  8778. };
  8779. Engine.prototype.setStencilFunctionReference = function (reference) {
  8780. this._stencilState.stencilFuncRef = reference;
  8781. };
  8782. Engine.prototype.setStencilFunctionMask = function (mask) {
  8783. this._stencilState.stencilFuncMask = mask;
  8784. };
  8785. Engine.prototype.getStencilOperationFail = function () {
  8786. return this._stencilState.stencilOpStencilFail;
  8787. };
  8788. Engine.prototype.getStencilOperationDepthFail = function () {
  8789. return this._stencilState.stencilOpDepthFail;
  8790. };
  8791. Engine.prototype.getStencilOperationPass = function () {
  8792. return this._stencilState.stencilOpStencilDepthPass;
  8793. };
  8794. Engine.prototype.setStencilOperationFail = function (operation) {
  8795. this._stencilState.stencilOpStencilFail = operation;
  8796. };
  8797. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8798. this._stencilState.stencilOpDepthFail = operation;
  8799. };
  8800. Engine.prototype.setStencilOperationPass = function (operation) {
  8801. this._stencilState.stencilOpStencilDepthPass = operation;
  8802. };
  8803. /**
  8804. * stop executing a render loop function and remove it from the execution array
  8805. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8806. */
  8807. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8808. if (!renderFunction) {
  8809. this._activeRenderLoops = [];
  8810. return;
  8811. }
  8812. var index = this._activeRenderLoops.indexOf(renderFunction);
  8813. if (index >= 0) {
  8814. this._activeRenderLoops.splice(index, 1);
  8815. }
  8816. };
  8817. Engine.prototype._renderLoop = function () {
  8818. var shouldRender = true;
  8819. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8820. shouldRender = false;
  8821. }
  8822. if (shouldRender) {
  8823. // Start new frame
  8824. this.beginFrame();
  8825. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8826. var renderFunction = this._activeRenderLoops[index];
  8827. renderFunction();
  8828. }
  8829. // Present
  8830. this.endFrame();
  8831. }
  8832. if (this._activeRenderLoops.length > 0) {
  8833. // Register new frame
  8834. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8835. }
  8836. else {
  8837. this._renderingQueueLaunched = false;
  8838. }
  8839. };
  8840. /**
  8841. * Register and execute a render loop. The engine can have more than one render function.
  8842. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8843. * @example
  8844. * engine.runRenderLoop(function () {
  8845. * scene.render()
  8846. * })
  8847. */
  8848. Engine.prototype.runRenderLoop = function (renderFunction) {
  8849. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8850. return;
  8851. }
  8852. this._activeRenderLoops.push(renderFunction);
  8853. if (!this._renderingQueueLaunched) {
  8854. this._renderingQueueLaunched = true;
  8855. this._bindedRenderFunction = this._renderLoop.bind(this);
  8856. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8857. }
  8858. };
  8859. /**
  8860. * Toggle full screen mode.
  8861. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8862. * @param {any} options - an options object to be sent to the requestFullscreen function
  8863. */
  8864. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8865. if (this.isFullscreen) {
  8866. BABYLON.Tools.ExitFullscreen();
  8867. }
  8868. else {
  8869. this._pointerLockRequested = requestPointerLock;
  8870. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8871. }
  8872. };
  8873. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8874. if (stencil === void 0) { stencil = false; }
  8875. this.applyStates();
  8876. var mode = 0;
  8877. if (backBuffer && color) {
  8878. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8879. mode |= this._gl.COLOR_BUFFER_BIT;
  8880. }
  8881. if (depth) {
  8882. this._gl.clearDepth(1.0);
  8883. mode |= this._gl.DEPTH_BUFFER_BIT;
  8884. }
  8885. if (stencil) {
  8886. this._gl.clearStencil(0);
  8887. mode |= this._gl.STENCIL_BUFFER_BIT;
  8888. }
  8889. this._gl.clear(mode);
  8890. };
  8891. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8892. var gl = this._gl;
  8893. // Save state
  8894. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8895. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8896. // Change state
  8897. gl.enable(gl.SCISSOR_TEST);
  8898. gl.scissor(x, y, width, height);
  8899. // Clear
  8900. this.clear(clearColor, true, true, true);
  8901. // Restore state
  8902. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8903. if (curScissor === true) {
  8904. gl.enable(gl.SCISSOR_TEST);
  8905. }
  8906. else {
  8907. gl.disable(gl.SCISSOR_TEST);
  8908. }
  8909. };
  8910. /**
  8911. * Set the WebGL's viewport
  8912. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8913. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8914. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8915. */
  8916. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8917. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8918. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8919. var x = viewport.x || 0;
  8920. var y = viewport.y || 0;
  8921. this._cachedViewport = viewport;
  8922. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8923. };
  8924. /**
  8925. * Directly set the WebGL Viewport
  8926. * The x, y, width & height are directly passed to the WebGL call
  8927. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  8928. */
  8929. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8930. var currentViewport = this._cachedViewport;
  8931. this._cachedViewport = null;
  8932. this._gl.viewport(x, y, width, height);
  8933. return currentViewport;
  8934. };
  8935. Engine.prototype.beginFrame = function () {
  8936. this._measureFps();
  8937. };
  8938. Engine.prototype.endFrame = function () {
  8939. //force a flush in case we are using a bad OS.
  8940. if (this._badOS) {
  8941. this.flushFramebuffer();
  8942. }
  8943. //submit frame to the vr device, if enabled
  8944. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8945. this._vrDisplayEnabled.submitFrame();
  8946. }
  8947. };
  8948. /**
  8949. * resize the view according to the canvas' size.
  8950. * @example
  8951. * window.addEventListener("resize", function () {
  8952. * engine.resize();
  8953. * });
  8954. */
  8955. Engine.prototype.resize = function () {
  8956. // We're not resizing the size of the canvas while in VR mode & presenting
  8957. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8958. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8959. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8960. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8961. }
  8962. };
  8963. /**
  8964. * force a specific size of the canvas
  8965. * @param {number} width - the new canvas' width
  8966. * @param {number} height - the new canvas' height
  8967. */
  8968. Engine.prototype.setSize = function (width, height) {
  8969. this._renderingCanvas.width = width;
  8970. this._renderingCanvas.height = height;
  8971. for (var index = 0; index < this.scenes.length; index++) {
  8972. var scene = this.scenes[index];
  8973. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8974. var cam = scene.cameras[camIndex];
  8975. cam._currentRenderId = 0;
  8976. }
  8977. }
  8978. };
  8979. //WebVR functions
  8980. Engine.prototype.initWebVR = function () {
  8981. if (!this.vrDisplaysPromise) {
  8982. this._getVRDisplays();
  8983. }
  8984. };
  8985. Engine.prototype.enableVR = function (vrDevice) {
  8986. this._vrDisplayEnabled = vrDevice;
  8987. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8988. };
  8989. Engine.prototype.disableVR = function () {
  8990. if (this._vrDisplayEnabled) {
  8991. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8992. }
  8993. };
  8994. Engine.prototype._getVRDisplays = function () {
  8995. var _this = this;
  8996. var getWebVRDevices = function (devices) {
  8997. var size = devices.length;
  8998. var i = 0;
  8999. _this._vrDisplays = devices.filter(function (device) {
  9000. return devices[i] instanceof VRDisplay;
  9001. });
  9002. return _this._vrDisplays;
  9003. };
  9004. //using a key due to typescript
  9005. if (navigator.getVRDisplays) {
  9006. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  9007. }
  9008. };
  9009. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  9010. this._currentRenderTarget = texture;
  9011. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9012. var gl = this._gl;
  9013. if (texture.isCube) {
  9014. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  9015. }
  9016. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  9017. this.wipeCaches();
  9018. };
  9019. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9020. if (this._currentFramebuffer !== framebuffer) {
  9021. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9022. this._currentFramebuffer = framebuffer;
  9023. }
  9024. };
  9025. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9026. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9027. this._currentRenderTarget = null;
  9028. // If MSAA, we need to bitblt back to main texture
  9029. var gl = this._gl;
  9030. if (texture._MSAAFramebuffer) {
  9031. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9032. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9033. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9034. }
  9035. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  9036. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9037. gl.generateMipmap(gl.TEXTURE_2D);
  9038. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9039. }
  9040. if (onBeforeUnbind) {
  9041. if (texture._MSAAFramebuffer) {
  9042. // Bind the correct framebuffer
  9043. this.bindUnboundFramebuffer(texture._framebuffer);
  9044. }
  9045. onBeforeUnbind();
  9046. }
  9047. this.bindUnboundFramebuffer(null);
  9048. };
  9049. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9050. if (texture.generateMipMaps) {
  9051. var gl = this._gl;
  9052. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9053. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9055. }
  9056. };
  9057. Engine.prototype.flushFramebuffer = function () {
  9058. this._gl.flush();
  9059. };
  9060. Engine.prototype.restoreDefaultFramebuffer = function () {
  9061. this._currentRenderTarget = null;
  9062. this.bindUnboundFramebuffer(null);
  9063. this.setViewport(this._cachedViewport);
  9064. this.wipeCaches();
  9065. };
  9066. // VBOs
  9067. Engine.prototype._resetVertexBufferBinding = function () {
  9068. this.bindArrayBuffer(null);
  9069. this._cachedVertexBuffers = null;
  9070. };
  9071. Engine.prototype.createVertexBuffer = function (vertices) {
  9072. var vbo = this._gl.createBuffer();
  9073. this.bindArrayBuffer(vbo);
  9074. if (vertices instanceof Float32Array) {
  9075. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9076. }
  9077. else {
  9078. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9079. }
  9080. this._resetVertexBufferBinding();
  9081. vbo.references = 1;
  9082. return vbo;
  9083. };
  9084. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9085. var vbo = this._gl.createBuffer();
  9086. this.bindArrayBuffer(vbo);
  9087. if (vertices instanceof Float32Array) {
  9088. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9089. }
  9090. else {
  9091. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9092. }
  9093. this._resetVertexBufferBinding();
  9094. vbo.references = 1;
  9095. return vbo;
  9096. };
  9097. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9098. this.bindArrayBuffer(vertexBuffer);
  9099. if (offset === undefined) {
  9100. offset = 0;
  9101. }
  9102. if (count === undefined) {
  9103. if (vertices instanceof Float32Array) {
  9104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9105. }
  9106. else {
  9107. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9108. }
  9109. }
  9110. else {
  9111. if (vertices instanceof Float32Array) {
  9112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9113. }
  9114. else {
  9115. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9116. }
  9117. }
  9118. this._resetVertexBufferBinding();
  9119. };
  9120. Engine.prototype._resetIndexBufferBinding = function () {
  9121. this.bindIndexBuffer(null);
  9122. this._cachedIndexBuffer = null;
  9123. };
  9124. Engine.prototype.createIndexBuffer = function (indices) {
  9125. var vbo = this._gl.createBuffer();
  9126. this.bindIndexBuffer(vbo);
  9127. // Check for 32 bits indices
  9128. var arrayBuffer;
  9129. var need32Bits = false;
  9130. if (indices instanceof Uint16Array) {
  9131. arrayBuffer = indices;
  9132. }
  9133. else {
  9134. //check 32 bit support
  9135. if (this._caps.uintIndices) {
  9136. if (indices instanceof Uint32Array) {
  9137. arrayBuffer = indices;
  9138. need32Bits = true;
  9139. }
  9140. else {
  9141. //number[] or Int32Array, check if 32 bit is necessary
  9142. for (var index = 0; index < indices.length; index++) {
  9143. if (indices[index] > 65535) {
  9144. need32Bits = true;
  9145. break;
  9146. }
  9147. }
  9148. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9149. }
  9150. }
  9151. else {
  9152. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9153. arrayBuffer = new Uint16Array(indices);
  9154. }
  9155. }
  9156. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9157. this._resetIndexBufferBinding();
  9158. vbo.references = 1;
  9159. vbo.is32Bits = need32Bits;
  9160. return vbo;
  9161. };
  9162. Engine.prototype.bindArrayBuffer = function (buffer) {
  9163. if (!this._vaoRecordInProgress) {
  9164. this._unBindVertexArrayObject();
  9165. }
  9166. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9167. };
  9168. Engine.prototype.bindIndexBuffer = function (buffer) {
  9169. if (!this._vaoRecordInProgress) {
  9170. this._unBindVertexArrayObject();
  9171. }
  9172. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9173. };
  9174. Engine.prototype.bindBuffer = function (buffer, target) {
  9175. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9176. this._gl.bindBuffer(target, buffer);
  9177. this._currentBoundBuffer[target] = buffer;
  9178. }
  9179. };
  9180. Engine.prototype.updateArrayBuffer = function (data) {
  9181. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9182. };
  9183. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9184. var pointer = this._currentBufferPointers[indx];
  9185. var changed = false;
  9186. if (!pointer) {
  9187. changed = true;
  9188. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  9189. }
  9190. else {
  9191. if (pointer.buffer !== buffer) {
  9192. pointer.buffer = buffer;
  9193. changed = true;
  9194. }
  9195. if (pointer.size !== size) {
  9196. pointer.size = size;
  9197. changed = true;
  9198. }
  9199. if (pointer.type !== type) {
  9200. pointer.type = type;
  9201. changed = true;
  9202. }
  9203. if (pointer.normalized !== normalized) {
  9204. pointer.normalized = normalized;
  9205. changed = true;
  9206. }
  9207. if (pointer.stride !== stride) {
  9208. pointer.stride = stride;
  9209. changed = true;
  9210. }
  9211. if (pointer.offset !== offset) {
  9212. pointer.offset = offset;
  9213. changed = true;
  9214. }
  9215. }
  9216. if (changed || this._vaoRecordInProgress) {
  9217. this.bindArrayBuffer(buffer);
  9218. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9219. }
  9220. };
  9221. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9222. if (indexBuffer == null) {
  9223. return;
  9224. }
  9225. if (this._cachedIndexBuffer !== indexBuffer) {
  9226. this._cachedIndexBuffer = indexBuffer;
  9227. this.bindIndexBuffer(indexBuffer);
  9228. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9229. }
  9230. };
  9231. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9232. var attributes = effect.getAttributesNames();
  9233. if (!this._vaoRecordInProgress) {
  9234. this._unBindVertexArrayObject();
  9235. }
  9236. this.unbindAllAttributes();
  9237. for (var index = 0; index < attributes.length; index++) {
  9238. var order = effect.getAttributeLocation(index);
  9239. if (order >= 0) {
  9240. var vertexBuffer = vertexBuffers[attributes[index]];
  9241. if (!vertexBuffer) {
  9242. continue;
  9243. }
  9244. this._gl.enableVertexAttribArray(order);
  9245. if (!this._vaoRecordInProgress) {
  9246. this._vertexAttribArraysEnabled[order] = true;
  9247. }
  9248. var buffer = vertexBuffer.getBuffer();
  9249. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9250. if (vertexBuffer.getIsInstanced()) {
  9251. this._gl.vertexAttribDivisor(order, 1);
  9252. if (!this._vaoRecordInProgress) {
  9253. this._currentInstanceLocations.push(order);
  9254. this._currentInstanceBuffers.push(buffer);
  9255. }
  9256. }
  9257. }
  9258. }
  9259. };
  9260. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9261. var vao = this._gl.createVertexArray();
  9262. this._vaoRecordInProgress = true;
  9263. this._gl.bindVertexArray(vao);
  9264. this._mustWipeVertexAttributes = true;
  9265. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9266. this.bindIndexBuffer(indexBuffer);
  9267. this._vaoRecordInProgress = false;
  9268. this._gl.bindVertexArray(null);
  9269. return vao;
  9270. };
  9271. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9272. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9273. this._cachedVertexArrayObject = vertexArrayObject;
  9274. this._gl.bindVertexArray(vertexArrayObject);
  9275. this._cachedVertexBuffers = null;
  9276. this._cachedIndexBuffer = null;
  9277. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9278. this._mustWipeVertexAttributes = true;
  9279. }
  9280. };
  9281. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9282. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9283. this._cachedVertexBuffers = vertexBuffer;
  9284. this._cachedEffectForVertexBuffers = effect;
  9285. var attributesCount = effect.getAttributesCount();
  9286. this._unBindVertexArrayObject();
  9287. this.unbindAllAttributes();
  9288. var offset = 0;
  9289. for (var index = 0; index < attributesCount; index++) {
  9290. if (index < vertexDeclaration.length) {
  9291. var order = effect.getAttributeLocation(index);
  9292. if (order >= 0) {
  9293. this._gl.enableVertexAttribArray(order);
  9294. this._vertexAttribArraysEnabled[order] = true;
  9295. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9296. }
  9297. offset += vertexDeclaration[index] * 4;
  9298. }
  9299. }
  9300. }
  9301. this._bindIndexBufferWithCache(indexBuffer);
  9302. };
  9303. Engine.prototype._unBindVertexArrayObject = function () {
  9304. if (!this._cachedVertexArrayObject) {
  9305. return;
  9306. }
  9307. this._cachedVertexArrayObject = null;
  9308. this._gl.bindVertexArray(null);
  9309. };
  9310. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9311. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9312. this._cachedVertexBuffers = vertexBuffers;
  9313. this._cachedEffectForVertexBuffers = effect;
  9314. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9315. }
  9316. this._bindIndexBufferWithCache(indexBuffer);
  9317. };
  9318. Engine.prototype.unbindInstanceAttributes = function () {
  9319. var boundBuffer;
  9320. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9321. var instancesBuffer = this._currentInstanceBuffers[i];
  9322. if (boundBuffer != instancesBuffer) {
  9323. boundBuffer = instancesBuffer;
  9324. this.bindArrayBuffer(instancesBuffer);
  9325. }
  9326. var offsetLocation = this._currentInstanceLocations[i];
  9327. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9328. }
  9329. this._currentInstanceBuffers.length = 0;
  9330. this._currentInstanceLocations.length = 0;
  9331. };
  9332. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9333. this._gl.deleteVertexArray(vao);
  9334. };
  9335. Engine.prototype._releaseBuffer = function (buffer) {
  9336. buffer.references--;
  9337. if (buffer.references === 0) {
  9338. this._gl.deleteBuffer(buffer);
  9339. return true;
  9340. }
  9341. return false;
  9342. };
  9343. Engine.prototype.createInstancesBuffer = function (capacity) {
  9344. var buffer = this._gl.createBuffer();
  9345. buffer.capacity = capacity;
  9346. this.bindArrayBuffer(buffer);
  9347. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9348. return buffer;
  9349. };
  9350. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9351. this._gl.deleteBuffer(buffer);
  9352. };
  9353. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9354. this.bindArrayBuffer(instancesBuffer);
  9355. if (data) {
  9356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9357. }
  9358. if (offsetLocations[0].index !== undefined) {
  9359. var stride = 0;
  9360. for (var i = 0; i < offsetLocations.length; i++) {
  9361. var ai = offsetLocations[i];
  9362. stride += ai.attributeSize * 4;
  9363. }
  9364. for (var i = 0; i < offsetLocations.length; i++) {
  9365. var ai = offsetLocations[i];
  9366. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9367. this._gl.enableVertexAttribArray(ai.index);
  9368. this._vertexAttribArraysEnabled[ai.index] = true;
  9369. }
  9370. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9371. this._gl.vertexAttribDivisor(ai.index, 1);
  9372. this._currentInstanceLocations.push(ai.index);
  9373. this._currentInstanceBuffers.push(instancesBuffer);
  9374. }
  9375. }
  9376. else {
  9377. for (var index = 0; index < 4; index++) {
  9378. var offsetLocation = offsetLocations[index];
  9379. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9380. this._gl.enableVertexAttribArray(offsetLocation);
  9381. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9382. }
  9383. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9384. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9385. this._currentInstanceLocations.push(offsetLocation);
  9386. this._currentInstanceBuffers.push(instancesBuffer);
  9387. }
  9388. }
  9389. };
  9390. Engine.prototype.applyStates = function () {
  9391. this._depthCullingState.apply(this._gl);
  9392. this._stencilState.apply(this._gl);
  9393. this._alphaState.apply(this._gl);
  9394. };
  9395. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9396. // Apply states
  9397. this.applyStates();
  9398. this._drawCalls.addCount(1, false);
  9399. // Render
  9400. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9401. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9402. if (instancesCount) {
  9403. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9404. return;
  9405. }
  9406. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9407. };
  9408. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9409. // Apply states
  9410. this.applyStates();
  9411. this._drawCalls.addCount(1, false);
  9412. if (instancesCount) {
  9413. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9414. return;
  9415. }
  9416. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9417. };
  9418. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9419. // Apply states
  9420. this.applyStates();
  9421. this._drawCalls.addCount(1, false);
  9422. if (instancesCount) {
  9423. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9424. return;
  9425. }
  9426. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9427. };
  9428. // Shaders
  9429. Engine.prototype._releaseEffect = function (effect) {
  9430. if (this._compiledEffects[effect._key]) {
  9431. delete this._compiledEffects[effect._key];
  9432. if (effect.getProgram()) {
  9433. this._gl.deleteProgram(effect.getProgram());
  9434. }
  9435. }
  9436. };
  9437. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9438. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9439. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9440. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9441. if (this._compiledEffects[name]) {
  9442. return this._compiledEffects[name];
  9443. }
  9444. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9445. effect._key = name;
  9446. this._compiledEffects[name] = effect;
  9447. return effect;
  9448. };
  9449. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9450. if (uniformsNames === void 0) { uniformsNames = []; }
  9451. if (samplers === void 0) { samplers = []; }
  9452. if (defines === void 0) { defines = ""; }
  9453. return this.createEffect({
  9454. vertex: "particles",
  9455. fragmentElement: fragmentName
  9456. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9457. };
  9458. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9459. context = context || this._gl;
  9460. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9461. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9462. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9463. var shaderProgram = context.createProgram();
  9464. context.attachShader(shaderProgram, vertexShader);
  9465. context.attachShader(shaderProgram, fragmentShader);
  9466. context.linkProgram(shaderProgram);
  9467. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9468. if (!linked) {
  9469. var error = context.getProgramInfoLog(shaderProgram);
  9470. if (error) {
  9471. throw new Error(error);
  9472. }
  9473. }
  9474. context.deleteShader(vertexShader);
  9475. context.deleteShader(fragmentShader);
  9476. return shaderProgram;
  9477. };
  9478. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9479. var results = [];
  9480. for (var index = 0; index < uniformsNames.length; index++) {
  9481. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9482. }
  9483. return results;
  9484. };
  9485. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9486. var results = [];
  9487. for (var index = 0; index < attributesNames.length; index++) {
  9488. try {
  9489. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9490. }
  9491. catch (e) {
  9492. results.push(-1);
  9493. }
  9494. }
  9495. return results;
  9496. };
  9497. Engine.prototype.enableEffect = function (effect) {
  9498. // Use program
  9499. this.setProgram(effect.getProgram());
  9500. this._currentEffect = effect;
  9501. if (effect.onBind) {
  9502. effect.onBind(effect);
  9503. }
  9504. };
  9505. Engine.prototype.setIntArray = function (uniform, array) {
  9506. if (!uniform)
  9507. return;
  9508. this._gl.uniform1iv(uniform, array);
  9509. };
  9510. Engine.prototype.setIntArray2 = function (uniform, array) {
  9511. if (!uniform || array.length % 2 !== 0)
  9512. return;
  9513. this._gl.uniform2iv(uniform, array);
  9514. };
  9515. Engine.prototype.setIntArray3 = function (uniform, array) {
  9516. if (!uniform || array.length % 3 !== 0)
  9517. return;
  9518. this._gl.uniform3iv(uniform, array);
  9519. };
  9520. Engine.prototype.setIntArray4 = function (uniform, array) {
  9521. if (!uniform || array.length % 4 !== 0)
  9522. return;
  9523. this._gl.uniform4iv(uniform, array);
  9524. };
  9525. Engine.prototype.setFloatArray = function (uniform, array) {
  9526. if (!uniform)
  9527. return;
  9528. this._gl.uniform1fv(uniform, array);
  9529. };
  9530. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9531. if (!uniform || array.length % 2 !== 0)
  9532. return;
  9533. this._gl.uniform2fv(uniform, array);
  9534. };
  9535. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9536. if (!uniform || array.length % 3 !== 0)
  9537. return;
  9538. this._gl.uniform3fv(uniform, array);
  9539. };
  9540. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9541. if (!uniform || array.length % 4 !== 0)
  9542. return;
  9543. this._gl.uniform4fv(uniform, array);
  9544. };
  9545. Engine.prototype.setArray = function (uniform, array) {
  9546. if (!uniform)
  9547. return;
  9548. this._gl.uniform1fv(uniform, array);
  9549. };
  9550. Engine.prototype.setArray2 = function (uniform, array) {
  9551. if (!uniform || array.length % 2 !== 0)
  9552. return;
  9553. this._gl.uniform2fv(uniform, array);
  9554. };
  9555. Engine.prototype.setArray3 = function (uniform, array) {
  9556. if (!uniform || array.length % 3 !== 0)
  9557. return;
  9558. this._gl.uniform3fv(uniform, array);
  9559. };
  9560. Engine.prototype.setArray4 = function (uniform, array) {
  9561. if (!uniform || array.length % 4 !== 0)
  9562. return;
  9563. this._gl.uniform4fv(uniform, array);
  9564. };
  9565. Engine.prototype.setMatrices = function (uniform, matrices) {
  9566. if (!uniform)
  9567. return;
  9568. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9569. };
  9570. Engine.prototype.setMatrix = function (uniform, matrix) {
  9571. if (!uniform)
  9572. return;
  9573. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9574. };
  9575. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9576. if (!uniform)
  9577. return;
  9578. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9579. };
  9580. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9581. if (!uniform)
  9582. return;
  9583. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9584. };
  9585. Engine.prototype.setFloat = function (uniform, value) {
  9586. if (!uniform)
  9587. return;
  9588. this._gl.uniform1f(uniform, value);
  9589. };
  9590. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9591. if (!uniform)
  9592. return;
  9593. this._gl.uniform2f(uniform, x, y);
  9594. };
  9595. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9596. if (!uniform)
  9597. return;
  9598. this._gl.uniform3f(uniform, x, y, z);
  9599. };
  9600. Engine.prototype.setBool = function (uniform, bool) {
  9601. if (!uniform)
  9602. return;
  9603. this._gl.uniform1i(uniform, bool);
  9604. };
  9605. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9606. if (!uniform)
  9607. return;
  9608. this._gl.uniform4f(uniform, x, y, z, w);
  9609. };
  9610. Engine.prototype.setColor3 = function (uniform, color3) {
  9611. if (!uniform)
  9612. return;
  9613. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9614. };
  9615. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9616. if (!uniform)
  9617. return;
  9618. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9619. };
  9620. // States
  9621. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9622. if (zOffset === void 0) { zOffset = 0; }
  9623. if (reverseSide === void 0) { reverseSide = false; }
  9624. // Culling
  9625. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9626. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9627. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9628. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9629. if (culling) {
  9630. this._depthCullingState.cullFace = cullFace;
  9631. this._depthCullingState.cull = true;
  9632. }
  9633. else {
  9634. this._depthCullingState.cull = false;
  9635. }
  9636. }
  9637. // Z offset
  9638. this._depthCullingState.zOffset = zOffset;
  9639. };
  9640. Engine.prototype.setDepthBuffer = function (enable) {
  9641. this._depthCullingState.depthTest = enable;
  9642. };
  9643. Engine.prototype.getDepthWrite = function () {
  9644. return this._depthCullingState.depthMask;
  9645. };
  9646. Engine.prototype.setDepthWrite = function (enable) {
  9647. this._depthCullingState.depthMask = enable;
  9648. };
  9649. Engine.prototype.setColorWrite = function (enable) {
  9650. this._gl.colorMask(enable, enable, enable, enable);
  9651. };
  9652. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9653. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9654. if (this._alphaMode === mode) {
  9655. return;
  9656. }
  9657. switch (mode) {
  9658. case Engine.ALPHA_DISABLE:
  9659. this._alphaState.alphaBlend = false;
  9660. break;
  9661. case Engine.ALPHA_PREMULTIPLIED:
  9662. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9663. this._alphaState.alphaBlend = true;
  9664. break;
  9665. case Engine.ALPHA_COMBINE:
  9666. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9667. this._alphaState.alphaBlend = true;
  9668. break;
  9669. case Engine.ALPHA_ONEONE:
  9670. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9671. this._alphaState.alphaBlend = true;
  9672. break;
  9673. case Engine.ALPHA_ADD:
  9674. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9675. this._alphaState.alphaBlend = true;
  9676. break;
  9677. case Engine.ALPHA_SUBTRACT:
  9678. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9679. this._alphaState.alphaBlend = true;
  9680. break;
  9681. case Engine.ALPHA_MULTIPLY:
  9682. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9683. this._alphaState.alphaBlend = true;
  9684. break;
  9685. case Engine.ALPHA_MAXIMIZED:
  9686. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9687. this._alphaState.alphaBlend = true;
  9688. break;
  9689. }
  9690. if (!noDepthWriteChange) {
  9691. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9692. }
  9693. this._alphaMode = mode;
  9694. };
  9695. Engine.prototype.getAlphaMode = function () {
  9696. return this._alphaMode;
  9697. };
  9698. Engine.prototype.setAlphaTesting = function (enable) {
  9699. this._alphaTest = enable;
  9700. };
  9701. Engine.prototype.getAlphaTesting = function () {
  9702. return !!this._alphaTest;
  9703. };
  9704. // Textures
  9705. Engine.prototype.wipeCaches = function () {
  9706. if (this.preventCacheWipeBetweenFrames) {
  9707. return;
  9708. }
  9709. this.resetTextureCache();
  9710. this._currentEffect = null;
  9711. this._stencilState.reset();
  9712. this._depthCullingState.reset();
  9713. this.setDepthFunctionToLessOrEqual();
  9714. this._alphaState.reset();
  9715. this._cachedVertexBuffers = null;
  9716. this._cachedIndexBuffer = null;
  9717. this._cachedEffectForVertexBuffers = null;
  9718. this._unBindVertexArrayObject();
  9719. this.bindIndexBuffer(null);
  9720. this.bindArrayBuffer(null);
  9721. };
  9722. /**
  9723. * Set the compressed texture format to use, based on the formats you have, and the formats
  9724. * supported by the hardware / browser.
  9725. *
  9726. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9727. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9728. * to API arguments needed to compressed textures. This puts the burden on the container
  9729. * generator to house the arcane code for determining these for current & future formats.
  9730. *
  9731. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9732. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9733. *
  9734. * Note: The result of this call is not taken into account when a texture is base64.
  9735. *
  9736. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9737. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9738. *
  9739. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9740. * @returns The extension selected.
  9741. */
  9742. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9743. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9744. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9745. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9746. return this._textureFormatInUse = this._texturesSupported[i];
  9747. }
  9748. }
  9749. }
  9750. // actively set format to nothing, to allow this to be called more than once
  9751. // and possibly fail the 2nd time
  9752. return this._textureFormatInUse = null;
  9753. };
  9754. /**
  9755. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9756. * @param {string} urlArg- This contains one of the following:
  9757. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9758. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9759. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9760. *
  9761. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9762. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9763. * @param {Scene} scene- Needed for loading to the correct scene.
  9764. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9765. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9766. * @param {callback} onError- Optional callback to be called upon failure.
  9767. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9768. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9769. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9770. *
  9771. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9772. */
  9773. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9774. var _this = this;
  9775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9776. if (onLoad === void 0) { onLoad = null; }
  9777. if (onError === void 0) { onError = null; }
  9778. if (buffer === void 0) { buffer = null; }
  9779. var texture = fallBack ? fallBack : this._gl.createTexture();
  9780. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9781. var fromData = url.substr(0, 5) === "data:";
  9782. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9783. // establish the file extension, if possible
  9784. var lastDot = url.lastIndexOf('.');
  9785. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9786. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9787. if (isDDS) {
  9788. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9789. }
  9790. var isTGA = (extension === ".tga");
  9791. // determine if a ktx file should be substituted
  9792. var isKTX = false;
  9793. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9794. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9795. isKTX = true;
  9796. }
  9797. scene._addPendingData(texture);
  9798. texture.url = url;
  9799. texture.noMipmap = noMipmap;
  9800. texture.references = 1;
  9801. texture.samplingMode = samplingMode;
  9802. texture.onLoadedCallbacks = [];
  9803. if (onLoad) {
  9804. texture.onLoadedCallbacks.push(onLoad);
  9805. }
  9806. if (!fallBack)
  9807. this._loadedTexturesCache.push(texture);
  9808. var onerror = function () {
  9809. scene._removePendingData(texture);
  9810. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9811. if (isKTX) {
  9812. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9813. }
  9814. else if (onError) {
  9815. onError();
  9816. }
  9817. };
  9818. var callback;
  9819. // processing for non-image formats
  9820. if (isKTX || isTGA || isDDS) {
  9821. if (isKTX) {
  9822. callback = function (data) {
  9823. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9824. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9825. ktx.uploadLevels(_this._gl, !noMipmap);
  9826. }, samplingMode);
  9827. };
  9828. }
  9829. else if (isTGA) {
  9830. callback = function (arrayBuffer) {
  9831. var data = new Uint8Array(arrayBuffer);
  9832. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9833. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9834. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9835. }, samplingMode);
  9836. };
  9837. }
  9838. else if (isDDS) {
  9839. callback = function (data) {
  9840. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9841. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9842. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9843. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9844. }, samplingMode);
  9845. };
  9846. }
  9847. if (!buffer) {
  9848. BABYLON.Tools.LoadFile(url, function (data) {
  9849. callback(data);
  9850. }, null, scene.database, true, onerror);
  9851. }
  9852. else {
  9853. callback(buffer);
  9854. }
  9855. // image format processing
  9856. }
  9857. else {
  9858. var onload = function (img) {
  9859. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9860. var isPot = (img.width === potWidth && img.height === potHeight);
  9861. if (!isPot) {
  9862. _this._prepareWorkingCanvas();
  9863. _this._workingCanvas.width = potWidth;
  9864. _this._workingCanvas.height = potHeight;
  9865. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9866. _this._workingContext.imageSmoothingEnabled = false;
  9867. _this._workingContext.mozImageSmoothingEnabled = false;
  9868. _this._workingContext.oImageSmoothingEnabled = false;
  9869. _this._workingContext.webkitImageSmoothingEnabled = false;
  9870. _this._workingContext.msImageSmoothingEnabled = false;
  9871. }
  9872. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9873. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9874. _this._workingContext.imageSmoothingEnabled = true;
  9875. _this._workingContext.mozImageSmoothingEnabled = true;
  9876. _this._workingContext.oImageSmoothingEnabled = true;
  9877. _this._workingContext.webkitImageSmoothingEnabled = true;
  9878. _this._workingContext.msImageSmoothingEnabled = true;
  9879. }
  9880. }
  9881. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9882. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9883. }, samplingMode);
  9884. };
  9885. if (!fromData || isBase64)
  9886. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9887. else if (buffer instanceof Array || typeof buffer === "string")
  9888. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9889. else
  9890. onload(buffer);
  9891. }
  9892. return texture;
  9893. };
  9894. Engine.prototype._getInternalFormat = function (format) {
  9895. var internalFormat = this._gl.RGBA;
  9896. switch (format) {
  9897. case Engine.TEXTUREFORMAT_ALPHA:
  9898. internalFormat = this._gl.ALPHA;
  9899. break;
  9900. case Engine.TEXTUREFORMAT_LUMINANCE:
  9901. internalFormat = this._gl.LUMINANCE;
  9902. break;
  9903. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9904. internalFormat = this._gl.LUMINANCE_ALPHA;
  9905. break;
  9906. case Engine.TEXTUREFORMAT_RGB:
  9907. internalFormat = this._gl.RGB;
  9908. break;
  9909. case Engine.TEXTUREFORMAT_RGBA:
  9910. internalFormat = this._gl.RGBA;
  9911. break;
  9912. }
  9913. return internalFormat;
  9914. };
  9915. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9916. if (compression === void 0) { compression = null; }
  9917. var internalFormat = this._getInternalFormat(format);
  9918. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9919. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9920. if (texture._width % 4 !== 0) {
  9921. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9922. }
  9923. if (compression) {
  9924. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9925. }
  9926. else {
  9927. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9928. }
  9929. if (texture.generateMipMaps) {
  9930. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9931. }
  9932. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9933. this.resetTextureCache();
  9934. texture.isReady = true;
  9935. };
  9936. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9937. if (compression === void 0) { compression = null; }
  9938. var texture = this._gl.createTexture();
  9939. texture._baseWidth = width;
  9940. texture._baseHeight = height;
  9941. texture._width = width;
  9942. texture._height = height;
  9943. texture.references = 1;
  9944. this.updateRawTexture(texture, data, format, invertY, compression);
  9945. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9946. // Filters
  9947. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9948. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9949. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9950. if (generateMipMaps) {
  9951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9952. }
  9953. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9954. texture.samplingMode = samplingMode;
  9955. this._loadedTexturesCache.push(texture);
  9956. return texture;
  9957. };
  9958. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9959. var texture = this._gl.createTexture();
  9960. texture._baseWidth = width;
  9961. texture._baseHeight = height;
  9962. if (generateMipMaps) {
  9963. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9964. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9965. }
  9966. this.resetTextureCache();
  9967. texture._width = width;
  9968. texture._height = height;
  9969. texture.isReady = false;
  9970. texture.generateMipMaps = generateMipMaps;
  9971. texture.references = 1;
  9972. texture.samplingMode = samplingMode;
  9973. this.updateTextureSamplingMode(samplingMode, texture);
  9974. this._loadedTexturesCache.push(texture);
  9975. return texture;
  9976. };
  9977. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9978. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9979. if (texture.isCube) {
  9980. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9981. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9982. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9983. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9984. }
  9985. else {
  9986. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9987. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9988. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9989. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9990. }
  9991. texture.samplingMode = samplingMode;
  9992. };
  9993. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9994. if (premulAlpha === void 0) { premulAlpha = false; }
  9995. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9996. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9997. if (premulAlpha) {
  9998. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9999. }
  10000. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10001. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10002. if (texture.generateMipMaps) {
  10003. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10004. }
  10005. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10006. if (premulAlpha) {
  10007. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10008. }
  10009. this.resetTextureCache();
  10010. texture.isReady = true;
  10011. };
  10012. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10013. if (texture._isDisabled) {
  10014. return;
  10015. }
  10016. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10017. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10018. try {
  10019. // Testing video texture support
  10020. if (this._videoTextureSupported === undefined) {
  10021. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10022. if (this._gl.getError() !== 0) {
  10023. this._videoTextureSupported = false;
  10024. }
  10025. else {
  10026. this._videoTextureSupported = true;
  10027. }
  10028. }
  10029. // Copy video through the current working canvas if video texture is not supported
  10030. if (!this._videoTextureSupported) {
  10031. if (!texture._workingCanvas) {
  10032. texture._workingCanvas = document.createElement("canvas");
  10033. texture._workingContext = texture._workingCanvas.getContext("2d");
  10034. texture._workingCanvas.width = texture._width;
  10035. texture._workingCanvas.height = texture._height;
  10036. }
  10037. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  10038. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10039. }
  10040. else {
  10041. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10042. }
  10043. if (texture.generateMipMaps) {
  10044. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10045. }
  10046. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10047. this.resetTextureCache();
  10048. texture.isReady = true;
  10049. }
  10050. catch (ex) {
  10051. // Something unexpected
  10052. // Let's disable the texture
  10053. texture._isDisabled = true;
  10054. }
  10055. };
  10056. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10057. // old version had a "generateMipMaps" arg instead of options.
  10058. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  10059. // in the same way, generateDepthBuffer is defaulted to true
  10060. var generateMipMaps = false;
  10061. var generateDepthBuffer = true;
  10062. var generateStencilBuffer = false;
  10063. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10064. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10065. if (options !== undefined) {
  10066. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  10067. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10068. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10069. type = options.type === undefined ? type : options.type;
  10070. if (options.samplingMode !== undefined) {
  10071. samplingMode = options.samplingMode;
  10072. }
  10073. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10074. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10075. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10076. }
  10077. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10078. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10079. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10080. }
  10081. }
  10082. var gl = this._gl;
  10083. var texture = gl.createTexture();
  10084. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10085. var width = size.width || size;
  10086. var height = size.height || size;
  10087. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10088. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10089. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10090. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10091. }
  10092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10096. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10097. // Create the framebuffer
  10098. var framebuffer = gl.createFramebuffer();
  10099. this.bindUnboundFramebuffer(framebuffer);
  10100. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10101. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10102. if (generateMipMaps) {
  10103. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10104. }
  10105. // Unbind
  10106. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10107. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10108. this.bindUnboundFramebuffer(null);
  10109. texture._framebuffer = framebuffer;
  10110. texture._baseWidth = width;
  10111. texture._baseHeight = height;
  10112. texture._width = width;
  10113. texture._height = height;
  10114. texture.isReady = true;
  10115. texture.samples = 1;
  10116. texture.generateMipMaps = generateMipMaps;
  10117. texture.references = 1;
  10118. texture.samplingMode = samplingMode;
  10119. texture.type = type;
  10120. texture._generateDepthBuffer = generateDepthBuffer;
  10121. texture._generateStencilBuffer = generateStencilBuffer;
  10122. this.resetTextureCache();
  10123. this._loadedTexturesCache.push(texture);
  10124. return texture;
  10125. };
  10126. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10127. if (samples === void 0) { samples = 1; }
  10128. var depthStencilBuffer = null;
  10129. var gl = this._gl;
  10130. // Create the depth/stencil buffer
  10131. if (generateStencilBuffer) {
  10132. depthStencilBuffer = gl.createRenderbuffer();
  10133. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10134. if (samples > 1) {
  10135. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  10136. }
  10137. else {
  10138. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10139. }
  10140. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10141. }
  10142. else if (generateDepthBuffer) {
  10143. depthStencilBuffer = gl.createRenderbuffer();
  10144. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10145. if (samples > 1) {
  10146. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10147. }
  10148. else {
  10149. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10150. }
  10151. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10152. }
  10153. return depthStencilBuffer;
  10154. };
  10155. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10156. if (this.webGLVersion < 2) {
  10157. return 1;
  10158. }
  10159. if (texture.samples === samples) {
  10160. return samples;
  10161. }
  10162. var gl = this._gl;
  10163. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10164. // Dispose previous render buffers
  10165. if (texture._depthStencilBuffer) {
  10166. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10167. }
  10168. if (texture._MSAAFramebuffer) {
  10169. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10170. }
  10171. if (texture._MSAARenderBuffer) {
  10172. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10173. }
  10174. if (samples > 1) {
  10175. texture._MSAAFramebuffer = gl.createFramebuffer();
  10176. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10177. var colorRenderbuffer = gl.createRenderbuffer();
  10178. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10179. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  10180. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10181. texture._MSAARenderBuffer = colorRenderbuffer;
  10182. }
  10183. else {
  10184. this.bindUnboundFramebuffer(texture._framebuffer);
  10185. }
  10186. texture.samples = samples;
  10187. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  10188. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10189. this.bindUnboundFramebuffer(null);
  10190. return samples;
  10191. };
  10192. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10193. var gl = this._gl;
  10194. var texture = gl.createTexture();
  10195. var generateMipMaps = true;
  10196. var generateDepthBuffer = true;
  10197. var generateStencilBuffer = false;
  10198. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10199. if (options !== undefined) {
  10200. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  10201. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10202. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10203. if (options.samplingMode !== undefined) {
  10204. samplingMode = options.samplingMode;
  10205. }
  10206. }
  10207. texture.isCube = true;
  10208. texture.references = 1;
  10209. texture.generateMipMaps = generateMipMaps;
  10210. texture.references = 1;
  10211. texture.samples = 1;
  10212. texture.samplingMode = samplingMode;
  10213. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10214. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10215. for (var face = 0; face < 6; face++) {
  10216. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10217. }
  10218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10222. // Create the framebuffer
  10223. var framebuffer = gl.createFramebuffer();
  10224. this.bindUnboundFramebuffer(framebuffer);
  10225. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10226. // Mipmaps
  10227. if (texture.generateMipMaps) {
  10228. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10229. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10230. }
  10231. // Unbind
  10232. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10233. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10234. this.bindUnboundFramebuffer(null);
  10235. texture._framebuffer = framebuffer;
  10236. texture._width = size;
  10237. texture._height = size;
  10238. texture.isReady = true;
  10239. this.resetTextureCache();
  10240. this._loadedTexturesCache.push(texture);
  10241. return texture;
  10242. };
  10243. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10244. var _this = this;
  10245. if (onLoad === void 0) { onLoad = null; }
  10246. if (onError === void 0) { onError = null; }
  10247. var gl = this._gl;
  10248. var texture = gl.createTexture();
  10249. texture.isCube = true;
  10250. texture.url = rootUrl;
  10251. texture.references = 1;
  10252. texture.onLoadedCallbacks = [];
  10253. var isKTX = false;
  10254. var lastDot = rootUrl.lastIndexOf('.');
  10255. var extension = rootUrl.substring(lastDot).toLowerCase();
  10256. if (this._textureFormatInUse) {
  10257. extension = this._textureFormatInUse;
  10258. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10259. isKTX = true;
  10260. }
  10261. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10262. if (isDDS) {
  10263. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  10264. }
  10265. if (isKTX) {
  10266. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10267. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10268. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10270. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10271. ktx.uploadLevels(_this._gl, !noMipmap);
  10272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10273. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10274. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10275. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10276. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10277. _this.resetTextureCache();
  10278. texture._width = ktx.pixelWidth;
  10279. texture._height = ktx.pixelHeight;
  10280. texture.isReady = true;
  10281. }, null, null, true, onError);
  10282. }
  10283. else if (isDDS) {
  10284. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10285. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10286. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10287. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10288. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10289. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10290. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10291. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10292. }
  10293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10297. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10298. _this.resetTextureCache();
  10299. texture._width = info.width;
  10300. texture._height = info.height;
  10301. texture.isReady = true;
  10302. }, null, null, true, onError);
  10303. }
  10304. else {
  10305. cascadeLoad(rootUrl, scene, function (imgs) {
  10306. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10307. var height = width;
  10308. _this._prepareWorkingCanvas();
  10309. _this._workingCanvas.width = width;
  10310. _this._workingCanvas.height = height;
  10311. var faces = [
  10312. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10313. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10314. ];
  10315. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10316. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10317. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10318. for (var index = 0; index < faces.length; index++) {
  10319. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10320. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10321. }
  10322. if (!noMipmap) {
  10323. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10324. }
  10325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10326. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10327. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10328. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10329. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10330. _this.resetTextureCache();
  10331. texture._width = width;
  10332. texture._height = height;
  10333. texture.isReady = true;
  10334. texture.onLoadedCallbacks.forEach(function (callback) {
  10335. callback();
  10336. });
  10337. if (onLoad) {
  10338. onLoad();
  10339. }
  10340. }, files, onError);
  10341. }
  10342. this._loadedTexturesCache.push(texture);
  10343. return texture;
  10344. };
  10345. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10346. texture._width = width;
  10347. texture._height = height;
  10348. texture._size = width * height;
  10349. texture._baseWidth = width;
  10350. texture._baseHeight = height;
  10351. };
  10352. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10353. var _this = this;
  10354. if (onLoad === void 0) { onLoad = null; }
  10355. if (onError === void 0) { onError = null; }
  10356. var gl = this._gl;
  10357. var texture = gl.createTexture();
  10358. scene._addPendingData(texture);
  10359. texture.isCube = true;
  10360. texture.references = 1;
  10361. texture.url = url;
  10362. var textureType = gl.UNSIGNED_BYTE;
  10363. if (type === Engine.TEXTURETYPE_FLOAT) {
  10364. textureType = gl.FLOAT;
  10365. }
  10366. var internalFormat = this._getInternalFormat(format);
  10367. var needConversion = false;
  10368. if (internalFormat === gl.RGB) {
  10369. internalFormat = gl.RGBA;
  10370. needConversion = true;
  10371. }
  10372. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10373. var width = size;
  10374. var height = width;
  10375. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10376. texture._width = width;
  10377. texture._height = height;
  10378. var onerror = function () {
  10379. scene._removePendingData(texture);
  10380. if (onError) {
  10381. onError();
  10382. }
  10383. };
  10384. var internalCallback = function (data) {
  10385. var rgbeDataArrays = callback(data);
  10386. var facesIndex = [
  10387. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10388. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10389. ];
  10390. width = texture._width;
  10391. height = texture._height;
  10392. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10393. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10394. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10395. if (mipmmapGenerator) {
  10396. var arrayTemp = [];
  10397. // Data are known to be in +X +Y +Z -X -Y -Z
  10398. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10399. arrayTemp.push(rgbeDataArrays[0]); // +X
  10400. arrayTemp.push(rgbeDataArrays[3]); // -X
  10401. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10402. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10403. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10404. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10405. var mipData = mipmmapGenerator(arrayTemp);
  10406. // mipData is order in +X -X +Y -Y +Z -Z
  10407. var mipFaces = [0, 2, 4, 1, 3, 5];
  10408. for (var level = 0; level < mipData.length; level++) {
  10409. var mipSize = width >> level;
  10410. for (var mipIndex in mipFaces) {
  10411. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10412. if (needConversion) {
  10413. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10414. }
  10415. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10416. }
  10417. }
  10418. }
  10419. else {
  10420. // Data are known to be in +X +Y +Z -X -Y -Z
  10421. for (var index = 0; index < facesIndex.length; index++) {
  10422. var faceData = rgbeDataArrays[index];
  10423. if (needConversion) {
  10424. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10425. }
  10426. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10427. }
  10428. if (!noMipmap && isPot) {
  10429. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10430. }
  10431. else {
  10432. noMipmap = true;
  10433. }
  10434. }
  10435. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10438. }
  10439. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10442. }
  10443. else {
  10444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10446. }
  10447. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10449. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10450. texture.isReady = true;
  10451. _this.resetTextureCache();
  10452. scene._removePendingData(texture);
  10453. if (onLoad) {
  10454. onLoad();
  10455. }
  10456. };
  10457. BABYLON.Tools.LoadFile(url, function (data) {
  10458. internalCallback(data);
  10459. }, onerror, scene.database, true);
  10460. return texture;
  10461. };
  10462. ;
  10463. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10464. // Create new RGBA data container.
  10465. var rgbaData;
  10466. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10467. rgbaData = new Float32Array(width * height * 4);
  10468. }
  10469. else {
  10470. rgbaData = new Uint32Array(width * height * 4);
  10471. }
  10472. // Convert each pixel.
  10473. for (var x = 0; x < width; x++) {
  10474. for (var y = 0; y < height; y++) {
  10475. var index = (y * width + x) * 3;
  10476. var newIndex = (y * width + x) * 4;
  10477. // Map Old Value to new value.
  10478. rgbaData[newIndex + 0] = rgbData[index + 0];
  10479. rgbaData[newIndex + 1] = rgbData[index + 1];
  10480. rgbaData[newIndex + 2] = rgbData[index + 2];
  10481. // Add fully opaque alpha channel.
  10482. rgbaData[newIndex + 3] = 1;
  10483. }
  10484. }
  10485. return rgbaData;
  10486. };
  10487. Engine.prototype._releaseTexture = function (texture) {
  10488. var gl = this._gl;
  10489. if (texture._framebuffer) {
  10490. gl.deleteFramebuffer(texture._framebuffer);
  10491. }
  10492. if (texture._depthStencilBuffer) {
  10493. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10494. }
  10495. if (texture._MSAAFramebuffer) {
  10496. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10497. }
  10498. if (texture._MSAARenderBuffer) {
  10499. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10500. }
  10501. gl.deleteTexture(texture);
  10502. // Unbind channels
  10503. this.unbindAllTextures();
  10504. var index = this._loadedTexturesCache.indexOf(texture);
  10505. if (index !== -1) {
  10506. this._loadedTexturesCache.splice(index, 1);
  10507. }
  10508. };
  10509. Engine.prototype.setProgram = function (program) {
  10510. if (this._currentProgram !== program) {
  10511. this._gl.useProgram(program);
  10512. this._currentProgram = program;
  10513. }
  10514. };
  10515. Engine.prototype.bindSamplers = function (effect) {
  10516. this.setProgram(effect.getProgram());
  10517. var samplers = effect.getSamplers();
  10518. for (var index = 0; index < samplers.length; index++) {
  10519. var uniform = effect.getUniform(samplers[index]);
  10520. this._gl.uniform1i(uniform, index);
  10521. }
  10522. this._currentEffect = null;
  10523. };
  10524. Engine.prototype.activateTexture = function (texture) {
  10525. if (this._activeTexture !== texture) {
  10526. this._gl.activeTexture(texture);
  10527. this._activeTexture = texture;
  10528. }
  10529. };
  10530. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10531. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10532. this._gl.bindTexture(target, texture);
  10533. this._activeTexturesCache[this._activeTexture] = texture;
  10534. }
  10535. };
  10536. Engine.prototype._bindTexture = function (channel, texture) {
  10537. if (channel < 0) {
  10538. return;
  10539. }
  10540. this.activateTexture(this._gl.TEXTURE0 + channel);
  10541. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10542. };
  10543. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10544. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10545. };
  10546. Engine.prototype.unbindAllTextures = function () {
  10547. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10548. this.activateTexture(this._gl["TEXTURE" + channel]);
  10549. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10550. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10551. }
  10552. };
  10553. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10554. if (channel < 0) {
  10555. return;
  10556. }
  10557. this._gl.uniform1i(uniform, channel);
  10558. this._setTexture(channel, texture);
  10559. };
  10560. Engine.prototype._setTexture = function (channel, texture) {
  10561. // Not ready?
  10562. if (!texture || !texture.isReady()) {
  10563. if (this._activeTexturesCache[channel] != null) {
  10564. this.activateTexture(this._gl["TEXTURE" + channel]);
  10565. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10566. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10567. }
  10568. return;
  10569. }
  10570. // Video
  10571. var alreadyActivated = false;
  10572. if (texture instanceof BABYLON.VideoTexture) {
  10573. this.activateTexture(this._gl["TEXTURE" + channel]);
  10574. alreadyActivated = true;
  10575. texture.update();
  10576. }
  10577. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10578. texture.delayLoad();
  10579. return;
  10580. }
  10581. var internalTexture = texture.getInternalTexture();
  10582. if (this._activeTexturesCache[channel] === internalTexture) {
  10583. return;
  10584. }
  10585. if (!alreadyActivated) {
  10586. this.activateTexture(this._gl["TEXTURE" + channel]);
  10587. }
  10588. if (internalTexture.isCube) {
  10589. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10590. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10591. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10592. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10593. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10594. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10595. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10596. }
  10597. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10598. }
  10599. else {
  10600. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10601. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10602. internalTexture._cachedWrapU = texture.wrapU;
  10603. switch (texture.wrapU) {
  10604. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10605. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10606. break;
  10607. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10609. break;
  10610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10612. break;
  10613. }
  10614. }
  10615. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10616. internalTexture._cachedWrapV = texture.wrapV;
  10617. switch (texture.wrapV) {
  10618. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10619. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10620. break;
  10621. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10622. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10623. break;
  10624. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10626. break;
  10627. }
  10628. }
  10629. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10630. }
  10631. };
  10632. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10633. if (channel < 0) {
  10634. return;
  10635. }
  10636. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10637. this._textureUnits = new Int32Array(textures.length);
  10638. }
  10639. for (var i = 0; i < textures.length; i++) {
  10640. this._textureUnits[i] = channel + i;
  10641. }
  10642. this._gl.uniform1iv(uniform, this._textureUnits);
  10643. for (var index = 0; index < textures.length; index++) {
  10644. this._setTexture(channel + index, textures[index]);
  10645. }
  10646. };
  10647. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10648. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10649. var value = texture.anisotropicFilteringLevel;
  10650. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10651. value = 1;
  10652. }
  10653. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10654. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10655. texture._cachedAnisotropicFilteringLevel = value;
  10656. }
  10657. };
  10658. Engine.prototype.readPixels = function (x, y, width, height) {
  10659. var data = new Uint8Array(height * width * 4);
  10660. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10661. return data;
  10662. };
  10663. /**
  10664. * Add an externaly attached data from its key.
  10665. * This method call will fail and return false, if such key already exists.
  10666. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10667. * @param key the unique key that identifies the data
  10668. * @param data the data object to associate to the key for this Engine instance
  10669. * @return true if no such key were already present and the data was added successfully, false otherwise
  10670. */
  10671. Engine.prototype.addExternalData = function (key, data) {
  10672. return this._externalData.add(key, data);
  10673. };
  10674. /**
  10675. * Get an externaly attached data from its key
  10676. * @param key the unique key that identifies the data
  10677. * @return the associated data, if present (can be null), or undefined if not present
  10678. */
  10679. Engine.prototype.getExternalData = function (key) {
  10680. return this._externalData.get(key);
  10681. };
  10682. /**
  10683. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10684. * @param key the unique key that identifies the data
  10685. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10686. * @return the associated data, can be null if the factory returned null.
  10687. */
  10688. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10689. return this._externalData.getOrAddWithFactory(key, factory);
  10690. };
  10691. /**
  10692. * Remove an externaly attached data from the Engine instance
  10693. * @param key the unique key that identifies the data
  10694. * @return true if the data was successfully removed, false if it doesn't exist
  10695. */
  10696. Engine.prototype.removeExternalData = function (key) {
  10697. return this._externalData.remove(key);
  10698. };
  10699. Engine.prototype.releaseInternalTexture = function (texture) {
  10700. if (!texture) {
  10701. return;
  10702. }
  10703. texture.references--;
  10704. // Final reference ?
  10705. if (texture.references === 0) {
  10706. var texturesCache = this.getLoadedTexturesCache();
  10707. var index = texturesCache.indexOf(texture);
  10708. if (index > -1) {
  10709. texturesCache.splice(index, 1);
  10710. }
  10711. this._releaseTexture(texture);
  10712. }
  10713. };
  10714. Engine.prototype.unbindAllAttributes = function () {
  10715. if (this._mustWipeVertexAttributes) {
  10716. this._mustWipeVertexAttributes = false;
  10717. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10718. this._gl.disableVertexAttribArray(i);
  10719. this._vertexAttribArraysEnabled[i] = false;
  10720. this._currentBufferPointers[i] = null;
  10721. }
  10722. return;
  10723. }
  10724. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10725. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10726. continue;
  10727. }
  10728. this._gl.disableVertexAttribArray(i);
  10729. this._vertexAttribArraysEnabled[i] = false;
  10730. this._currentBufferPointers[i] = null;
  10731. }
  10732. };
  10733. Engine.prototype.releaseEffects = function () {
  10734. for (var name in this._compiledEffects) {
  10735. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10736. }
  10737. this._compiledEffects = {};
  10738. };
  10739. // Dispose
  10740. Engine.prototype.dispose = function () {
  10741. this.hideLoadingUI();
  10742. this.stopRenderLoop();
  10743. // Release scenes
  10744. while (this.scenes.length) {
  10745. this.scenes[0].dispose();
  10746. }
  10747. // Release audio engine
  10748. Engine.audioEngine.dispose();
  10749. // Release effects
  10750. this.releaseEffects();
  10751. // Unbind
  10752. this.unbindAllAttributes();
  10753. this._gl = null;
  10754. //WebVR
  10755. this.disableVR();
  10756. // Events
  10757. window.removeEventListener("blur", this._onBlur);
  10758. window.removeEventListener("focus", this._onFocus);
  10759. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10760. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10761. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10762. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10763. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10764. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10765. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10766. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10767. // Remove from Instances
  10768. var index = Engine.Instances.indexOf(this);
  10769. if (index >= 0) {
  10770. Engine.Instances.splice(index, 1);
  10771. }
  10772. };
  10773. // Loading screen
  10774. Engine.prototype.displayLoadingUI = function () {
  10775. this.loadingScreen.displayLoadingUI();
  10776. };
  10777. Engine.prototype.hideLoadingUI = function () {
  10778. this.loadingScreen.hideLoadingUI();
  10779. };
  10780. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10781. get: function () {
  10782. if (!this._loadingScreen)
  10783. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10784. return this._loadingScreen;
  10785. },
  10786. set: function (loadingScreen) {
  10787. this._loadingScreen = loadingScreen;
  10788. },
  10789. enumerable: true,
  10790. configurable: true
  10791. });
  10792. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10793. set: function (text) {
  10794. this.loadingScreen.loadingUIText = text;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10800. set: function (color) {
  10801. this.loadingScreen.loadingUIBackgroundColor = color;
  10802. },
  10803. enumerable: true,
  10804. configurable: true
  10805. });
  10806. Engine.prototype.attachContextLostEvent = function (callback) {
  10807. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10808. };
  10809. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10810. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10811. };
  10812. Engine.prototype.getVertexShaderSource = function (program) {
  10813. var shaders = this._gl.getAttachedShaders(program);
  10814. return this._gl.getShaderSource(shaders[0]);
  10815. };
  10816. Engine.prototype.getFragmentShaderSource = function (program) {
  10817. var shaders = this._gl.getAttachedShaders(program);
  10818. return this._gl.getShaderSource(shaders[1]);
  10819. };
  10820. // FPS
  10821. Engine.prototype.getFps = function () {
  10822. return this.fps;
  10823. };
  10824. Engine.prototype.getDeltaTime = function () {
  10825. return this.deltaTime;
  10826. };
  10827. Engine.prototype._measureFps = function () {
  10828. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10829. var length = this.previousFramesDuration.length;
  10830. if (length >= 2) {
  10831. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10832. }
  10833. if (length >= this.fpsRange) {
  10834. if (length > this.fpsRange) {
  10835. this.previousFramesDuration.splice(0, 1);
  10836. length = this.previousFramesDuration.length;
  10837. }
  10838. var sum = 0;
  10839. for (var id = 0; id < length - 1; id++) {
  10840. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10841. }
  10842. this.fps = 1000.0 / (sum / (length - 1));
  10843. }
  10844. };
  10845. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10846. if (this._webGLVersion > 1) {
  10847. return this._caps.colorBufferFloat;
  10848. }
  10849. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10850. };
  10851. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10852. if (this._webGLVersion > 1) {
  10853. return this._caps.colorBufferFloat;
  10854. }
  10855. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10856. };
  10857. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10858. Engine.prototype._canRenderToFramebuffer = function (type) {
  10859. var gl = this._gl;
  10860. //clear existing errors
  10861. while (gl.getError() !== gl.NO_ERROR) { }
  10862. var successful = true;
  10863. var texture = gl.createTexture();
  10864. gl.bindTexture(gl.TEXTURE_2D, texture);
  10865. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10868. var fb = gl.createFramebuffer();
  10869. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10870. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10871. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10872. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10873. successful = successful && (gl.getError() === gl.NO_ERROR);
  10874. //try render by clearing frame buffer's color buffer
  10875. if (successful) {
  10876. gl.clear(gl.COLOR_BUFFER_BIT);
  10877. successful = successful && (gl.getError() === gl.NO_ERROR);
  10878. }
  10879. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10880. if (successful) {
  10881. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10882. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10883. var readFormat = gl.RGBA;
  10884. var readType = gl.UNSIGNED_BYTE;
  10885. var buffer = new Uint8Array(4);
  10886. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10887. successful = successful && (gl.getError() === gl.NO_ERROR);
  10888. }
  10889. //clean up
  10890. gl.deleteTexture(texture);
  10891. gl.deleteFramebuffer(fb);
  10892. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10893. //clear accumulated errors
  10894. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10895. return successful;
  10896. };
  10897. Engine.prototype._getWebGLTextureType = function (type) {
  10898. if (type === Engine.TEXTURETYPE_FLOAT) {
  10899. return this._gl.FLOAT;
  10900. }
  10901. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10902. // Add Half Float Constant.
  10903. return Engine.HALF_FLOAT_OES;
  10904. }
  10905. return this._gl.UNSIGNED_BYTE;
  10906. };
  10907. ;
  10908. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10909. if (this._webGLVersion === 1) {
  10910. return this._gl.RGBA;
  10911. }
  10912. if (type === Engine.TEXTURETYPE_FLOAT) {
  10913. return Engine.RGBA32F;
  10914. }
  10915. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10916. return Engine.RGBA16F;
  10917. }
  10918. return this._gl.RGBA;
  10919. };
  10920. ;
  10921. // Statics
  10922. Engine.isSupported = function () {
  10923. try {
  10924. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10925. if (navigator.isCocoonJS) {
  10926. return true;
  10927. }
  10928. var tempcanvas = document.createElement("canvas");
  10929. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10930. return gl != null && !!window.WebGLRenderingContext;
  10931. }
  10932. catch (e) {
  10933. return false;
  10934. }
  10935. };
  10936. return Engine;
  10937. }());
  10938. Engine.Instances = new Array();
  10939. // Const statics
  10940. Engine._ALPHA_DISABLE = 0;
  10941. Engine._ALPHA_ADD = 1;
  10942. Engine._ALPHA_COMBINE = 2;
  10943. Engine._ALPHA_SUBTRACT = 3;
  10944. Engine._ALPHA_MULTIPLY = 4;
  10945. Engine._ALPHA_MAXIMIZED = 5;
  10946. Engine._ALPHA_ONEONE = 6;
  10947. Engine._ALPHA_PREMULTIPLIED = 7;
  10948. Engine._DELAYLOADSTATE_NONE = 0;
  10949. Engine._DELAYLOADSTATE_LOADED = 1;
  10950. Engine._DELAYLOADSTATE_LOADING = 2;
  10951. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10952. Engine._TEXTUREFORMAT_ALPHA = 0;
  10953. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10954. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10955. Engine._TEXTUREFORMAT_RGB = 4;
  10956. Engine._TEXTUREFORMAT_RGBA = 5;
  10957. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10958. Engine._TEXTURETYPE_FLOAT = 1;
  10959. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10960. // Depht or Stencil test Constants.
  10961. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10962. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  10963. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  10964. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  10965. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  10966. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  10967. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  10968. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  10969. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10970. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10971. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10972. // Stencil Actions Constants.
  10973. Engine._KEEP = 0x1E00;
  10974. Engine._REPLACE = 0x1E01;
  10975. Engine._INCR = 0x1E02;
  10976. Engine._DECR = 0x1E03;
  10977. Engine._INVERT = 0x150A;
  10978. Engine._INCR_WRAP = 0x8507;
  10979. Engine._DECR_WRAP = 0x8508;
  10980. // Updatable statics so stick with vars here
  10981. Engine.CollisionsEpsilon = 0.001;
  10982. Engine.CodeRepository = "src/";
  10983. Engine.ShadersRepository = "src/Shaders/";
  10984. BABYLON.Engine = Engine;
  10985. })(BABYLON || (BABYLON = {}));
  10986. //# sourceMappingURL=babylon.engine.js.map
  10987. /// <reference path="Tools\babylon.decorators.ts" />
  10988. var BABYLON;
  10989. (function (BABYLON) {
  10990. /**
  10991. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10992. */
  10993. var Node = (function () {
  10994. /**
  10995. * @constructor
  10996. * @param {string} name - the name and id to be given to this node
  10997. * @param {BABYLON.Scene} the scene this node will be added to
  10998. */
  10999. function Node(name, scene) {
  11000. this.state = "";
  11001. this.metadata = null;
  11002. this.doNotSerialize = false;
  11003. this.animations = new Array();
  11004. this._ranges = {};
  11005. this._childrenFlag = -1;
  11006. this._isEnabled = true;
  11007. this._isReady = true;
  11008. this._currentRenderId = -1;
  11009. this._parentRenderId = -1;
  11010. /**
  11011. * An event triggered when the mesh is disposed.
  11012. * @type {BABYLON.Observable}
  11013. */
  11014. this.onDisposeObservable = new BABYLON.Observable();
  11015. this.name = name;
  11016. this.id = name;
  11017. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11018. this._initCache();
  11019. }
  11020. Object.defineProperty(Node.prototype, "parent", {
  11021. get: function () {
  11022. return this._parentNode;
  11023. },
  11024. set: function (parent) {
  11025. if (this._parentNode === parent) {
  11026. return;
  11027. }
  11028. if (this._parentNode) {
  11029. var index = this._parentNode._children.indexOf(this);
  11030. if (index !== -1) {
  11031. this._parentNode._children.splice(index, 1);
  11032. }
  11033. }
  11034. this._parentNode = parent;
  11035. if (this._parentNode) {
  11036. if (!this._parentNode._children) {
  11037. this._parentNode._children = new Array();
  11038. }
  11039. this._parentNode._children.push(this);
  11040. }
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Node.prototype.getClassName = function () {
  11046. return "Node";
  11047. };
  11048. Object.defineProperty(Node.prototype, "onDispose", {
  11049. set: function (callback) {
  11050. if (this._onDisposeObserver) {
  11051. this.onDisposeObservable.remove(this._onDisposeObserver);
  11052. }
  11053. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. Node.prototype.getScene = function () {
  11059. return this._scene;
  11060. };
  11061. Node.prototype.getEngine = function () {
  11062. return this._scene.getEngine();
  11063. };
  11064. // override it in derived class
  11065. Node.prototype.getWorldMatrix = function () {
  11066. return BABYLON.Matrix.Identity();
  11067. };
  11068. // override it in derived class if you add new variables to the cache
  11069. // and call the parent class method
  11070. Node.prototype._initCache = function () {
  11071. this._cache = {};
  11072. this._cache.parent = undefined;
  11073. };
  11074. Node.prototype.updateCache = function (force) {
  11075. if (!force && this.isSynchronized())
  11076. return;
  11077. this._cache.parent = this.parent;
  11078. this._updateCache();
  11079. };
  11080. // override it in derived class if you add new variables to the cache
  11081. // and call the parent class method if !ignoreParentClass
  11082. Node.prototype._updateCache = function (ignoreParentClass) {
  11083. };
  11084. // override it in derived class if you add new variables to the cache
  11085. Node.prototype._isSynchronized = function () {
  11086. return true;
  11087. };
  11088. Node.prototype._markSyncedWithParent = function () {
  11089. this._parentRenderId = this.parent._currentRenderId;
  11090. };
  11091. Node.prototype.isSynchronizedWithParent = function () {
  11092. if (!this.parent) {
  11093. return true;
  11094. }
  11095. if (this._parentRenderId !== this.parent._currentRenderId) {
  11096. return false;
  11097. }
  11098. return this.parent.isSynchronized();
  11099. };
  11100. Node.prototype.isSynchronized = function (updateCache) {
  11101. var check = this.hasNewParent();
  11102. check = check || !this.isSynchronizedWithParent();
  11103. check = check || !this._isSynchronized();
  11104. if (updateCache)
  11105. this.updateCache(true);
  11106. return !check;
  11107. };
  11108. Node.prototype.hasNewParent = function (update) {
  11109. if (this._cache.parent === this.parent)
  11110. return false;
  11111. if (update)
  11112. this._cache.parent = this.parent;
  11113. return true;
  11114. };
  11115. /**
  11116. * Is this node ready to be used/rendered
  11117. * @return {boolean} is it ready
  11118. */
  11119. Node.prototype.isReady = function () {
  11120. return this._isReady;
  11121. };
  11122. /**
  11123. * Is this node enabled.
  11124. * If the node has a parent and is enabled, the parent will be inspected as well.
  11125. * @return {boolean} whether this node (and its parent) is enabled.
  11126. * @see setEnabled
  11127. */
  11128. Node.prototype.isEnabled = function () {
  11129. if (!this._isEnabled) {
  11130. return false;
  11131. }
  11132. if (this.parent) {
  11133. return this.parent.isEnabled();
  11134. }
  11135. return true;
  11136. };
  11137. /**
  11138. * Set the enabled state of this node.
  11139. * @param {boolean} value - the new enabled state
  11140. * @see isEnabled
  11141. */
  11142. Node.prototype.setEnabled = function (value) {
  11143. this._isEnabled = value;
  11144. };
  11145. /**
  11146. * Is this node a descendant of the given node.
  11147. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11148. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11149. * @see parent
  11150. */
  11151. Node.prototype.isDescendantOf = function (ancestor) {
  11152. if (this.parent) {
  11153. if (this.parent === ancestor) {
  11154. return true;
  11155. }
  11156. return this.parent.isDescendantOf(ancestor);
  11157. }
  11158. return false;
  11159. };
  11160. /**
  11161. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11162. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11163. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  11164. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  11165. */
  11166. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11167. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11168. if (!this._children) {
  11169. return;
  11170. }
  11171. for (var index = 0; index < this._children.length; index++) {
  11172. var item = this._children[index];
  11173. if (!predicate || predicate(item)) {
  11174. results.push(item);
  11175. }
  11176. if (!directDescendantsOnly) {
  11177. item._getDescendants(results, false, predicate);
  11178. }
  11179. }
  11180. };
  11181. /**
  11182. * Will return all nodes that have this node as ascendant.
  11183. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  11184. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  11185. * @return {BABYLON.Node[]} all children nodes of all types.
  11186. */
  11187. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11188. var results = [];
  11189. this._getDescendants(results, directDescendantsOnly, predicate);
  11190. return results;
  11191. };
  11192. /**
  11193. * Get all child-meshes of this node.
  11194. */
  11195. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11196. var results = [];
  11197. this._getDescendants(results, directDecendantsOnly, function (node) {
  11198. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11199. });
  11200. return results;
  11201. };
  11202. /**
  11203. * Get all direct children of this node.
  11204. */
  11205. Node.prototype.getChildren = function (predicate) {
  11206. return this.getDescendants(true, predicate);
  11207. };
  11208. Node.prototype._setReady = function (state) {
  11209. if (state === this._isReady) {
  11210. return;
  11211. }
  11212. if (!state) {
  11213. this._isReady = false;
  11214. return;
  11215. }
  11216. this._isReady = true;
  11217. if (this.onReady) {
  11218. this.onReady(this);
  11219. }
  11220. };
  11221. Node.prototype.getAnimationByName = function (name) {
  11222. for (var i = 0; i < this.animations.length; i++) {
  11223. var animation = this.animations[i];
  11224. if (animation.name === name) {
  11225. return animation;
  11226. }
  11227. }
  11228. return null;
  11229. };
  11230. Node.prototype.createAnimationRange = function (name, from, to) {
  11231. // check name not already in use
  11232. if (!this._ranges[name]) {
  11233. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11234. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11235. if (this.animations[i]) {
  11236. this.animations[i].createRange(name, from, to);
  11237. }
  11238. }
  11239. }
  11240. };
  11241. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11242. if (deleteFrames === void 0) { deleteFrames = true; }
  11243. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11244. if (this.animations[i]) {
  11245. this.animations[i].deleteRange(name, deleteFrames);
  11246. }
  11247. }
  11248. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11249. };
  11250. Node.prototype.getAnimationRange = function (name) {
  11251. return this._ranges[name];
  11252. };
  11253. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11254. var range = this.getAnimationRange(name);
  11255. if (!range) {
  11256. return null;
  11257. }
  11258. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11259. };
  11260. Node.prototype.serializeAnimationRanges = function () {
  11261. var serializationRanges = [];
  11262. for (var name in this._ranges) {
  11263. var range = {};
  11264. range.name = name;
  11265. range.from = this._ranges[name].from;
  11266. range.to = this._ranges[name].to;
  11267. serializationRanges.push(range);
  11268. }
  11269. return serializationRanges;
  11270. };
  11271. Node.prototype.dispose = function () {
  11272. this.parent = null;
  11273. // Callback
  11274. this.onDisposeObservable.notifyObservers(this);
  11275. this.onDisposeObservable.clear();
  11276. };
  11277. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11278. if (parsedNode.ranges) {
  11279. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11280. var data = parsedNode.ranges[index];
  11281. node.createAnimationRange(data.name, data.from, data.to);
  11282. }
  11283. }
  11284. };
  11285. return Node;
  11286. }());
  11287. __decorate([
  11288. BABYLON.serialize()
  11289. ], Node.prototype, "name", void 0);
  11290. __decorate([
  11291. BABYLON.serialize()
  11292. ], Node.prototype, "id", void 0);
  11293. __decorate([
  11294. BABYLON.serialize()
  11295. ], Node.prototype, "uniqueId", void 0);
  11296. __decorate([
  11297. BABYLON.serialize()
  11298. ], Node.prototype, "state", void 0);
  11299. __decorate([
  11300. BABYLON.serialize()
  11301. ], Node.prototype, "metadata", void 0);
  11302. BABYLON.Node = Node;
  11303. })(BABYLON || (BABYLON = {}));
  11304. //# sourceMappingURL=babylon.node.js.map
  11305. var BABYLON;
  11306. (function (BABYLON) {
  11307. var FilesInput = (function () {
  11308. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11309. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11310. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11311. this._engine = p_engine;
  11312. this._canvas = p_canvas;
  11313. this._currentScene = p_scene;
  11314. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11315. this._progressCallback = p_progressCallback;
  11316. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11317. this._textureLoadingCallback = p_textureLoadingCallback;
  11318. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11319. }
  11320. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11321. var _this = this;
  11322. if (p_elementToMonitor) {
  11323. this._elementToMonitor = p_elementToMonitor;
  11324. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11325. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11326. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11327. }
  11328. };
  11329. FilesInput.prototype.renderFunction = function () {
  11330. if (this._additionnalRenderLoopLogicCallback) {
  11331. this._additionnalRenderLoopLogicCallback();
  11332. }
  11333. if (this._currentScene) {
  11334. if (this._textureLoadingCallback) {
  11335. var remaining = this._currentScene.getWaitingItemsCount();
  11336. if (remaining > 0) {
  11337. this._textureLoadingCallback(remaining);
  11338. }
  11339. }
  11340. this._currentScene.render();
  11341. }
  11342. };
  11343. FilesInput.prototype.drag = function (e) {
  11344. e.stopPropagation();
  11345. e.preventDefault();
  11346. };
  11347. FilesInput.prototype.drop = function (eventDrop) {
  11348. eventDrop.stopPropagation();
  11349. eventDrop.preventDefault();
  11350. this.loadFiles(eventDrop);
  11351. };
  11352. FilesInput.prototype.loadFiles = function (event) {
  11353. if (this._startingProcessingFilesCallback)
  11354. this._startingProcessingFilesCallback();
  11355. // Handling data transfer via drag'n'drop
  11356. if (event && event.dataTransfer && event.dataTransfer.files) {
  11357. this._filesToLoad = event.dataTransfer.files;
  11358. }
  11359. // Handling files from input files
  11360. if (event && event.target && event.target.files) {
  11361. this._filesToLoad = event.target.files;
  11362. }
  11363. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11364. for (var i = 0; i < this._filesToLoad.length; i++) {
  11365. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11366. var extension = name_1.split('.').pop();
  11367. var type = this._filesToLoad[i].type;
  11368. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  11369. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11370. this._sceneFileToLoad = this._filesToLoad[i];
  11371. }
  11372. else {
  11373. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11374. }
  11375. }
  11376. this.reload();
  11377. }
  11378. };
  11379. FilesInput.prototype.reload = function () {
  11380. var _this = this;
  11381. var that = this;
  11382. // If a ".babylon" file has been provided
  11383. if (this._sceneFileToLoad) {
  11384. if (this._currentScene) {
  11385. if (BABYLON.Tools.errorsCount > 0) {
  11386. BABYLON.Tools.ClearLogCache();
  11387. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11388. }
  11389. this._engine.stopRenderLoop();
  11390. this._currentScene.dispose();
  11391. }
  11392. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11393. that._currentScene = newScene;
  11394. // Wait for textures and shaders to be ready
  11395. that._currentScene.executeWhenReady(function () {
  11396. if (that._sceneLoadedCallback) {
  11397. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11398. }
  11399. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11400. });
  11401. }, function (progress) {
  11402. if (_this._progressCallback) {
  11403. _this._progressCallback(progress);
  11404. }
  11405. });
  11406. }
  11407. else {
  11408. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11409. }
  11410. };
  11411. return FilesInput;
  11412. }());
  11413. FilesInput.FilesToLoad = new Array();
  11414. BABYLON.FilesInput = FilesInput;
  11415. })(BABYLON || (BABYLON = {}));
  11416. //# sourceMappingURL=babylon.filesInput.js.map
  11417. var BABYLON;
  11418. (function (BABYLON) {
  11419. var IntersectionInfo = (function () {
  11420. function IntersectionInfo(bu, bv, distance) {
  11421. this.bu = bu;
  11422. this.bv = bv;
  11423. this.distance = distance;
  11424. this.faceId = 0;
  11425. this.subMeshId = 0;
  11426. }
  11427. return IntersectionInfo;
  11428. }());
  11429. BABYLON.IntersectionInfo = IntersectionInfo;
  11430. var PickingInfo = (function () {
  11431. function PickingInfo() {
  11432. this.hit = false;
  11433. this.distance = 0;
  11434. this.pickedPoint = null;
  11435. this.pickedMesh = null;
  11436. this.bu = 0;
  11437. this.bv = 0;
  11438. this.faceId = -1;
  11439. this.subMeshId = 0;
  11440. this.pickedSprite = null;
  11441. }
  11442. // Methods
  11443. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11444. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11445. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11446. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11447. return null;
  11448. }
  11449. var indices = this.pickedMesh.getIndices();
  11450. var result;
  11451. if (useVerticesNormals) {
  11452. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11453. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11454. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11455. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11456. normal0 = normal0.scale(this.bu);
  11457. normal1 = normal1.scale(this.bv);
  11458. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11459. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11460. }
  11461. else {
  11462. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11463. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11464. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11465. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11466. var p1p2 = vertex1.subtract(vertex2);
  11467. var p3p2 = vertex3.subtract(vertex2);
  11468. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11469. }
  11470. if (useWorldCoordinates) {
  11471. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11472. }
  11473. return BABYLON.Vector3.Normalize(result);
  11474. };
  11475. PickingInfo.prototype.getTextureCoordinates = function () {
  11476. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11477. return null;
  11478. }
  11479. var indices = this.pickedMesh.getIndices();
  11480. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11481. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11482. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11483. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11484. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11485. uv1 = uv1.scale(this.bu);
  11486. uv2 = uv2.scale(this.bv);
  11487. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11488. };
  11489. return PickingInfo;
  11490. }());
  11491. BABYLON.PickingInfo = PickingInfo;
  11492. })(BABYLON || (BABYLON = {}));
  11493. //# sourceMappingURL=babylon.pickingInfo.js.map
  11494. var BABYLON;
  11495. (function (BABYLON) {
  11496. var BoundingSphere = (function () {
  11497. function BoundingSphere(minimum, maximum) {
  11498. this.minimum = minimum;
  11499. this.maximum = maximum;
  11500. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11501. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11502. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11503. this.radius = distance * 0.5;
  11504. this.centerWorld = BABYLON.Vector3.Zero();
  11505. this._update(BABYLON.Matrix.Identity());
  11506. }
  11507. // Methods
  11508. BoundingSphere.prototype._update = function (world) {
  11509. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11510. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11511. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11512. };
  11513. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11514. for (var i = 0; i < 6; i++) {
  11515. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11516. return false;
  11517. }
  11518. return true;
  11519. };
  11520. BoundingSphere.prototype.intersectsPoint = function (point) {
  11521. var x = this.centerWorld.x - point.x;
  11522. var y = this.centerWorld.y - point.y;
  11523. var z = this.centerWorld.z - point.z;
  11524. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11525. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11526. return false;
  11527. return true;
  11528. };
  11529. // Statics
  11530. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11531. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11532. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11533. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11534. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11535. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11536. return false;
  11537. return true;
  11538. };
  11539. return BoundingSphere;
  11540. }());
  11541. BABYLON.BoundingSphere = BoundingSphere;
  11542. })(BABYLON || (BABYLON = {}));
  11543. //# sourceMappingURL=babylon.boundingSphere.js.map
  11544. var BABYLON;
  11545. (function (BABYLON) {
  11546. var BoundingBox = (function () {
  11547. function BoundingBox(minimum, maximum) {
  11548. this.minimum = minimum;
  11549. this.maximum = maximum;
  11550. this.vectors = new Array();
  11551. this.vectorsWorld = new Array();
  11552. // Bounding vectors
  11553. this.vectors.push(this.minimum.clone());
  11554. this.vectors.push(this.maximum.clone());
  11555. this.vectors.push(this.minimum.clone());
  11556. this.vectors[2].x = this.maximum.x;
  11557. this.vectors.push(this.minimum.clone());
  11558. this.vectors[3].y = this.maximum.y;
  11559. this.vectors.push(this.minimum.clone());
  11560. this.vectors[4].z = this.maximum.z;
  11561. this.vectors.push(this.maximum.clone());
  11562. this.vectors[5].z = this.minimum.z;
  11563. this.vectors.push(this.maximum.clone());
  11564. this.vectors[6].x = this.minimum.x;
  11565. this.vectors.push(this.maximum.clone());
  11566. this.vectors[7].y = this.minimum.y;
  11567. // OBB
  11568. this.center = this.maximum.add(this.minimum).scale(0.5);
  11569. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11570. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11571. // World
  11572. for (var index = 0; index < this.vectors.length; index++) {
  11573. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11574. }
  11575. this.minimumWorld = BABYLON.Vector3.Zero();
  11576. this.maximumWorld = BABYLON.Vector3.Zero();
  11577. this.centerWorld = BABYLON.Vector3.Zero();
  11578. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11579. this._update(BABYLON.Matrix.Identity());
  11580. }
  11581. // Methods
  11582. BoundingBox.prototype.getWorldMatrix = function () {
  11583. return this._worldMatrix;
  11584. };
  11585. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11586. this._worldMatrix.copyFrom(matrix);
  11587. return this;
  11588. };
  11589. BoundingBox.prototype._update = function (world) {
  11590. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11591. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11592. for (var index = 0; index < this.vectors.length; index++) {
  11593. var v = this.vectorsWorld[index];
  11594. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11595. if (v.x < this.minimumWorld.x)
  11596. this.minimumWorld.x = v.x;
  11597. if (v.y < this.minimumWorld.y)
  11598. this.minimumWorld.y = v.y;
  11599. if (v.z < this.minimumWorld.z)
  11600. this.minimumWorld.z = v.z;
  11601. if (v.x > this.maximumWorld.x)
  11602. this.maximumWorld.x = v.x;
  11603. if (v.y > this.maximumWorld.y)
  11604. this.maximumWorld.y = v.y;
  11605. if (v.z > this.maximumWorld.z)
  11606. this.maximumWorld.z = v.z;
  11607. }
  11608. // Extend
  11609. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11610. this.extendSizeWorld.scaleInPlace(0.5);
  11611. // OBB
  11612. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11613. this.centerWorld.scaleInPlace(0.5);
  11614. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11615. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11616. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11617. this._worldMatrix = world;
  11618. };
  11619. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11620. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11621. };
  11622. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11623. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11624. };
  11625. BoundingBox.prototype.intersectsPoint = function (point) {
  11626. var delta = -BABYLON.Epsilon;
  11627. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11628. return false;
  11629. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11630. return false;
  11631. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11632. return false;
  11633. return true;
  11634. };
  11635. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11636. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11637. };
  11638. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11639. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11640. return false;
  11641. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11642. return false;
  11643. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11644. return false;
  11645. return true;
  11646. };
  11647. // Statics
  11648. BoundingBox.Intersects = function (box0, box1) {
  11649. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11650. return false;
  11651. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11652. return false;
  11653. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11654. return false;
  11655. return true;
  11656. };
  11657. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11658. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11659. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11660. return (num <= (sphereRadius * sphereRadius));
  11661. };
  11662. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11663. for (var p = 0; p < 6; p++) {
  11664. for (var i = 0; i < 8; i++) {
  11665. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11666. return false;
  11667. }
  11668. }
  11669. }
  11670. return true;
  11671. };
  11672. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11673. for (var p = 0; p < 6; p++) {
  11674. var inCount = 8;
  11675. for (var i = 0; i < 8; i++) {
  11676. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11677. --inCount;
  11678. }
  11679. else {
  11680. break;
  11681. }
  11682. }
  11683. if (inCount === 0)
  11684. return false;
  11685. }
  11686. return true;
  11687. };
  11688. return BoundingBox;
  11689. }());
  11690. BABYLON.BoundingBox = BoundingBox;
  11691. })(BABYLON || (BABYLON = {}));
  11692. //# sourceMappingURL=babylon.boundingBox.js.map
  11693. var BABYLON;
  11694. (function (BABYLON) {
  11695. var computeBoxExtents = function (axis, box) {
  11696. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11697. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11698. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11699. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11700. var r = r0 + r1 + r2;
  11701. return {
  11702. min: p - r,
  11703. max: p + r
  11704. };
  11705. };
  11706. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11707. var axisOverlap = function (axis, box0, box1) {
  11708. var result0 = computeBoxExtents(axis, box0);
  11709. var result1 = computeBoxExtents(axis, box1);
  11710. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11711. };
  11712. var BoundingInfo = (function () {
  11713. function BoundingInfo(minimum, maximum) {
  11714. this.minimum = minimum;
  11715. this.maximum = maximum;
  11716. this._isLocked = false;
  11717. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11718. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11719. }
  11720. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11721. get: function () {
  11722. return this._isLocked;
  11723. },
  11724. set: function (value) {
  11725. this._isLocked = value;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. // Methods
  11731. BoundingInfo.prototype.update = function (world) {
  11732. if (this._isLocked) {
  11733. return;
  11734. }
  11735. this.boundingBox._update(world);
  11736. this.boundingSphere._update(world);
  11737. };
  11738. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11739. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11740. return false;
  11741. return this.boundingBox.isInFrustum(frustumPlanes);
  11742. };
  11743. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11744. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11745. };
  11746. BoundingInfo.prototype._checkCollision = function (collider) {
  11747. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11748. };
  11749. BoundingInfo.prototype.intersectsPoint = function (point) {
  11750. if (!this.boundingSphere.centerWorld) {
  11751. return false;
  11752. }
  11753. if (!this.boundingSphere.intersectsPoint(point)) {
  11754. return false;
  11755. }
  11756. if (!this.boundingBox.intersectsPoint(point)) {
  11757. return false;
  11758. }
  11759. return true;
  11760. };
  11761. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11762. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11763. return false;
  11764. }
  11765. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11766. return false;
  11767. }
  11768. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11769. return false;
  11770. }
  11771. if (!precise) {
  11772. return true;
  11773. }
  11774. var box0 = this.boundingBox;
  11775. var box1 = boundingInfo.boundingBox;
  11776. if (!axisOverlap(box0.directions[0], box0, box1))
  11777. return false;
  11778. if (!axisOverlap(box0.directions[1], box0, box1))
  11779. return false;
  11780. if (!axisOverlap(box0.directions[2], box0, box1))
  11781. return false;
  11782. if (!axisOverlap(box1.directions[0], box0, box1))
  11783. return false;
  11784. if (!axisOverlap(box1.directions[1], box0, box1))
  11785. return false;
  11786. if (!axisOverlap(box1.directions[2], box0, box1))
  11787. return false;
  11788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11789. return false;
  11790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11791. return false;
  11792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11793. return false;
  11794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11795. return false;
  11796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11797. return false;
  11798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11799. return false;
  11800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11801. return false;
  11802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11803. return false;
  11804. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11805. return false;
  11806. return true;
  11807. };
  11808. return BoundingInfo;
  11809. }());
  11810. BABYLON.BoundingInfo = BoundingInfo;
  11811. })(BABYLON || (BABYLON = {}));
  11812. //# sourceMappingURL=babylon.boundingInfo.js.map
  11813. var BABYLON;
  11814. (function (BABYLON) {
  11815. var Ray = (function () {
  11816. function Ray(origin, direction, length) {
  11817. if (length === void 0) { length = Number.MAX_VALUE; }
  11818. this.origin = origin;
  11819. this.direction = direction;
  11820. this.length = length;
  11821. }
  11822. // Methods
  11823. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11824. var d = 0.0;
  11825. var maxValue = Number.MAX_VALUE;
  11826. var inv;
  11827. var min;
  11828. var max;
  11829. var temp;
  11830. if (Math.abs(this.direction.x) < 0.0000001) {
  11831. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11832. return false;
  11833. }
  11834. }
  11835. else {
  11836. inv = 1.0 / this.direction.x;
  11837. min = (minimum.x - this.origin.x) * inv;
  11838. max = (maximum.x - this.origin.x) * inv;
  11839. if (max === -Infinity) {
  11840. max = Infinity;
  11841. }
  11842. if (min > max) {
  11843. temp = min;
  11844. min = max;
  11845. max = temp;
  11846. }
  11847. d = Math.max(min, d);
  11848. maxValue = Math.min(max, maxValue);
  11849. if (d > maxValue) {
  11850. return false;
  11851. }
  11852. }
  11853. if (Math.abs(this.direction.y) < 0.0000001) {
  11854. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11855. return false;
  11856. }
  11857. }
  11858. else {
  11859. inv = 1.0 / this.direction.y;
  11860. min = (minimum.y - this.origin.y) * inv;
  11861. max = (maximum.y - this.origin.y) * inv;
  11862. if (max === -Infinity) {
  11863. max = Infinity;
  11864. }
  11865. if (min > max) {
  11866. temp = min;
  11867. min = max;
  11868. max = temp;
  11869. }
  11870. d = Math.max(min, d);
  11871. maxValue = Math.min(max, maxValue);
  11872. if (d > maxValue) {
  11873. return false;
  11874. }
  11875. }
  11876. if (Math.abs(this.direction.z) < 0.0000001) {
  11877. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11878. return false;
  11879. }
  11880. }
  11881. else {
  11882. inv = 1.0 / this.direction.z;
  11883. min = (minimum.z - this.origin.z) * inv;
  11884. max = (maximum.z - this.origin.z) * inv;
  11885. if (max === -Infinity) {
  11886. max = Infinity;
  11887. }
  11888. if (min > max) {
  11889. temp = min;
  11890. min = max;
  11891. max = temp;
  11892. }
  11893. d = Math.max(min, d);
  11894. maxValue = Math.min(max, maxValue);
  11895. if (d > maxValue) {
  11896. return false;
  11897. }
  11898. }
  11899. return true;
  11900. };
  11901. Ray.prototype.intersectsBox = function (box) {
  11902. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11903. };
  11904. Ray.prototype.intersectsSphere = function (sphere) {
  11905. var x = sphere.center.x - this.origin.x;
  11906. var y = sphere.center.y - this.origin.y;
  11907. var z = sphere.center.z - this.origin.z;
  11908. var pyth = (x * x) + (y * y) + (z * z);
  11909. var rr = sphere.radius * sphere.radius;
  11910. if (pyth <= rr) {
  11911. return true;
  11912. }
  11913. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11914. if (dot < 0.0) {
  11915. return false;
  11916. }
  11917. var temp = pyth - (dot * dot);
  11918. return temp <= rr;
  11919. };
  11920. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11921. if (!this._edge1) {
  11922. this._edge1 = BABYLON.Vector3.Zero();
  11923. this._edge2 = BABYLON.Vector3.Zero();
  11924. this._pvec = BABYLON.Vector3.Zero();
  11925. this._tvec = BABYLON.Vector3.Zero();
  11926. this._qvec = BABYLON.Vector3.Zero();
  11927. }
  11928. vertex1.subtractToRef(vertex0, this._edge1);
  11929. vertex2.subtractToRef(vertex0, this._edge2);
  11930. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11931. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11932. if (det === 0) {
  11933. return null;
  11934. }
  11935. var invdet = 1 / det;
  11936. this.origin.subtractToRef(vertex0, this._tvec);
  11937. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11938. if (bu < 0 || bu > 1.0) {
  11939. return null;
  11940. }
  11941. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11942. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11943. if (bv < 0 || bu + bv > 1.0) {
  11944. return null;
  11945. }
  11946. //check if the distance is longer than the predefined length.
  11947. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11948. if (distance > this.length) {
  11949. return null;
  11950. }
  11951. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11952. };
  11953. Ray.prototype.intersectsPlane = function (plane) {
  11954. var distance;
  11955. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11956. if (Math.abs(result1) < 9.99999997475243E-07) {
  11957. return null;
  11958. }
  11959. else {
  11960. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11961. distance = (-plane.d - result2) / result1;
  11962. if (distance < 0.0) {
  11963. if (distance < -9.99999997475243E-07) {
  11964. return null;
  11965. }
  11966. else {
  11967. return 0;
  11968. }
  11969. }
  11970. return distance;
  11971. }
  11972. };
  11973. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11974. var tm = BABYLON.Tmp.Matrix[0];
  11975. mesh.getWorldMatrix().invertToRef(tm);
  11976. if (this._tmpRay) {
  11977. Ray.TransformToRef(this, tm, this._tmpRay);
  11978. }
  11979. else {
  11980. this._tmpRay = Ray.Transform(this, tm);
  11981. }
  11982. return mesh.intersects(this._tmpRay, fastCheck);
  11983. };
  11984. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11985. if (results) {
  11986. results.length = 0;
  11987. }
  11988. else {
  11989. results = [];
  11990. }
  11991. for (var i = 0; i < meshes.length; i++) {
  11992. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11993. if (pickInfo.hit) {
  11994. results.push(pickInfo);
  11995. }
  11996. }
  11997. results.sort(this._comparePickingInfo);
  11998. return results;
  11999. };
  12000. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  12001. if (pickingInfoA.distance < pickingInfoB.distance) {
  12002. return -1;
  12003. }
  12004. else if (pickingInfoA.distance > pickingInfoB.distance) {
  12005. return 1;
  12006. }
  12007. else {
  12008. return 0;
  12009. }
  12010. };
  12011. /**
  12012. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  12013. * @param sega the first point of the segment to test the intersection against
  12014. * @param segb the second point of the segment to test the intersection against
  12015. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  12016. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  12017. */
  12018. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  12019. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  12020. var u = segb.subtract(sega);
  12021. var v = rsegb.subtract(this.origin);
  12022. var w = sega.subtract(this.origin);
  12023. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  12024. var b = BABYLON.Vector3.Dot(u, v);
  12025. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  12026. var d = BABYLON.Vector3.Dot(u, w);
  12027. var e = BABYLON.Vector3.Dot(v, w);
  12028. var D = a * c - b * b; // always >= 0
  12029. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  12030. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  12031. // compute the line parameters of the two closest points
  12032. if (D < Ray.smallnum) {
  12033. sN = 0.0; // force using point P0 on segment S1
  12034. sD = 1.0; // to prevent possible division by 0.0 later
  12035. tN = e;
  12036. tD = c;
  12037. }
  12038. else {
  12039. sN = (b * e - c * d);
  12040. tN = (a * e - b * d);
  12041. if (sN < 0.0) {
  12042. sN = 0.0;
  12043. tN = e;
  12044. tD = c;
  12045. }
  12046. else if (sN > sD) {
  12047. sN = sD;
  12048. tN = e + b;
  12049. tD = c;
  12050. }
  12051. }
  12052. if (tN < 0.0) {
  12053. tN = 0.0;
  12054. // recompute sc for this edge
  12055. if (-d < 0.0) {
  12056. sN = 0.0;
  12057. }
  12058. else if (-d > a)
  12059. sN = sD;
  12060. else {
  12061. sN = -d;
  12062. sD = a;
  12063. }
  12064. }
  12065. else if (tN > tD) {
  12066. tN = tD;
  12067. // recompute sc for this edge
  12068. if ((-d + b) < 0.0) {
  12069. sN = 0;
  12070. }
  12071. else if ((-d + b) > a) {
  12072. sN = sD;
  12073. }
  12074. else {
  12075. sN = (-d + b);
  12076. sD = a;
  12077. }
  12078. }
  12079. // finally do the division to get sc and tc
  12080. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  12081. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  12082. // get the difference of the two closest points
  12083. var qtc = v.multiplyByFloats(tc, tc, tc);
  12084. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  12085. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  12086. if (isIntersected) {
  12087. return qtc.length();
  12088. }
  12089. return -1;
  12090. };
  12091. // Statics
  12092. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  12093. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  12094. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  12095. var direction = end.subtract(start);
  12096. direction.normalize();
  12097. return new Ray(start, direction);
  12098. };
  12099. /**
  12100. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  12101. * transformed to the given world matrix.
  12102. * @param origin The origin point
  12103. * @param end The end point
  12104. * @param world a matrix to transform the ray to. Default is the identity matrix.
  12105. */
  12106. Ray.CreateNewFromTo = function (origin, end, world) {
  12107. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  12108. var direction = end.subtract(origin);
  12109. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  12110. direction.normalize();
  12111. return Ray.Transform(new Ray(origin, direction, length), world);
  12112. };
  12113. Ray.Transform = function (ray, matrix) {
  12114. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  12115. Ray.TransformToRef(ray, matrix, result);
  12116. return result;
  12117. };
  12118. Ray.TransformToRef = function (ray, matrix, result) {
  12119. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  12120. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  12121. result.length = ray.length;
  12122. var dir = result.direction;
  12123. var len = dir.length();
  12124. if (!(len === 0 || len === 1)) {
  12125. var num = 1.0 / len;
  12126. dir.x *= num;
  12127. dir.y *= num;
  12128. dir.z *= num;
  12129. result.length *= len;
  12130. }
  12131. };
  12132. return Ray;
  12133. }());
  12134. Ray.smallnum = 0.00000001;
  12135. Ray.rayl = 10e8;
  12136. BABYLON.Ray = Ray;
  12137. })(BABYLON || (BABYLON = {}));
  12138. //# sourceMappingURL=babylon.ray.js.map
  12139. var BABYLON;
  12140. (function (BABYLON) {
  12141. var RayHelper = (function () {
  12142. function RayHelper(ray) {
  12143. this.ray = ray;
  12144. }
  12145. RayHelper.CreateAndShow = function (ray, scene, color) {
  12146. var helper = new RayHelper(ray);
  12147. helper.show(scene, color);
  12148. return helper;
  12149. };
  12150. RayHelper.prototype.show = function (scene, color) {
  12151. if (!this._renderFunction) {
  12152. var ray = this.ray;
  12153. this._renderFunction = this._render.bind(this);
  12154. this._scene = scene;
  12155. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  12156. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  12157. this._scene.registerBeforeRender(this._renderFunction);
  12158. }
  12159. if (color) {
  12160. this._renderLine.color.copyFrom(color);
  12161. }
  12162. };
  12163. RayHelper.prototype.hide = function () {
  12164. if (this._renderFunction) {
  12165. this._scene.unregisterBeforeRender(this._renderFunction);
  12166. this._scene = null;
  12167. this._renderFunction = null;
  12168. this._renderLine.dispose();
  12169. this._renderLine = null;
  12170. this._renderPoints = null;
  12171. }
  12172. };
  12173. RayHelper.prototype._render = function () {
  12174. var ray = this.ray;
  12175. var point = this._renderPoints[1];
  12176. var len = Math.min(ray.length, 1000000);
  12177. point.copyFrom(ray.direction);
  12178. point.scaleInPlace(len);
  12179. point.addInPlace(ray.origin);
  12180. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  12181. };
  12182. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  12183. this._attachedToMesh = mesh;
  12184. var ray = this.ray;
  12185. if (!ray.direction) {
  12186. ray.direction = BABYLON.Vector3.Zero();
  12187. }
  12188. if (!ray.origin) {
  12189. ray.origin = BABYLON.Vector3.Zero();
  12190. }
  12191. if (length) {
  12192. ray.length = length;
  12193. }
  12194. if (!meshSpaceOrigin) {
  12195. meshSpaceOrigin = BABYLON.Vector3.Zero();
  12196. }
  12197. if (!meshSpaceDirection) {
  12198. // -1 so that this will work with Mesh.lookAt
  12199. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  12200. }
  12201. if (!this._meshSpaceDirection) {
  12202. this._meshSpaceDirection = meshSpaceDirection.clone();
  12203. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  12204. }
  12205. else {
  12206. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  12207. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  12208. }
  12209. if (!this._updateToMeshFunction) {
  12210. this._updateToMeshFunction = this._updateToMesh.bind(this);
  12211. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  12212. }
  12213. this._updateToMesh();
  12214. };
  12215. RayHelper.prototype.detachFromMesh = function () {
  12216. if (this._attachedToMesh) {
  12217. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  12218. this._attachedToMesh = null;
  12219. this._updateToMeshFunction = null;
  12220. }
  12221. };
  12222. RayHelper.prototype._updateToMesh = function () {
  12223. var ray = this.ray;
  12224. if (this._attachedToMesh._isDisposed) {
  12225. this.detachFromMesh();
  12226. return;
  12227. }
  12228. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12229. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12230. };
  12231. RayHelper.prototype.dispose = function () {
  12232. this.hide();
  12233. this.detachFromMesh();
  12234. this.ray = null;
  12235. };
  12236. return RayHelper;
  12237. }());
  12238. BABYLON.RayHelper = RayHelper;
  12239. })(BABYLON || (BABYLON = {}));
  12240. //# sourceMappingURL=babylon.rayHelper.js.map
  12241. var BABYLON;
  12242. (function (BABYLON) {
  12243. var AbstractMesh = (function (_super) {
  12244. __extends(AbstractMesh, _super);
  12245. // Constructor
  12246. function AbstractMesh(name, scene) {
  12247. var _this = _super.call(this, name, scene) || this;
  12248. _this._facetNb = 0; // facet number
  12249. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12250. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12251. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12252. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12253. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12254. _this._subDiv = {
  12255. max: 1,
  12256. X: 1,
  12257. Y: 1,
  12258. Z: 1
  12259. };
  12260. // Events
  12261. /**
  12262. * An event triggered when this mesh collides with another one
  12263. * @type {BABYLON.Observable}
  12264. */
  12265. _this.onCollideObservable = new BABYLON.Observable();
  12266. /**
  12267. * An event triggered when the collision's position changes
  12268. * @type {BABYLON.Observable}
  12269. */
  12270. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12271. /**
  12272. * An event triggered after the world matrix is updated
  12273. * @type {BABYLON.Observable}
  12274. */
  12275. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12276. // Properties
  12277. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12278. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12279. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12280. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12281. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12282. _this.visibility = 1.0;
  12283. _this.alphaIndex = Number.MAX_VALUE;
  12284. _this.infiniteDistance = false;
  12285. _this.isVisible = true;
  12286. _this.isPickable = true;
  12287. _this.showBoundingBox = false;
  12288. _this.showSubMeshesBoundingBox = false;
  12289. _this.isBlocker = false;
  12290. _this.renderingGroupId = 0;
  12291. _this._receiveShadows = false;
  12292. _this.renderOutline = false;
  12293. _this.outlineColor = BABYLON.Color3.Red();
  12294. _this.outlineWidth = 0.02;
  12295. _this.renderOverlay = false;
  12296. _this.overlayColor = BABYLON.Color3.Red();
  12297. _this.overlayAlpha = 0.5;
  12298. _this._hasVertexAlpha = false;
  12299. _this._useVertexColors = true;
  12300. _this._computeBonesUsingShaders = true;
  12301. _this._numBoneInfluencers = 4;
  12302. _this._applyFog = true;
  12303. _this.scalingDeterminant = 1;
  12304. _this.useOctreeForRenderingSelection = true;
  12305. _this.useOctreeForPicking = true;
  12306. _this.useOctreeForCollisions = true;
  12307. _this.layerMask = 0x0FFFFFFF;
  12308. /**
  12309. * True if the mesh must be rendered in any case.
  12310. */
  12311. _this.alwaysSelectAsActiveMesh = false;
  12312. // Collisions
  12313. _this._checkCollisions = false;
  12314. _this._collisionMask = -1;
  12315. _this._collisionGroup = -1;
  12316. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12317. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12318. _this._collider = new BABYLON.Collider();
  12319. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12320. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12321. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12322. // Edges
  12323. _this.edgesWidth = 1;
  12324. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12325. // Cache
  12326. _this._localWorld = BABYLON.Matrix.Zero();
  12327. _this._worldMatrix = BABYLON.Matrix.Zero();
  12328. _this._absolutePosition = BABYLON.Vector3.Zero();
  12329. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12330. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12331. _this._isDirty = false;
  12332. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12333. _this._isDisposed = false;
  12334. _this._renderId = 0;
  12335. _this._intersectionsInProgress = new Array();
  12336. _this._isWorldMatrixFrozen = false;
  12337. _this._unIndexed = false;
  12338. _this._lightSources = new Array();
  12339. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12340. if (collidedMesh === void 0) { collidedMesh = null; }
  12341. //TODO move this to the collision coordinator!
  12342. if (_this.getScene().workerCollisions)
  12343. newPosition.multiplyInPlace(_this._collider.radius);
  12344. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12345. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12346. _this.position.addInPlace(_this._diffPositionForCollisions);
  12347. }
  12348. if (collidedMesh) {
  12349. _this.onCollideObservable.notifyObservers(collidedMesh);
  12350. }
  12351. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12352. };
  12353. _this.getScene().addMesh(_this);
  12354. _this._resyncLightSources();
  12355. return _this;
  12356. }
  12357. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12358. get: function () {
  12359. return AbstractMesh._BILLBOARDMODE_NONE;
  12360. },
  12361. enumerable: true,
  12362. configurable: true
  12363. });
  12364. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12365. get: function () {
  12366. return AbstractMesh._BILLBOARDMODE_X;
  12367. },
  12368. enumerable: true,
  12369. configurable: true
  12370. });
  12371. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12372. get: function () {
  12373. return AbstractMesh._BILLBOARDMODE_Y;
  12374. },
  12375. enumerable: true,
  12376. configurable: true
  12377. });
  12378. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12379. get: function () {
  12380. return AbstractMesh._BILLBOARDMODE_Z;
  12381. },
  12382. enumerable: true,
  12383. configurable: true
  12384. });
  12385. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12386. get: function () {
  12387. return AbstractMesh._BILLBOARDMODE_ALL;
  12388. },
  12389. enumerable: true,
  12390. configurable: true
  12391. });
  12392. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12393. /**
  12394. * Read-only : the number of facets in the mesh
  12395. */
  12396. get: function () {
  12397. return this._facetNb;
  12398. },
  12399. enumerable: true,
  12400. configurable: true
  12401. });
  12402. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12403. /**
  12404. * The number (integer) of subdivisions per axis in the partioning space
  12405. */
  12406. get: function () {
  12407. return this._partitioningSubdivisions;
  12408. },
  12409. set: function (nb) {
  12410. this._partitioningSubdivisions = nb;
  12411. },
  12412. enumerable: true,
  12413. configurable: true
  12414. });
  12415. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12416. /**
  12417. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12418. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12419. */
  12420. get: function () {
  12421. return this._partitioningBBoxRatio;
  12422. },
  12423. set: function (ratio) {
  12424. this._partitioningBBoxRatio = ratio;
  12425. },
  12426. enumerable: true,
  12427. configurable: true
  12428. });
  12429. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12430. /**
  12431. * Read-only boolean : is the feature facetData enabled ?
  12432. */
  12433. get: function () {
  12434. return this._facetDataEnabled;
  12435. },
  12436. enumerable: true,
  12437. configurable: true
  12438. });
  12439. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12440. set: function (callback) {
  12441. if (this._onCollideObserver) {
  12442. this.onCollideObservable.remove(this._onCollideObserver);
  12443. }
  12444. this._onCollideObserver = this.onCollideObservable.add(callback);
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12450. set: function (callback) {
  12451. if (this._onCollisionPositionChangeObserver) {
  12452. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12453. }
  12454. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(AbstractMesh.prototype, "material", {
  12460. get: function () {
  12461. return this._material;
  12462. },
  12463. set: function (value) {
  12464. if (this._material === value) {
  12465. return;
  12466. }
  12467. this._material = value;
  12468. if (!this.subMeshes) {
  12469. return;
  12470. }
  12471. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12472. var subMesh = _a[_i];
  12473. subMesh.setEffect(null);
  12474. }
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12480. get: function () {
  12481. return this._receiveShadows;
  12482. },
  12483. set: function (value) {
  12484. if (this._receiveShadows === value) {
  12485. return;
  12486. }
  12487. this._receiveShadows = value;
  12488. this._markSubMeshesAsLightDirty();
  12489. },
  12490. enumerable: true,
  12491. configurable: true
  12492. });
  12493. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12494. get: function () {
  12495. return this._hasVertexAlpha;
  12496. },
  12497. set: function (value) {
  12498. if (this._hasVertexAlpha === value) {
  12499. return;
  12500. }
  12501. this._hasVertexAlpha = value;
  12502. this._markSubMeshesAsAttributesDirty();
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12508. get: function () {
  12509. return this._useVertexColors;
  12510. },
  12511. set: function (value) {
  12512. if (this._useVertexColors === value) {
  12513. return;
  12514. }
  12515. this._useVertexColors = value;
  12516. this._markSubMeshesAsAttributesDirty();
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12522. get: function () {
  12523. return this._computeBonesUsingShaders;
  12524. },
  12525. set: function (value) {
  12526. if (this._computeBonesUsingShaders === value) {
  12527. return;
  12528. }
  12529. this._computeBonesUsingShaders = value;
  12530. this._markSubMeshesAsAttributesDirty();
  12531. },
  12532. enumerable: true,
  12533. configurable: true
  12534. });
  12535. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12536. get: function () {
  12537. return this._numBoneInfluencers;
  12538. },
  12539. set: function (value) {
  12540. if (this._numBoneInfluencers === value) {
  12541. return;
  12542. }
  12543. this._numBoneInfluencers = value;
  12544. this._markSubMeshesAsAttributesDirty();
  12545. },
  12546. enumerable: true,
  12547. configurable: true
  12548. });
  12549. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12550. get: function () {
  12551. return this._applyFog;
  12552. },
  12553. set: function (value) {
  12554. if (this._applyFog === value) {
  12555. return;
  12556. }
  12557. this._applyFog = value;
  12558. this._markSubMeshesAsMiscDirty();
  12559. },
  12560. enumerable: true,
  12561. configurable: true
  12562. });
  12563. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12564. get: function () {
  12565. return this._collisionMask;
  12566. },
  12567. set: function (mask) {
  12568. this._collisionMask = !isNaN(mask) ? mask : -1;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12574. get: function () {
  12575. return this._collisionGroup;
  12576. },
  12577. set: function (mask) {
  12578. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12579. },
  12580. enumerable: true,
  12581. configurable: true
  12582. });
  12583. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12584. get: function () {
  12585. return this._skeleton;
  12586. },
  12587. set: function (value) {
  12588. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12589. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12590. }
  12591. if (value && value.needInitialSkinMatrix) {
  12592. value._registerMeshWithPoseMatrix(this);
  12593. }
  12594. this._skeleton = value;
  12595. if (!this._skeleton) {
  12596. this._bonesTransformMatrices = null;
  12597. }
  12598. this._markSubMeshesAsAttributesDirty();
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. /**
  12604. * Returns the string "AbstractMesh"
  12605. */
  12606. AbstractMesh.prototype.getClassName = function () {
  12607. return "AbstractMesh";
  12608. };
  12609. /**
  12610. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12611. */
  12612. AbstractMesh.prototype.toString = function (fullDetails) {
  12613. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12614. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12615. if (this._skeleton) {
  12616. ret += ", skeleton: " + this._skeleton.name;
  12617. }
  12618. if (fullDetails) {
  12619. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12620. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12621. }
  12622. return ret;
  12623. };
  12624. AbstractMesh.prototype._resyncLightSources = function () {
  12625. this._lightSources.length = 0;
  12626. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12627. var light = _a[_i];
  12628. if (!light.isEnabled()) {
  12629. continue;
  12630. }
  12631. if (light.canAffectMesh(this)) {
  12632. this._lightSources.push(light);
  12633. }
  12634. }
  12635. this._markSubMeshesAsLightDirty();
  12636. };
  12637. AbstractMesh.prototype._resyncLighSource = function (light) {
  12638. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12639. var index = this._lightSources.indexOf(light);
  12640. if (index === -1) {
  12641. if (!isIn) {
  12642. return;
  12643. }
  12644. this._lightSources.push(light);
  12645. }
  12646. else {
  12647. if (isIn) {
  12648. return;
  12649. }
  12650. this._lightSources.splice(index, 1);
  12651. }
  12652. this._markSubMeshesAsLightDirty();
  12653. };
  12654. AbstractMesh.prototype._removeLightSource = function (light) {
  12655. var index = this._lightSources.indexOf(light);
  12656. if (index === -1) {
  12657. return;
  12658. }
  12659. this._lightSources.splice(index, 1);
  12660. };
  12661. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12662. if (!this.subMeshes) {
  12663. return;
  12664. }
  12665. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12666. var subMesh = _a[_i];
  12667. if (subMesh._materialDefines) {
  12668. func(subMesh._materialDefines);
  12669. }
  12670. }
  12671. };
  12672. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12673. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12674. };
  12675. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12676. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12677. };
  12678. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12679. if (!this.subMeshes) {
  12680. return;
  12681. }
  12682. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12683. var subMesh = _a[_i];
  12684. var material = subMesh.getMaterial();
  12685. if (material) {
  12686. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12687. }
  12688. }
  12689. };
  12690. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12691. /**
  12692. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12693. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12694. * Default : (0.0, 0.0, 0.0)
  12695. */
  12696. get: function () {
  12697. return this._rotation;
  12698. },
  12699. set: function (newRotation) {
  12700. this._rotation = newRotation;
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12706. /**
  12707. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12708. * Default : (1.0, 1.0, 1.0)
  12709. */
  12710. get: function () {
  12711. return this._scaling;
  12712. },
  12713. set: function (newScaling) {
  12714. this._scaling = newScaling;
  12715. if (this.physicsImpostor) {
  12716. this.physicsImpostor.forceUpdate();
  12717. }
  12718. },
  12719. enumerable: true,
  12720. configurable: true
  12721. });
  12722. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12723. /**
  12724. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12725. * It's null by default.
  12726. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12727. */
  12728. get: function () {
  12729. return this._rotationQuaternion;
  12730. },
  12731. set: function (quaternion) {
  12732. this._rotationQuaternion = quaternion;
  12733. //reset the rotation vector.
  12734. if (quaternion && this.rotation.length()) {
  12735. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12736. }
  12737. },
  12738. enumerable: true,
  12739. configurable: true
  12740. });
  12741. // Methods
  12742. /**
  12743. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12744. * Returns the AbstractMesh.
  12745. */
  12746. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12747. this._poseMatrix.copyFrom(matrix);
  12748. return this;
  12749. };
  12750. /**
  12751. * Returns the mesh Pose matrix.
  12752. * Returned object : Matrix
  12753. */
  12754. AbstractMesh.prototype.getPoseMatrix = function () {
  12755. return this._poseMatrix;
  12756. };
  12757. /**
  12758. * Disables the mesh edger rendering mode.
  12759. * Returns the AbstractMesh.
  12760. */
  12761. AbstractMesh.prototype.disableEdgesRendering = function () {
  12762. if (this._edgesRenderer !== undefined) {
  12763. this._edgesRenderer.dispose();
  12764. this._edgesRenderer = undefined;
  12765. }
  12766. return this;
  12767. };
  12768. /**
  12769. * Enables the edge rendering mode on the mesh.
  12770. * This mode makes the mesh edges visible.
  12771. * Returns the AbstractMesh.
  12772. */
  12773. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12774. if (epsilon === void 0) { epsilon = 0.95; }
  12775. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12776. this.disableEdgesRendering();
  12777. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12778. return this;
  12779. };
  12780. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12781. /**
  12782. * Returns true if the mesh is blocked. Used by the class Mesh.
  12783. * Returns the boolean `false` by default.
  12784. */
  12785. get: function () {
  12786. return false;
  12787. },
  12788. enumerable: true,
  12789. configurable: true
  12790. });
  12791. /**
  12792. * Returns the mesh itself by default, used by the class Mesh.
  12793. * Returned type : AbstractMesh
  12794. */
  12795. AbstractMesh.prototype.getLOD = function (camera) {
  12796. return this;
  12797. };
  12798. /**
  12799. * Returns 0 by default, used by the class Mesh.
  12800. * Returns an integer.
  12801. */
  12802. AbstractMesh.prototype.getTotalVertices = function () {
  12803. return 0;
  12804. };
  12805. /**
  12806. * Returns null by default, used by the class Mesh.
  12807. * Returned type : integer array
  12808. */
  12809. AbstractMesh.prototype.getIndices = function () {
  12810. return null;
  12811. };
  12812. /**
  12813. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12814. * Returned type : float array or Float32Array
  12815. */
  12816. AbstractMesh.prototype.getVerticesData = function (kind) {
  12817. return null;
  12818. };
  12819. /**
  12820. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12821. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12822. * The `data` are either a numeric array either a Float32Array.
  12823. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12824. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  12825. * Note that a new underlying VertexBuffer object is created each call.
  12826. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12827. *
  12828. * Possible `kind` values :
  12829. * - BABYLON.VertexBuffer.PositionKind
  12830. * - BABYLON.VertexBuffer.UVKind
  12831. * - BABYLON.VertexBuffer.UV2Kind
  12832. * - BABYLON.VertexBuffer.UV3Kind
  12833. * - BABYLON.VertexBuffer.UV4Kind
  12834. * - BABYLON.VertexBuffer.UV5Kind
  12835. * - BABYLON.VertexBuffer.UV6Kind
  12836. * - BABYLON.VertexBuffer.ColorKind
  12837. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12838. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12839. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12840. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12841. *
  12842. * Returns the Mesh.
  12843. */
  12844. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12845. return null;
  12846. };
  12847. /**
  12848. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12849. * If the mesh has no geometry, it is simply returned as it is.
  12850. * The `data` are either a numeric array either a Float32Array.
  12851. * No new underlying VertexBuffer object is created.
  12852. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12853. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12854. *
  12855. * Possible `kind` values :
  12856. * - BABYLON.VertexBuffer.PositionKind
  12857. * - BABYLON.VertexBuffer.UVKind
  12858. * - BABYLON.VertexBuffer.UV2Kind
  12859. * - BABYLON.VertexBuffer.UV3Kind
  12860. * - BABYLON.VertexBuffer.UV4Kind
  12861. * - BABYLON.VertexBuffer.UV5Kind
  12862. * - BABYLON.VertexBuffer.UV6Kind
  12863. * - BABYLON.VertexBuffer.ColorKind
  12864. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12865. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12866. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12867. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12868. *
  12869. * Returns the Mesh.
  12870. */
  12871. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12872. return null;
  12873. };
  12874. /**
  12875. * Sets the mesh indices.
  12876. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12877. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12878. * This method creates a new index buffer each call.
  12879. * Returns the Mesh.
  12880. */
  12881. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12882. return null;
  12883. };
  12884. /** Returns false by default, used by the class Mesh.
  12885. * Returns a boolean
  12886. */
  12887. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12888. return false;
  12889. };
  12890. /**
  12891. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12892. * Returns a BoundingInfo
  12893. */
  12894. AbstractMesh.prototype.getBoundingInfo = function () {
  12895. if (this._masterMesh) {
  12896. return this._masterMesh.getBoundingInfo();
  12897. }
  12898. if (!this._boundingInfo) {
  12899. this._updateBoundingInfo();
  12900. }
  12901. return this._boundingInfo;
  12902. };
  12903. /**
  12904. * Sets a mesh new object BoundingInfo.
  12905. * Returns the AbstractMesh.
  12906. */
  12907. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12908. this._boundingInfo = boundingInfo;
  12909. return this;
  12910. };
  12911. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12912. get: function () {
  12913. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12914. },
  12915. enumerable: true,
  12916. configurable: true
  12917. });
  12918. AbstractMesh.prototype._preActivate = function () {
  12919. };
  12920. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12921. };
  12922. AbstractMesh.prototype._activate = function (renderId) {
  12923. this._renderId = renderId;
  12924. };
  12925. /**
  12926. * Returns the last update of the World matrix
  12927. * Returns a Matrix.
  12928. */
  12929. AbstractMesh.prototype.getWorldMatrix = function () {
  12930. if (this._masterMesh) {
  12931. return this._masterMesh.getWorldMatrix();
  12932. }
  12933. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12934. this.computeWorldMatrix();
  12935. }
  12936. return this._worldMatrix;
  12937. };
  12938. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12939. /**
  12940. * Returns directly the last state of the mesh World matrix.
  12941. * A Matrix is returned.
  12942. */
  12943. get: function () {
  12944. return this._worldMatrix;
  12945. },
  12946. enumerable: true,
  12947. configurable: true
  12948. });
  12949. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12950. /**
  12951. * Returns the current mesh absolute position.
  12952. * Retuns a Vector3.
  12953. */
  12954. get: function () {
  12955. return this._absolutePosition;
  12956. },
  12957. enumerable: true,
  12958. configurable: true
  12959. });
  12960. /**
  12961. * Prevents the World matrix to be computed any longer.
  12962. * Returns the AbstractMesh.
  12963. */
  12964. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12965. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12966. this.computeWorldMatrix(true);
  12967. this._isWorldMatrixFrozen = true;
  12968. return this;
  12969. };
  12970. /**
  12971. * Allows back the World matrix computation.
  12972. * Returns the AbstractMesh.
  12973. */
  12974. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12975. this._isWorldMatrixFrozen = false;
  12976. this.computeWorldMatrix(true);
  12977. return this;
  12978. };
  12979. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12980. /**
  12981. * True if the World matrix has been frozen.
  12982. * Returns a boolean.
  12983. */
  12984. get: function () {
  12985. return this._isWorldMatrixFrozen;
  12986. },
  12987. enumerable: true,
  12988. configurable: true
  12989. });
  12990. /**
  12991. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12992. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12993. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12994. * The passed axis is also normalized.
  12995. * Returns the AbstractMesh.
  12996. */
  12997. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12998. axis.normalize();
  12999. if (!this.rotationQuaternion) {
  13000. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13001. this.rotation = BABYLON.Vector3.Zero();
  13002. }
  13003. var rotationQuaternion;
  13004. if (!space || space === BABYLON.Space.LOCAL) {
  13005. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13006. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13007. }
  13008. else {
  13009. if (this.parent) {
  13010. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13011. invertParentWorldMatrix.invert();
  13012. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13013. }
  13014. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13015. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13016. }
  13017. return this;
  13018. };
  13019. /**
  13020. * Translates the mesh along the axis vector for the passed distance in the given space.
  13021. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13022. * Returns the AbstractMesh.
  13023. */
  13024. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13025. var displacementVector = axis.scale(distance);
  13026. if (!space || space === BABYLON.Space.LOCAL) {
  13027. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13028. this.setPositionWithLocalVector(tempV3);
  13029. }
  13030. else {
  13031. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13032. }
  13033. return this;
  13034. };
  13035. /**
  13036. * Adds a rotation step to the mesh current rotation.
  13037. * x, y, z are Euler angles expressed in radians.
  13038. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13039. * This means this rotation is made in the mesh local space only.
  13040. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13041. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13042. * ```javascript
  13043. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13044. * ```
  13045. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13046. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  13047. * Returns the AbstractMesh.
  13048. */
  13049. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13050. var rotationQuaternion;
  13051. if (this.rotationQuaternion) {
  13052. rotationQuaternion = this.rotationQuaternion;
  13053. }
  13054. else {
  13055. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13056. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13057. }
  13058. var accumulation = BABYLON.Tmp.Quaternion[0];
  13059. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13060. rotationQuaternion.multiplyInPlace(accumulation);
  13061. if (!this.rotationQuaternion) {
  13062. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13063. }
  13064. return this;
  13065. };
  13066. /**
  13067. * Retuns the mesh absolute position in the World.
  13068. * Returns a Vector3.
  13069. */
  13070. AbstractMesh.prototype.getAbsolutePosition = function () {
  13071. this.computeWorldMatrix();
  13072. return this._absolutePosition;
  13073. };
  13074. /**
  13075. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13076. * Returns the AbstractMesh.
  13077. */
  13078. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13079. if (!absolutePosition) {
  13080. return;
  13081. }
  13082. var absolutePositionX;
  13083. var absolutePositionY;
  13084. var absolutePositionZ;
  13085. if (absolutePosition.x === undefined) {
  13086. if (arguments.length < 3) {
  13087. return;
  13088. }
  13089. absolutePositionX = arguments[0];
  13090. absolutePositionY = arguments[1];
  13091. absolutePositionZ = arguments[2];
  13092. }
  13093. else {
  13094. absolutePositionX = absolutePosition.x;
  13095. absolutePositionY = absolutePosition.y;
  13096. absolutePositionZ = absolutePosition.z;
  13097. }
  13098. if (this.parent) {
  13099. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13100. invertParentWorldMatrix.invert();
  13101. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13102. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13103. }
  13104. else {
  13105. this.position.x = absolutePositionX;
  13106. this.position.y = absolutePositionY;
  13107. this.position.z = absolutePositionZ;
  13108. }
  13109. return this;
  13110. };
  13111. // ================================== Point of View Movement =================================
  13112. /**
  13113. * Perform relative position change from the point of view of behind the front of the mesh.
  13114. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13115. * Supports definition of mesh facing forward or backward.
  13116. * @param {number} amountRight
  13117. * @param {number} amountUp
  13118. * @param {number} amountForward
  13119. *
  13120. * Returns the AbstractMesh.
  13121. */
  13122. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13123. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13124. return this;
  13125. };
  13126. /**
  13127. * Calculate relative position change from the point of view of behind the front of the mesh.
  13128. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13129. * Supports definition of mesh facing forward or backward.
  13130. * @param {number} amountRight
  13131. * @param {number} amountUp
  13132. * @param {number} amountForward
  13133. *
  13134. * Returns a new Vector3.
  13135. */
  13136. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13137. var rotMatrix = new BABYLON.Matrix();
  13138. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13139. rotQuaternion.toRotationMatrix(rotMatrix);
  13140. var translationDelta = BABYLON.Vector3.Zero();
  13141. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13142. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13143. return translationDelta;
  13144. };
  13145. // ================================== Point of View Rotation =================================
  13146. /**
  13147. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13148. * Supports definition of mesh facing forward or backward.
  13149. * @param {number} flipBack
  13150. * @param {number} twirlClockwise
  13151. * @param {number} tiltRight
  13152. *
  13153. * Returns the AbstractMesh.
  13154. */
  13155. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13156. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13157. return this;
  13158. };
  13159. /**
  13160. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13161. * Supports definition of mesh facing forward or backward.
  13162. * @param {number} flipBack
  13163. * @param {number} twirlClockwise
  13164. * @param {number} tiltRight
  13165. *
  13166. * Returns a new Vector3.
  13167. */
  13168. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13169. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13170. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13171. };
  13172. /**
  13173. * Sets a new pivot matrix to the mesh.
  13174. * Returns the AbstractMesh.
  13175. */
  13176. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13177. this._pivotMatrix = matrix;
  13178. this._cache.pivotMatrixUpdated = true;
  13179. return this;
  13180. };
  13181. /**
  13182. * Returns the mesh pivot matrix.
  13183. * Default : Identity.
  13184. * A Matrix is returned.
  13185. */
  13186. AbstractMesh.prototype.getPivotMatrix = function () {
  13187. return this._pivotMatrix;
  13188. };
  13189. AbstractMesh.prototype._isSynchronized = function () {
  13190. if (this._isDirty) {
  13191. return false;
  13192. }
  13193. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13194. return false;
  13195. if (this._cache.pivotMatrixUpdated) {
  13196. return false;
  13197. }
  13198. if (this.infiniteDistance) {
  13199. return false;
  13200. }
  13201. if (!this._cache.position.equals(this.position))
  13202. return false;
  13203. if (this.rotationQuaternion) {
  13204. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13205. return false;
  13206. }
  13207. if (!this._cache.rotation.equals(this.rotation))
  13208. return false;
  13209. if (!this._cache.scaling.equals(this.scaling))
  13210. return false;
  13211. return true;
  13212. };
  13213. AbstractMesh.prototype._initCache = function () {
  13214. _super.prototype._initCache.call(this);
  13215. this._cache.localMatrixUpdated = false;
  13216. this._cache.position = BABYLON.Vector3.Zero();
  13217. this._cache.scaling = BABYLON.Vector3.Zero();
  13218. this._cache.rotation = BABYLON.Vector3.Zero();
  13219. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13220. this._cache.billboardMode = -1;
  13221. };
  13222. AbstractMesh.prototype.markAsDirty = function (property) {
  13223. if (property === "rotation") {
  13224. this.rotationQuaternion = null;
  13225. }
  13226. this._currentRenderId = Number.MAX_VALUE;
  13227. this._isDirty = true;
  13228. return this;
  13229. };
  13230. /**
  13231. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13232. * Returns the AbstractMesh.
  13233. */
  13234. AbstractMesh.prototype._updateBoundingInfo = function () {
  13235. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13236. this._boundingInfo.update(this.worldMatrixFromCache);
  13237. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13238. return this;
  13239. };
  13240. /**
  13241. * Update a mesh's children BoundingInfo objects only.
  13242. * Returns the AbstractMesh.
  13243. */
  13244. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13245. if (!this.subMeshes) {
  13246. return;
  13247. }
  13248. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13249. var subMesh = this.subMeshes[subIndex];
  13250. if (!subMesh.IsGlobal) {
  13251. subMesh.updateBoundingInfo(matrix);
  13252. }
  13253. }
  13254. return this;
  13255. };
  13256. /**
  13257. * Computes the mesh World matrix and returns it.
  13258. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13259. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13260. * If the parameter `force`is set to `true`, the actual computation is done.
  13261. * Returns the mesh World Matrix.
  13262. */
  13263. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13264. if (this._isWorldMatrixFrozen) {
  13265. return this._worldMatrix;
  13266. }
  13267. if (!force && this.isSynchronized(true)) {
  13268. this._currentRenderId = this.getScene().getRenderId();
  13269. return this._worldMatrix;
  13270. }
  13271. this._cache.position.copyFrom(this.position);
  13272. this._cache.scaling.copyFrom(this.scaling);
  13273. this._cache.pivotMatrixUpdated = false;
  13274. this._cache.billboardMode = this.billboardMode;
  13275. this._currentRenderId = this.getScene().getRenderId();
  13276. this._isDirty = false;
  13277. // Scaling
  13278. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13279. // Rotation
  13280. //rotate, if quaternion is set and rotation was used
  13281. if (this.rotationQuaternion) {
  13282. var len = this.rotation.length();
  13283. if (len) {
  13284. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13285. this.rotation.copyFromFloats(0, 0, 0);
  13286. }
  13287. }
  13288. if (this.rotationQuaternion) {
  13289. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13290. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13291. }
  13292. else {
  13293. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13294. this._cache.rotation.copyFrom(this.rotation);
  13295. }
  13296. // Translation
  13297. if (this.infiniteDistance && !this.parent) {
  13298. var camera = this.getScene().activeCamera;
  13299. if (camera) {
  13300. var cameraWorldMatrix = camera.getWorldMatrix();
  13301. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13302. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13303. }
  13304. }
  13305. else {
  13306. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13307. }
  13308. // Composing transformations
  13309. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13310. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13311. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13312. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13313. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13314. // Need to decompose each rotation here
  13315. var currentPosition = BABYLON.Tmp.Vector3[3];
  13316. if (this.parent && this.parent.getWorldMatrix) {
  13317. if (this._meshToBoneReferal) {
  13318. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13319. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13320. }
  13321. else {
  13322. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13323. }
  13324. }
  13325. else {
  13326. currentPosition.copyFrom(this.position);
  13327. }
  13328. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13329. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13330. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13331. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13332. }
  13333. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13334. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13335. }
  13336. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13337. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13338. }
  13339. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13340. }
  13341. else {
  13342. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13343. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13344. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13345. }
  13346. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13347. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13348. }
  13349. // Local world
  13350. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13351. // Parent
  13352. if (this.parent && this.parent.getWorldMatrix) {
  13353. this._markSyncedWithParent();
  13354. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13355. if (this._meshToBoneReferal) {
  13356. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13357. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13358. }
  13359. else {
  13360. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13361. }
  13362. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13363. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13364. this._worldMatrix.copyFrom(this._localWorld);
  13365. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13366. }
  13367. else {
  13368. if (this._meshToBoneReferal) {
  13369. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13370. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13371. }
  13372. else {
  13373. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13374. }
  13375. }
  13376. }
  13377. else {
  13378. this._worldMatrix.copyFrom(this._localWorld);
  13379. }
  13380. // Bounding info
  13381. this._updateBoundingInfo();
  13382. // Absolute position
  13383. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13384. // Callbacks
  13385. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13386. if (!this._poseMatrix) {
  13387. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13388. }
  13389. return this._worldMatrix;
  13390. };
  13391. /**
  13392. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13393. * @param func: callback function to add
  13394. *
  13395. * Returns the AbstractMesh.
  13396. */
  13397. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13398. this.onAfterWorldMatrixUpdateObservable.add(func);
  13399. return this;
  13400. };
  13401. /**
  13402. * Removes a registered callback function.
  13403. * Returns the AbstractMesh.
  13404. */
  13405. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13406. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13407. return this;
  13408. };
  13409. /**
  13410. * Sets the mesh position in its local space.
  13411. * Returns the AbstractMesh.
  13412. */
  13413. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13414. this.computeWorldMatrix();
  13415. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13416. return this;
  13417. };
  13418. /**
  13419. * Returns the mesh position in the local space from the current World matrix values.
  13420. * Returns a new Vector3.
  13421. */
  13422. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13423. this.computeWorldMatrix();
  13424. var invLocalWorldMatrix = this._localWorld.clone();
  13425. invLocalWorldMatrix.invert();
  13426. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13427. };
  13428. /**
  13429. * Translates the mesh along the passed Vector3 in its local space.
  13430. * Returns the AbstractMesh.
  13431. */
  13432. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13433. this.computeWorldMatrix(true);
  13434. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13435. return this;
  13436. };
  13437. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13438. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13439. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13440. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13441. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13442. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13443. /// <returns>Mesh oriented towards targetMesh</returns>
  13444. if (yawCor === void 0) { yawCor = 0; }
  13445. if (pitchCor === void 0) { pitchCor = 0; }
  13446. if (rollCor === void 0) { rollCor = 0; }
  13447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13448. var dv = AbstractMesh._lookAtVectorCache;
  13449. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13450. targetPoint.subtractToRef(pos, dv);
  13451. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13452. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13453. var pitch = Math.atan2(dv.y, len);
  13454. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13455. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13456. return this;
  13457. };
  13458. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13459. this._meshToBoneReferal = affectedMesh;
  13460. this.parent = bone;
  13461. if (bone.getWorldMatrix().determinant() < 0) {
  13462. this.scalingDeterminant *= -1;
  13463. }
  13464. return this;
  13465. };
  13466. AbstractMesh.prototype.detachFromBone = function () {
  13467. if (this.parent.getWorldMatrix().determinant() < 0) {
  13468. this.scalingDeterminant *= -1;
  13469. }
  13470. this._meshToBoneReferal = null;
  13471. this.parent = null;
  13472. return this;
  13473. };
  13474. /**
  13475. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13476. * A mesh is in the frustum if its bounding box intersects the frustum.
  13477. * Boolean returned.
  13478. */
  13479. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13480. return this._boundingInfo.isInFrustum(frustumPlanes);
  13481. };
  13482. /**
  13483. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13484. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13485. * Boolean returned.
  13486. */
  13487. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13488. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13489. ;
  13490. };
  13491. /**
  13492. * True if the mesh intersects another mesh or a SolidParticle object.
  13493. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  13494. * Returns a boolean.
  13495. */
  13496. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13497. if (!this._boundingInfo || !mesh._boundingInfo) {
  13498. return false;
  13499. }
  13500. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13501. };
  13502. /**
  13503. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13504. * Returns a boolean.
  13505. */
  13506. AbstractMesh.prototype.intersectsPoint = function (point) {
  13507. if (!this._boundingInfo) {
  13508. return false;
  13509. }
  13510. return this._boundingInfo.intersectsPoint(point);
  13511. };
  13512. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13513. return this.physicsImpostor;
  13514. };
  13515. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13516. if (!camera) {
  13517. camera = this.getScene().activeCamera;
  13518. }
  13519. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13520. };
  13521. /**
  13522. * Returns the distance from the mesh to the active camera.
  13523. * Returns a float.
  13524. */
  13525. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13526. if (!camera) {
  13527. camera = this.getScene().activeCamera;
  13528. }
  13529. return this.absolutePosition.subtract(camera.position).length();
  13530. };
  13531. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13532. if (!this.physicsImpostor) {
  13533. return;
  13534. }
  13535. this.physicsImpostor.applyImpulse(force, contactPoint);
  13536. return this;
  13537. };
  13538. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13539. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13540. return;
  13541. }
  13542. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13543. mainPivot: pivot1,
  13544. connectedPivot: pivot2,
  13545. nativeParams: options
  13546. });
  13547. return this;
  13548. };
  13549. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13550. // Collisions
  13551. /**
  13552. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13553. * Default `false`.
  13554. */
  13555. get: function () {
  13556. return this._checkCollisions;
  13557. },
  13558. set: function (collisionEnabled) {
  13559. this._checkCollisions = collisionEnabled;
  13560. if (this.getScene().workerCollisions) {
  13561. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13562. }
  13563. },
  13564. enumerable: true,
  13565. configurable: true
  13566. });
  13567. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13568. var globalPosition = this.getAbsolutePosition();
  13569. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13570. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13571. this._collider.radius = this.ellipsoid;
  13572. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13573. return this;
  13574. };
  13575. // Submeshes octree
  13576. /**
  13577. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13578. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13579. * Returns an Octree of submeshes.
  13580. */
  13581. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13582. if (maxCapacity === void 0) { maxCapacity = 64; }
  13583. if (maxDepth === void 0) { maxDepth = 2; }
  13584. if (!this._submeshesOctree) {
  13585. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13586. }
  13587. this.computeWorldMatrix(true);
  13588. // Update octree
  13589. var bbox = this.getBoundingInfo().boundingBox;
  13590. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13591. return this._submeshesOctree;
  13592. };
  13593. // Collisions
  13594. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13595. this._generatePointsArray();
  13596. // Transformation
  13597. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13598. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13599. subMesh._lastColliderWorldVertices = [];
  13600. subMesh._trianglePlanes = [];
  13601. var start = subMesh.verticesStart;
  13602. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13603. for (var i = start; i < end; i++) {
  13604. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13605. }
  13606. }
  13607. // Collide
  13608. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13609. if (collider.collisionFound) {
  13610. collider.collidedMesh = this;
  13611. }
  13612. return this;
  13613. };
  13614. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13615. var subMeshes;
  13616. var len;
  13617. // Octrees
  13618. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13619. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13620. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13621. len = intersections.length;
  13622. subMeshes = intersections.data;
  13623. }
  13624. else {
  13625. subMeshes = this.subMeshes;
  13626. len = subMeshes.length;
  13627. }
  13628. for (var index = 0; index < len; index++) {
  13629. var subMesh = subMeshes[index];
  13630. // Bounding test
  13631. if (len > 1 && !subMesh._checkCollision(collider))
  13632. continue;
  13633. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13634. }
  13635. return this;
  13636. };
  13637. AbstractMesh.prototype._checkCollision = function (collider) {
  13638. // Bounding box test
  13639. if (!this._boundingInfo._checkCollision(collider))
  13640. return this;
  13641. // Transformation matrix
  13642. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13643. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13644. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13645. return this;
  13646. };
  13647. // Picking
  13648. AbstractMesh.prototype._generatePointsArray = function () {
  13649. return false;
  13650. };
  13651. /**
  13652. * Checks if the passed Ray intersects with the mesh.
  13653. * Returns an object PickingInfo.
  13654. */
  13655. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13656. var pickingInfo = new BABYLON.PickingInfo();
  13657. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13658. return pickingInfo;
  13659. }
  13660. if (!this._generatePointsArray()) {
  13661. return pickingInfo;
  13662. }
  13663. var intersectInfo = null;
  13664. // Octrees
  13665. var subMeshes;
  13666. var len;
  13667. if (this._submeshesOctree && this.useOctreeForPicking) {
  13668. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13669. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13670. len = intersections.length;
  13671. subMeshes = intersections.data;
  13672. }
  13673. else {
  13674. subMeshes = this.subMeshes;
  13675. len = subMeshes.length;
  13676. }
  13677. for (var index = 0; index < len; index++) {
  13678. var subMesh = subMeshes[index];
  13679. // Bounding test
  13680. if (len > 1 && !subMesh.canIntersects(ray))
  13681. continue;
  13682. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13683. if (currentIntersectInfo) {
  13684. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13685. intersectInfo = currentIntersectInfo;
  13686. intersectInfo.subMeshId = index;
  13687. if (fastCheck) {
  13688. break;
  13689. }
  13690. }
  13691. }
  13692. }
  13693. if (intersectInfo) {
  13694. // Get picked point
  13695. var world = this.getWorldMatrix();
  13696. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13697. var direction = ray.direction.clone();
  13698. direction = direction.scale(intersectInfo.distance);
  13699. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13700. var pickedPoint = worldOrigin.add(worldDirection);
  13701. // Return result
  13702. pickingInfo.hit = true;
  13703. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13704. pickingInfo.pickedPoint = pickedPoint;
  13705. pickingInfo.pickedMesh = this;
  13706. pickingInfo.bu = intersectInfo.bu;
  13707. pickingInfo.bv = intersectInfo.bv;
  13708. pickingInfo.faceId = intersectInfo.faceId;
  13709. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13710. return pickingInfo;
  13711. }
  13712. return pickingInfo;
  13713. };
  13714. /**
  13715. * Clones the mesh, used by the class Mesh.
  13716. * Just returns `null` for an AbstractMesh.
  13717. */
  13718. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13719. return null;
  13720. };
  13721. /**
  13722. * Disposes all the mesh submeshes.
  13723. * Returns the AbstractMesh.
  13724. */
  13725. AbstractMesh.prototype.releaseSubMeshes = function () {
  13726. if (this.subMeshes) {
  13727. while (this.subMeshes.length) {
  13728. this.subMeshes[0].dispose();
  13729. }
  13730. }
  13731. else {
  13732. this.subMeshes = new Array();
  13733. }
  13734. return this;
  13735. };
  13736. /**
  13737. * Disposes the AbstractMesh.
  13738. * Some internal references are kept for further use.
  13739. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13740. * Returns nothing.
  13741. */
  13742. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13743. var _this = this;
  13744. var index;
  13745. // Action manager
  13746. if (this.actionManager) {
  13747. this.actionManager.dispose();
  13748. this.actionManager = null;
  13749. }
  13750. // Skeleton
  13751. this.skeleton = null;
  13752. // Animations
  13753. this.getScene().stopAnimation(this);
  13754. // Physics
  13755. if (this.physicsImpostor) {
  13756. this.physicsImpostor.dispose();
  13757. }
  13758. // Intersections in progress
  13759. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13760. var other = this._intersectionsInProgress[index];
  13761. var pos = other._intersectionsInProgress.indexOf(this);
  13762. other._intersectionsInProgress.splice(pos, 1);
  13763. }
  13764. this._intersectionsInProgress = [];
  13765. // Lights
  13766. var lights = this.getScene().lights;
  13767. lights.forEach(function (light) {
  13768. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13769. if (meshIndex !== -1) {
  13770. light.includedOnlyMeshes.splice(meshIndex, 1);
  13771. }
  13772. meshIndex = light.excludedMeshes.indexOf(_this);
  13773. if (meshIndex !== -1) {
  13774. light.excludedMeshes.splice(meshIndex, 1);
  13775. }
  13776. // Shadow generators
  13777. var generator = light.getShadowGenerator();
  13778. if (generator) {
  13779. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13780. if (meshIndex !== -1) {
  13781. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13782. }
  13783. }
  13784. });
  13785. // Edges
  13786. if (this._edgesRenderer) {
  13787. this._edgesRenderer.dispose();
  13788. this._edgesRenderer = null;
  13789. }
  13790. // SubMeshes
  13791. if (this.getClassName() !== "InstancedMesh") {
  13792. this.releaseSubMeshes();
  13793. }
  13794. // Octree
  13795. var sceneOctree = this.getScene().selectionOctree;
  13796. if (sceneOctree) {
  13797. var index = sceneOctree.dynamicContent.indexOf(this);
  13798. if (index !== -1) {
  13799. sceneOctree.dynamicContent.splice(index, 1);
  13800. }
  13801. }
  13802. // Engine
  13803. this.getScene().getEngine().wipeCaches();
  13804. // Remove from scene
  13805. this.getScene().removeMesh(this);
  13806. if (!doNotRecurse) {
  13807. // Particles
  13808. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13809. if (this.getScene().particleSystems[index].emitter === this) {
  13810. this.getScene().particleSystems[index].dispose();
  13811. index--;
  13812. }
  13813. }
  13814. // Children
  13815. var objects = this.getDescendants(true);
  13816. for (index = 0; index < objects.length; index++) {
  13817. objects[index].dispose();
  13818. }
  13819. }
  13820. else {
  13821. var childMeshes = this.getChildMeshes(true);
  13822. for (index = 0; index < childMeshes.length; index++) {
  13823. var child = childMeshes[index];
  13824. child.parent = null;
  13825. child.computeWorldMatrix(true);
  13826. }
  13827. }
  13828. // facet data
  13829. if (this._facetDataEnabled) {
  13830. this.disableFacetData();
  13831. }
  13832. this.onAfterWorldMatrixUpdateObservable.clear();
  13833. this.onCollideObservable.clear();
  13834. this.onCollisionPositionChangeObservable.clear();
  13835. this._isDisposed = true;
  13836. _super.prototype.dispose.call(this);
  13837. };
  13838. /**
  13839. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13840. * This Vector3 is expressed in the World space.
  13841. */
  13842. AbstractMesh.prototype.getDirection = function (localAxis) {
  13843. var result = BABYLON.Vector3.Zero();
  13844. this.getDirectionToRef(localAxis, result);
  13845. return result;
  13846. };
  13847. /**
  13848. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13849. * localAxis is expressed in the mesh local space.
  13850. * result is computed in the Wordl space from the mesh World matrix.
  13851. * Returns the AbstractMesh.
  13852. */
  13853. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13854. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13855. return this;
  13856. };
  13857. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13859. if (this.getScene().getRenderId() == 0) {
  13860. this.computeWorldMatrix(true);
  13861. }
  13862. var wm = this.getWorldMatrix();
  13863. if (space == BABYLON.Space.WORLD) {
  13864. var tmat = BABYLON.Tmp.Matrix[0];
  13865. wm.invertToRef(tmat);
  13866. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13867. }
  13868. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13869. this._pivotMatrix.m[12] = -point.x;
  13870. this._pivotMatrix.m[13] = -point.y;
  13871. this._pivotMatrix.m[14] = -point.z;
  13872. this._cache.pivotMatrixUpdated = true;
  13873. return this;
  13874. };
  13875. /**
  13876. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13877. */
  13878. AbstractMesh.prototype.getPivotPoint = function () {
  13879. var point = BABYLON.Vector3.Zero();
  13880. this.getPivotPointToRef(point);
  13881. return point;
  13882. };
  13883. /**
  13884. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13885. * Returns the AbstractMesh.
  13886. */
  13887. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13888. result.x = -this._pivotMatrix.m[12];
  13889. result.y = -this._pivotMatrix.m[13];
  13890. result.z = -this._pivotMatrix.m[14];
  13891. return this;
  13892. };
  13893. /**
  13894. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13895. */
  13896. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13897. var point = BABYLON.Vector3.Zero();
  13898. this.getAbsolutePivotPointToRef(point);
  13899. return point;
  13900. };
  13901. /**
  13902. * Defines the passed mesh as the parent of the current mesh.
  13903. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13904. * Returns the AbstractMesh.
  13905. */
  13906. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13907. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13908. var child = this;
  13909. var parent = mesh;
  13910. if (mesh == null) {
  13911. if (child.parent && keepWorldPositionRotation) {
  13912. var rotation = BABYLON.Tmp.Quaternion[0];
  13913. var position = BABYLON.Tmp.Vector3[0];
  13914. var scale = BABYLON.Tmp.Vector3[1];
  13915. child.getWorldMatrix().decompose(scale, rotation, position);
  13916. if (child.rotationQuaternion) {
  13917. child.rotationQuaternion.copyFrom(rotation);
  13918. }
  13919. else {
  13920. rotation.toEulerAnglesToRef(child.rotation);
  13921. }
  13922. child.position.x = position.x;
  13923. child.position.y = position.y;
  13924. child.position.z = position.z;
  13925. }
  13926. }
  13927. else {
  13928. if (keepWorldPositionRotation) {
  13929. var rotation = BABYLON.Tmp.Quaternion[0];
  13930. var position = BABYLON.Tmp.Vector3[0];
  13931. var scale = BABYLON.Tmp.Vector3[1];
  13932. var m1 = BABYLON.Tmp.Matrix[0];
  13933. var m2 = BABYLON.Tmp.Matrix[1];
  13934. parent.getWorldMatrix().decompose(scale, rotation, position);
  13935. rotation.toRotationMatrix(m1);
  13936. m2.setTranslation(position);
  13937. m2.multiplyToRef(m1, m1);
  13938. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13939. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13940. m.decompose(scale, rotation, position);
  13941. if (child.rotationQuaternion) {
  13942. child.rotationQuaternion.copyFrom(rotation);
  13943. }
  13944. else {
  13945. rotation.toEulerAnglesToRef(child.rotation);
  13946. }
  13947. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13948. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13949. m.decompose(scale, rotation, position);
  13950. child.position.x = position.x;
  13951. child.position.y = position.y;
  13952. child.position.z = position.z;
  13953. }
  13954. }
  13955. child.parent = parent;
  13956. return this;
  13957. };
  13958. /**
  13959. * Adds the passed mesh as a child to the current mesh.
  13960. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13961. * Returns the AbstractMesh.
  13962. */
  13963. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13964. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13965. mesh.setParent(this, keepWorldPositionRotation);
  13966. return this;
  13967. };
  13968. /**
  13969. * Removes the passed mesh from the current mesh children list.
  13970. * Returns the AbstractMesh.
  13971. */
  13972. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13973. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13974. mesh.setParent(null, keepWorldPositionRotation);
  13975. return this;
  13976. };
  13977. /**
  13978. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13979. * Returns the AbstractMesh.
  13980. */
  13981. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13982. result.x = this._pivotMatrix.m[12];
  13983. result.y = this._pivotMatrix.m[13];
  13984. result.z = this._pivotMatrix.m[14];
  13985. this.getPivotPointToRef(result);
  13986. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13987. return this;
  13988. };
  13989. // Facet data
  13990. /**
  13991. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13992. * Returns the AbstractMesh.
  13993. */
  13994. AbstractMesh.prototype._initFacetData = function () {
  13995. if (!this._facetNormals) {
  13996. this._facetNormals = new Array();
  13997. }
  13998. if (!this._facetPositions) {
  13999. this._facetPositions = new Array();
  14000. }
  14001. if (!this._facetPartitioning) {
  14002. this._facetPartitioning = new Array();
  14003. }
  14004. this._facetNb = this.getIndices().length / 3;
  14005. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14006. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14007. for (var f = 0; f < this._facetNb; f++) {
  14008. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14009. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14010. }
  14011. this._facetDataEnabled = true;
  14012. return this;
  14013. };
  14014. /**
  14015. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14016. * This method can be called within the render loop.
  14017. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  14018. * Returns the AbstractMesh.
  14019. */
  14020. AbstractMesh.prototype.updateFacetData = function () {
  14021. if (!this._facetDataEnabled) {
  14022. this._initFacetData();
  14023. }
  14024. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14025. var indices = this.getIndices();
  14026. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14027. var bInfo = this.getBoundingInfo();
  14028. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14029. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14030. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14031. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14032. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14033. this._subDiv.max = this._partitioningSubdivisions;
  14034. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14035. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14036. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14037. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14038. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14039. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14040. // set the parameters for ComputeNormals()
  14041. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14042. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14043. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14044. this._facetParameters.bInfo = bInfo;
  14045. this._facetParameters.bbSize = this._bbSize;
  14046. this._facetParameters.subDiv = this._subDiv;
  14047. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14048. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14049. return this;
  14050. };
  14051. /**
  14052. * Returns the facetLocalNormals array.
  14053. * The normals are expressed in the mesh local space.
  14054. */
  14055. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14056. if (!this._facetNormals) {
  14057. this.updateFacetData();
  14058. }
  14059. return this._facetNormals;
  14060. };
  14061. /**
  14062. * Returns the facetLocalPositions array.
  14063. * The facet positions are expressed in the mesh local space.
  14064. */
  14065. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14066. if (!this._facetPositions) {
  14067. this.updateFacetData();
  14068. }
  14069. return this._facetPositions;
  14070. };
  14071. /**
  14072. * Returns the facetLocalPartioning array.
  14073. */
  14074. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14075. if (!this._facetPartitioning) {
  14076. this.updateFacetData();
  14077. }
  14078. return this._facetPartitioning;
  14079. };
  14080. /**
  14081. * Returns the i-th facet position in the world system.
  14082. * This method allocates a new Vector3 per call.
  14083. */
  14084. AbstractMesh.prototype.getFacetPosition = function (i) {
  14085. var pos = BABYLON.Vector3.Zero();
  14086. this.getFacetPositionToRef(i, pos);
  14087. return pos;
  14088. };
  14089. /**
  14090. * Sets the reference Vector3 with the i-th facet position in the world system.
  14091. * Returns the AbstractMesh.
  14092. */
  14093. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14094. var localPos = (this.getFacetLocalPositions())[i];
  14095. var world = this.getWorldMatrix();
  14096. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14097. return this;
  14098. };
  14099. /**
  14100. * Returns the i-th facet normal in the world system.
  14101. * This method allocates a new Vector3 per call.
  14102. */
  14103. AbstractMesh.prototype.getFacetNormal = function (i) {
  14104. var norm = BABYLON.Vector3.Zero();
  14105. this.getFacetNormalToRef(i, norm);
  14106. return norm;
  14107. };
  14108. /**
  14109. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14110. * Returns the AbstractMesh.
  14111. */
  14112. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14113. var localNorm = (this.getFacetLocalNormals())[i];
  14114. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14115. return this;
  14116. };
  14117. /**
  14118. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  14119. */
  14120. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14121. var bInfo = this.getBoundingInfo();
  14122. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14123. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14124. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14125. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14126. return null;
  14127. }
  14128. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14129. };
  14130. /**
  14131. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14132. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14133. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  14134. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14135. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  14136. */
  14137. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14138. if (checkFace === void 0) { checkFace = false; }
  14139. if (facing === void 0) { facing = true; }
  14140. var world = this.getWorldMatrix();
  14141. var invMat = BABYLON.Tmp.Matrix[5];
  14142. world.invertToRef(invMat);
  14143. var invVect = BABYLON.Tmp.Vector3[8];
  14144. var closest = null;
  14145. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14146. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14147. if (projected) {
  14148. // tranform the local computed projected vector to world coordinates
  14149. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14150. }
  14151. return closest;
  14152. };
  14153. /**
  14154. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14155. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14156. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  14157. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14158. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  14159. */
  14160. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14161. if (checkFace === void 0) { checkFace = false; }
  14162. if (facing === void 0) { facing = true; }
  14163. var closest = null;
  14164. var tmpx = 0.0;
  14165. var tmpy = 0.0;
  14166. var tmpz = 0.0;
  14167. var d = 0.0; // tmp dot facet normal * facet position
  14168. var t0 = 0.0;
  14169. var projx = 0.0;
  14170. var projy = 0.0;
  14171. var projz = 0.0;
  14172. // Get all the facets in the same partitioning block than (x, y, z)
  14173. var facetPositions = this.getFacetLocalPositions();
  14174. var facetNormals = this.getFacetLocalNormals();
  14175. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14176. if (!facetsInBlock) {
  14177. return null;
  14178. }
  14179. // Get the closest facet to (x, y, z)
  14180. var shortest = Number.MAX_VALUE; // init distance vars
  14181. var tmpDistance = shortest;
  14182. var fib; // current facet in the block
  14183. var norm; // current facet normal
  14184. var p0; // current facet barycenter position
  14185. // loop on all the facets in the current partitioning block
  14186. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14187. fib = facetsInBlock[idx];
  14188. norm = facetNormals[fib];
  14189. p0 = facetPositions[fib];
  14190. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14191. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14192. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14193. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14194. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14195. projx = x + norm.x * t0;
  14196. projy = y + norm.y * t0;
  14197. projz = z + norm.z * t0;
  14198. tmpx = projx - x;
  14199. tmpy = projy - y;
  14200. tmpz = projz - z;
  14201. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14202. if (tmpDistance < shortest) {
  14203. shortest = tmpDistance;
  14204. closest = fib;
  14205. if (projected) {
  14206. projected.x = projx;
  14207. projected.y = projy;
  14208. projected.z = projz;
  14209. }
  14210. }
  14211. }
  14212. }
  14213. return closest;
  14214. };
  14215. /**
  14216. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14217. */
  14218. AbstractMesh.prototype.getFacetDataParameters = function () {
  14219. return this._facetParameters;
  14220. };
  14221. /**
  14222. * Disables the feature FacetData and frees the related memory.
  14223. * Returns the AbstractMesh.
  14224. */
  14225. AbstractMesh.prototype.disableFacetData = function () {
  14226. if (this._facetDataEnabled) {
  14227. this._facetDataEnabled = false;
  14228. this._facetPositions = null;
  14229. this._facetNormals = null;
  14230. this._facetPartitioning = null;
  14231. this._facetParameters = null;
  14232. }
  14233. return this;
  14234. };
  14235. /**
  14236. * Creates new normals data for the mesh.
  14237. * @param updatable.
  14238. */
  14239. AbstractMesh.prototype.createNormals = function (updatable) {
  14240. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14241. var indices = this.getIndices();
  14242. var normals;
  14243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14244. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14245. }
  14246. else {
  14247. normals = [];
  14248. }
  14249. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14250. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14251. };
  14252. return AbstractMesh;
  14253. }(BABYLON.Node));
  14254. // Statics
  14255. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14256. AbstractMesh._BILLBOARDMODE_X = 1;
  14257. AbstractMesh._BILLBOARDMODE_Y = 2;
  14258. AbstractMesh._BILLBOARDMODE_Z = 4;
  14259. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14260. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14261. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14262. BABYLON.AbstractMesh = AbstractMesh;
  14263. })(BABYLON || (BABYLON = {}));
  14264. //# sourceMappingURL=babylon.abstractMesh.js.map
  14265. var BABYLON;
  14266. (function (BABYLON) {
  14267. var Light = (function (_super) {
  14268. __extends(Light, _super);
  14269. /**
  14270. * Creates a Light object in the scene.
  14271. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14272. */
  14273. function Light(name, scene) {
  14274. var _this = _super.call(this, name, scene) || this;
  14275. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14276. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14277. _this.intensity = 1.0;
  14278. _this.range = Number.MAX_VALUE;
  14279. _this._excludeWithLayerMask = 0;
  14280. _this._includeOnlyWithLayerMask = 0;
  14281. _this._lightmapMode = 0;
  14282. // PBR Properties.
  14283. _this.radius = 0.00001;
  14284. _this._excludedMeshesIds = new Array();
  14285. _this._includedOnlyMeshesIds = new Array();
  14286. _this.getScene().addLight(_this);
  14287. _this.includedOnlyMeshes = new Array();
  14288. _this.excludedMeshes = new Array();
  14289. _this._resyncMeshes();
  14290. return _this;
  14291. }
  14292. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14293. /**
  14294. * If every light affecting the material is in this lightmapMode,
  14295. * material.lightmapTexture adds or multiplies
  14296. * (depends on material.useLightmapAsShadowmap)
  14297. * after every other light calculations.
  14298. */
  14299. get: function () {
  14300. return Light._LIGHTMAP_DEFAULT;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14306. /**
  14307. * material.lightmapTexture as only diffuse lighting from this light
  14308. * adds pnly specular lighting from this light
  14309. * adds dynamic shadows
  14310. */
  14311. get: function () {
  14312. return Light._LIGHTMAP_SPECULAR;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14318. /**
  14319. * material.lightmapTexture as only lighting
  14320. * no light calculation from this light
  14321. * only adds dynamic shadows from this light
  14322. */
  14323. get: function () {
  14324. return Light._LIGHTMAP_SHADOWSONLY;
  14325. },
  14326. enumerable: true,
  14327. configurable: true
  14328. });
  14329. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14330. get: function () {
  14331. return this._includedOnlyMeshes;
  14332. },
  14333. set: function (value) {
  14334. this._includedOnlyMeshes = value;
  14335. this._hookArrayForIncludedOnly(value);
  14336. },
  14337. enumerable: true,
  14338. configurable: true
  14339. });
  14340. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14341. get: function () {
  14342. return this._excludedMeshes;
  14343. },
  14344. set: function (value) {
  14345. this._excludedMeshes = value;
  14346. this._hookArrayForExcluded(value);
  14347. },
  14348. enumerable: true,
  14349. configurable: true
  14350. });
  14351. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14352. get: function () {
  14353. return this._excludeWithLayerMask;
  14354. },
  14355. set: function (value) {
  14356. this._excludeWithLayerMask = value;
  14357. this._resyncMeshes();
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14363. get: function () {
  14364. return this._includeOnlyWithLayerMask;
  14365. },
  14366. set: function (value) {
  14367. this._includeOnlyWithLayerMask = value;
  14368. this._resyncMeshes();
  14369. },
  14370. enumerable: true,
  14371. configurable: true
  14372. });
  14373. Object.defineProperty(Light.prototype, "lightmapMode", {
  14374. get: function () {
  14375. return this._lightmapMode;
  14376. },
  14377. set: function (value) {
  14378. if (this._lightmapMode === value) {
  14379. return;
  14380. }
  14381. this._lightmapMode = value;
  14382. this._markMeshesAsLightDirty();
  14383. },
  14384. enumerable: true,
  14385. configurable: true
  14386. });
  14387. /**
  14388. * Returns the string "Light".
  14389. */
  14390. Light.prototype.getClassName = function () {
  14391. return "Light";
  14392. };
  14393. /**
  14394. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14395. */
  14396. Light.prototype.toString = function (fullDetails) {
  14397. var ret = "Name: " + this.name;
  14398. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14399. if (this.animations) {
  14400. for (var i = 0; i < this.animations.length; i++) {
  14401. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14402. }
  14403. }
  14404. if (fullDetails) {
  14405. }
  14406. return ret;
  14407. };
  14408. /**
  14409. * Set the enabled state of this node.
  14410. * @param {boolean} value - the new enabled state
  14411. * @see isEnabled
  14412. */
  14413. Light.prototype.setEnabled = function (value) {
  14414. _super.prototype.setEnabled.call(this, value);
  14415. this._resyncMeshes();
  14416. };
  14417. /**
  14418. * Returns the Light associated shadow generator.
  14419. */
  14420. Light.prototype.getShadowGenerator = function () {
  14421. return this._shadowGenerator;
  14422. };
  14423. /**
  14424. * Returns a Vector3, the absolute light position in the World.
  14425. */
  14426. Light.prototype.getAbsolutePosition = function () {
  14427. return BABYLON.Vector3.Zero();
  14428. };
  14429. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  14430. };
  14431. Light.prototype._getWorldMatrix = function () {
  14432. return BABYLON.Matrix.Identity();
  14433. };
  14434. /**
  14435. * Boolean : True if the light will affect the passed mesh.
  14436. */
  14437. Light.prototype.canAffectMesh = function (mesh) {
  14438. if (!mesh) {
  14439. return true;
  14440. }
  14441. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14442. return false;
  14443. }
  14444. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14445. return false;
  14446. }
  14447. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14448. return false;
  14449. }
  14450. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14451. return false;
  14452. }
  14453. return true;
  14454. };
  14455. /**
  14456. * Returns the light World matrix.
  14457. */
  14458. Light.prototype.getWorldMatrix = function () {
  14459. this._currentRenderId = this.getScene().getRenderId();
  14460. var worldMatrix = this._getWorldMatrix();
  14461. if (this.parent && this.parent.getWorldMatrix) {
  14462. if (!this._parentedWorldMatrix) {
  14463. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14464. }
  14465. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14466. this._markSyncedWithParent();
  14467. return this._parentedWorldMatrix;
  14468. }
  14469. return worldMatrix;
  14470. };
  14471. /**
  14472. * Disposes the light.
  14473. */
  14474. Light.prototype.dispose = function () {
  14475. if (this._shadowGenerator) {
  14476. this._shadowGenerator.dispose();
  14477. this._shadowGenerator = null;
  14478. }
  14479. // Animations
  14480. this.getScene().stopAnimation(this);
  14481. // Remove from meshes
  14482. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14483. var mesh = _a[_i];
  14484. mesh._removeLightSource(this);
  14485. }
  14486. // Remove from scene
  14487. this.getScene().removeLight(this);
  14488. _super.prototype.dispose.call(this);
  14489. };
  14490. /**
  14491. * Returns the light type ID (integer).
  14492. */
  14493. Light.prototype.getTypeID = function () {
  14494. return 0;
  14495. };
  14496. /**
  14497. * Returns a new Light object, named "name", from the current one.
  14498. */
  14499. Light.prototype.clone = function (name) {
  14500. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14501. };
  14502. /**
  14503. * Serializes the current light into a Serialization object.
  14504. * Returns the serialized object.
  14505. */
  14506. Light.prototype.serialize = function () {
  14507. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14508. // Type
  14509. serializationObject.type = this.getTypeID();
  14510. // Parent
  14511. if (this.parent) {
  14512. serializationObject.parentId = this.parent.id;
  14513. }
  14514. // Inclusion / exclusions
  14515. if (this.excludedMeshes.length > 0) {
  14516. serializationObject.excludedMeshesIds = [];
  14517. this.excludedMeshes.forEach(function (mesh) {
  14518. serializationObject.excludedMeshesIds.push(mesh.id);
  14519. });
  14520. }
  14521. if (this.includedOnlyMeshes.length > 0) {
  14522. serializationObject.includedOnlyMeshesIds = [];
  14523. this.includedOnlyMeshes.forEach(function (mesh) {
  14524. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14525. });
  14526. }
  14527. // Animations
  14528. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14529. serializationObject.ranges = this.serializeAnimationRanges();
  14530. return serializationObject;
  14531. };
  14532. /**
  14533. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14534. * This new light is named "name" and added to the passed scene.
  14535. */
  14536. Light.GetConstructorFromName = function (type, name, scene) {
  14537. switch (type) {
  14538. case 0:
  14539. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14540. case 1:
  14541. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14542. case 2:
  14543. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14544. case 3:
  14545. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14546. }
  14547. };
  14548. /**
  14549. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14550. */
  14551. Light.Parse = function (parsedLight, scene) {
  14552. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14553. // Inclusion / exclusions
  14554. if (parsedLight.excludedMeshesIds) {
  14555. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14556. }
  14557. if (parsedLight.includedOnlyMeshesIds) {
  14558. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14559. }
  14560. // Parent
  14561. if (parsedLight.parentId) {
  14562. light._waitingParentId = parsedLight.parentId;
  14563. }
  14564. // Animations
  14565. if (parsedLight.animations) {
  14566. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14567. var parsedAnimation = parsedLight.animations[animationIndex];
  14568. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14569. }
  14570. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14571. }
  14572. if (parsedLight.autoAnimate) {
  14573. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14574. }
  14575. return light;
  14576. };
  14577. Light.prototype._hookArrayForExcluded = function (array) {
  14578. var _this = this;
  14579. var oldPush = array.push;
  14580. array.push = function () {
  14581. var items = [];
  14582. for (var _i = 0; _i < arguments.length; _i++) {
  14583. items[_i] = arguments[_i];
  14584. }
  14585. var result = oldPush.apply(array, items);
  14586. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14587. var item = items_1[_a];
  14588. item._resyncLighSource(_this);
  14589. }
  14590. return result;
  14591. };
  14592. var oldSplice = array.splice;
  14593. array.splice = function (index, deleteCount) {
  14594. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14595. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14596. var item = deleted_1[_i];
  14597. item._resyncLighSource(_this);
  14598. }
  14599. return deleted;
  14600. };
  14601. };
  14602. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14603. var _this = this;
  14604. var oldPush = array.push;
  14605. array.push = function () {
  14606. var items = [];
  14607. for (var _i = 0; _i < arguments.length; _i++) {
  14608. items[_i] = arguments[_i];
  14609. }
  14610. var result = oldPush.apply(array, items);
  14611. _this._resyncMeshes();
  14612. return result;
  14613. };
  14614. var oldSplice = array.splice;
  14615. array.splice = function (index, deleteCount) {
  14616. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14617. _this._resyncMeshes();
  14618. return deleted;
  14619. };
  14620. };
  14621. Light.prototype._resyncMeshes = function () {
  14622. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14623. var mesh = _a[_i];
  14624. mesh._resyncLighSource(this);
  14625. }
  14626. };
  14627. Light.prototype._markMeshesAsLightDirty = function () {
  14628. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14629. var mesh = _a[_i];
  14630. if (mesh._lightSources.indexOf(this) !== -1) {
  14631. mesh._markSubMeshesAsLightDirty();
  14632. }
  14633. }
  14634. };
  14635. return Light;
  14636. }(BABYLON.Node));
  14637. //lightmapMode Consts
  14638. Light._LIGHTMAP_DEFAULT = 0;
  14639. Light._LIGHTMAP_SPECULAR = 1;
  14640. Light._LIGHTMAP_SHADOWSONLY = 2;
  14641. __decorate([
  14642. BABYLON.serializeAsColor3()
  14643. ], Light.prototype, "diffuse", void 0);
  14644. __decorate([
  14645. BABYLON.serializeAsColor3()
  14646. ], Light.prototype, "specular", void 0);
  14647. __decorate([
  14648. BABYLON.serialize()
  14649. ], Light.prototype, "intensity", void 0);
  14650. __decorate([
  14651. BABYLON.serialize()
  14652. ], Light.prototype, "range", void 0);
  14653. __decorate([
  14654. BABYLON.serialize("excludeWithLayerMask")
  14655. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14656. __decorate([
  14657. BABYLON.serialize("includeOnlyWithLayerMask")
  14658. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14659. __decorate([
  14660. BABYLON.serialize("lightmapMode")
  14661. ], Light.prototype, "_lightmapMode", void 0);
  14662. __decorate([
  14663. BABYLON.serialize()
  14664. ], Light.prototype, "radius", void 0);
  14665. BABYLON.Light = Light;
  14666. })(BABYLON || (BABYLON = {}));
  14667. //# sourceMappingURL=babylon.light.js.map
  14668. var BABYLON;
  14669. (function (BABYLON) {
  14670. var PointLight = (function (_super) {
  14671. __extends(PointLight, _super);
  14672. /**
  14673. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14674. * A PointLight emits the light in every direction.
  14675. * It can cast shadows.
  14676. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14677. * ```javascript
  14678. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14679. * ```
  14680. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14681. */
  14682. function PointLight(name, position, scene) {
  14683. var _this = _super.call(this, name, scene) || this;
  14684. _this.position = position;
  14685. return _this;
  14686. }
  14687. /**
  14688. * Returns the string "PointLight"
  14689. */
  14690. PointLight.prototype.getClassName = function () {
  14691. return "PointLight";
  14692. };
  14693. /**
  14694. * Returns a Vector3, the PointLight absolute position in the World.
  14695. */
  14696. PointLight.prototype.getAbsolutePosition = function () {
  14697. return this.transformedPosition ? this.transformedPosition : this.position;
  14698. };
  14699. /**
  14700. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14701. */
  14702. PointLight.prototype.computeTransformedPosition = function () {
  14703. if (this.parent && this.parent.getWorldMatrix) {
  14704. if (!this.transformedPosition) {
  14705. this.transformedPosition = BABYLON.Vector3.Zero();
  14706. }
  14707. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14708. return true;
  14709. }
  14710. return false;
  14711. };
  14712. /**
  14713. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14714. * Returns the PointLight.
  14715. */
  14716. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14717. if (this.parent && this.parent.getWorldMatrix) {
  14718. this.computeTransformedPosition();
  14719. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14720. return this;
  14721. }
  14722. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14723. return this;
  14724. };
  14725. /**
  14726. * Boolean : returns true by default.
  14727. */
  14728. PointLight.prototype.needCube = function () {
  14729. return true;
  14730. };
  14731. /**
  14732. * Boolean : returns false by default.
  14733. */
  14734. PointLight.prototype.needRefreshPerFrame = function () {
  14735. return false;
  14736. };
  14737. /**
  14738. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14739. */
  14740. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14741. switch (faceIndex) {
  14742. case 0:
  14743. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14744. case 1:
  14745. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14746. case 2:
  14747. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14748. case 3:
  14749. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14750. case 4:
  14751. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14752. case 5:
  14753. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14754. }
  14755. return BABYLON.Vector3.Zero();
  14756. };
  14757. /**
  14758. * Return the depth scale used for the shadow map.
  14759. */
  14760. PointLight.prototype.getDepthScale = function () {
  14761. return 30.0;
  14762. };
  14763. /**
  14764. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14765. * - fov = PI / 2
  14766. * - aspect ratio : 1.0
  14767. * - z-near and far equal to the active camera minZ and maxZ.
  14768. * Returns the PointLight.
  14769. */
  14770. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14771. if (this.customProjectionMatrixBuilder) {
  14772. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14773. }
  14774. else {
  14775. var activeCamera = this.getScene().activeCamera;
  14776. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14777. }
  14778. return this;
  14779. };
  14780. PointLight.prototype._getWorldMatrix = function () {
  14781. if (!this._worldMatrix) {
  14782. this._worldMatrix = BABYLON.Matrix.Identity();
  14783. }
  14784. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14785. return this._worldMatrix;
  14786. };
  14787. /**
  14788. * Returns the integer 0.
  14789. */
  14790. PointLight.prototype.getTypeID = function () {
  14791. return 0;
  14792. };
  14793. return PointLight;
  14794. }(BABYLON.Light));
  14795. __decorate([
  14796. BABYLON.serializeAsVector3()
  14797. ], PointLight.prototype, "position", void 0);
  14798. __decorate([
  14799. BABYLON.serialize()
  14800. ], PointLight.prototype, "shadowMinZ", void 0);
  14801. __decorate([
  14802. BABYLON.serialize()
  14803. ], PointLight.prototype, "shadowMaxZ", void 0);
  14804. BABYLON.PointLight = PointLight;
  14805. })(BABYLON || (BABYLON = {}));
  14806. //# sourceMappingURL=babylon.pointLight.js.map
  14807. var BABYLON;
  14808. (function (BABYLON) {
  14809. var SpotLight = (function (_super) {
  14810. __extends(SpotLight, _super);
  14811. /**
  14812. * Creates a SpotLight object in the scene with the passed parameters :
  14813. * - `position` (Vector3) is the initial SpotLight position,
  14814. * - `direction` (Vector3) is the initial SpotLight direction,
  14815. * - `angle` (float, in radians) is the spot light cone angle,
  14816. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14817. * A spot light is a simply light oriented cone.
  14818. * It can cast shadows.
  14819. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14820. */
  14821. function SpotLight(name, position, direction, angle, exponent, scene) {
  14822. var _this = _super.call(this, name, scene) || this;
  14823. _this.position = position;
  14824. _this.direction = direction;
  14825. _this.angle = angle;
  14826. _this.exponent = exponent;
  14827. return _this;
  14828. }
  14829. /**
  14830. * Returns the string "SpotLight".
  14831. */
  14832. SpotLight.prototype.getClassName = function () {
  14833. return "SpotLight";
  14834. };
  14835. /**
  14836. * Returns the SpotLight absolute position in the World (Vector3).
  14837. */
  14838. SpotLight.prototype.getAbsolutePosition = function () {
  14839. return this.transformedPosition ? this.transformedPosition : this.position;
  14840. };
  14841. /**
  14842. * Return the depth scale used for the shadow map.
  14843. */
  14844. SpotLight.prototype.getDepthScale = function () {
  14845. return 30.0;
  14846. };
  14847. /**
  14848. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  14849. * Returns the SpotLight.
  14850. */
  14851. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14852. if (this.customProjectionMatrixBuilder) {
  14853. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14854. }
  14855. else {
  14856. var activeCamera = this.getScene().activeCamera;
  14857. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14858. }
  14859. return this;
  14860. };
  14861. /**
  14862. * Boolean : false by default.
  14863. */
  14864. SpotLight.prototype.needCube = function () {
  14865. return false;
  14866. };
  14867. /**
  14868. * Boolean : false by default.
  14869. */
  14870. SpotLight.prototype.needRefreshPerFrame = function () {
  14871. return false;
  14872. };
  14873. /**
  14874. * Returns the SpotLight direction (Vector3) for any passed face index.
  14875. */
  14876. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14877. return this.direction;
  14878. };
  14879. /**
  14880. * Updates the SpotLight direction towards the passed target (Vector3).
  14881. * Returns the updated direction.
  14882. */
  14883. SpotLight.prototype.setDirectionToTarget = function (target) {
  14884. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14885. return this.direction;
  14886. };
  14887. /**
  14888. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14889. */
  14890. SpotLight.prototype.computeTransformedPosition = function () {
  14891. if (this.parent && this.parent.getWorldMatrix) {
  14892. if (!this.transformedPosition) {
  14893. this.transformedPosition = BABYLON.Vector3.Zero();
  14894. }
  14895. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14896. return true;
  14897. }
  14898. return false;
  14899. };
  14900. /**
  14901. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14902. * Return the SpotLight.
  14903. */
  14904. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14905. var normalizeDirection;
  14906. if (this.parent && this.parent.getWorldMatrix) {
  14907. if (!this._transformedDirection) {
  14908. this._transformedDirection = BABYLON.Vector3.Zero();
  14909. }
  14910. this.computeTransformedPosition();
  14911. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14912. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14913. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14914. }
  14915. else {
  14916. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14917. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14918. }
  14919. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14920. return this;
  14921. };
  14922. SpotLight.prototype._getWorldMatrix = function () {
  14923. if (!this._worldMatrix) {
  14924. this._worldMatrix = BABYLON.Matrix.Identity();
  14925. }
  14926. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14927. return this._worldMatrix;
  14928. };
  14929. /**
  14930. * Returns the integer 2.
  14931. */
  14932. SpotLight.prototype.getTypeID = function () {
  14933. return 2;
  14934. };
  14935. /**
  14936. * Returns the SpotLight rotation (Vector3).
  14937. */
  14938. SpotLight.prototype.getRotation = function () {
  14939. this.direction.normalize();
  14940. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14941. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14942. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14943. };
  14944. return SpotLight;
  14945. }(BABYLON.Light));
  14946. __decorate([
  14947. BABYLON.serializeAsVector3()
  14948. ], SpotLight.prototype, "position", void 0);
  14949. __decorate([
  14950. BABYLON.serializeAsVector3()
  14951. ], SpotLight.prototype, "direction", void 0);
  14952. __decorate([
  14953. BABYLON.serialize()
  14954. ], SpotLight.prototype, "angle", void 0);
  14955. __decorate([
  14956. BABYLON.serialize()
  14957. ], SpotLight.prototype, "exponent", void 0);
  14958. __decorate([
  14959. BABYLON.serialize()
  14960. ], SpotLight.prototype, "shadowMinZ", void 0);
  14961. __decorate([
  14962. BABYLON.serialize()
  14963. ], SpotLight.prototype, "shadowMaxZ", void 0);
  14964. BABYLON.SpotLight = SpotLight;
  14965. })(BABYLON || (BABYLON = {}));
  14966. //# sourceMappingURL=babylon.spotLight.js.map
  14967. var BABYLON;
  14968. (function (BABYLON) {
  14969. var HemisphericLight = (function (_super) {
  14970. __extends(HemisphericLight, _super);
  14971. /**
  14972. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14973. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14974. * The HemisphericLight can't cast shadows.
  14975. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14976. */
  14977. function HemisphericLight(name, direction, scene) {
  14978. var _this = _super.call(this, name, scene) || this;
  14979. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14980. _this.direction = direction;
  14981. return _this;
  14982. }
  14983. /**
  14984. * Returns the string "HemisphericLight".
  14985. */
  14986. HemisphericLight.prototype.getClassName = function () {
  14987. return "HemisphericLight";
  14988. };
  14989. /**
  14990. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14991. * Returns the updated direction.
  14992. */
  14993. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14994. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14995. return this.direction;
  14996. };
  14997. HemisphericLight.prototype.getShadowGenerator = function () {
  14998. return null;
  14999. };
  15000. /**
  15001. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  15002. * Returns the HemisphericLight.
  15003. */
  15004. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  15005. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  15006. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  15007. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  15008. return this;
  15009. };
  15010. HemisphericLight.prototype._getWorldMatrix = function () {
  15011. if (!this._worldMatrix) {
  15012. this._worldMatrix = BABYLON.Matrix.Identity();
  15013. }
  15014. return this._worldMatrix;
  15015. };
  15016. /**
  15017. * Returns the integer 3.
  15018. */
  15019. HemisphericLight.prototype.getTypeID = function () {
  15020. return 3;
  15021. };
  15022. return HemisphericLight;
  15023. }(BABYLON.Light));
  15024. __decorate([
  15025. BABYLON.serializeAsColor3()
  15026. ], HemisphericLight.prototype, "groundColor", void 0);
  15027. __decorate([
  15028. BABYLON.serializeAsVector3()
  15029. ], HemisphericLight.prototype, "direction", void 0);
  15030. BABYLON.HemisphericLight = HemisphericLight;
  15031. })(BABYLON || (BABYLON = {}));
  15032. //# sourceMappingURL=babylon.hemisphericLight.js.map
  15033. /// <reference path="babylon.light.ts" />
  15034. var BABYLON;
  15035. (function (BABYLON) {
  15036. var DirectionalLight = (function (_super) {
  15037. __extends(DirectionalLight, _super);
  15038. /**
  15039. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  15040. * The directional light is emitted from everywhere in the given direction.
  15041. * It can cast shawdows.
  15042. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15043. */
  15044. function DirectionalLight(name, direction, scene) {
  15045. var _this = _super.call(this, name, scene) || this;
  15046. _this.shadowOrthoScale = 0.5;
  15047. _this.autoUpdateExtends = true;
  15048. // Cache
  15049. _this._orthoLeft = Number.MAX_VALUE;
  15050. _this._orthoRight = Number.MIN_VALUE;
  15051. _this._orthoTop = Number.MIN_VALUE;
  15052. _this._orthoBottom = Number.MAX_VALUE;
  15053. _this.position = direction.scale(-1.0);
  15054. _this.direction = direction;
  15055. return _this;
  15056. }
  15057. /**
  15058. * Returns the string "DirectionalLight".
  15059. */
  15060. DirectionalLight.prototype.getClassName = function () {
  15061. return "DirectionalLight";
  15062. };
  15063. /**
  15064. * Returns the DirectionalLight absolute position in the World.
  15065. */
  15066. DirectionalLight.prototype.getAbsolutePosition = function () {
  15067. return this.transformedPosition ? this.transformedPosition : this.position;
  15068. };
  15069. /**
  15070. * Sets the DirectionalLight direction toward the passed target (Vector3).
  15071. * Returns the updated DirectionalLight direction (Vector3).
  15072. */
  15073. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  15074. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  15075. return this.direction;
  15076. };
  15077. /**
  15078. * Return the depth scale used for the shadow map.
  15079. */
  15080. DirectionalLight.prototype.getDepthScale = function () {
  15081. return 30.0;
  15082. };
  15083. /**
  15084. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  15085. * Returns the DirectionalLight.
  15086. */
  15087. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  15088. if (this.customProjectionMatrixBuilder) {
  15089. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  15090. }
  15091. else {
  15092. var activeCamera = this.getScene().activeCamera;
  15093. // Check extends
  15094. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  15095. var tempVector3 = BABYLON.Vector3.Zero();
  15096. this._orthoLeft = Number.MAX_VALUE;
  15097. this._orthoRight = Number.MIN_VALUE;
  15098. this._orthoTop = Number.MIN_VALUE;
  15099. this._orthoBottom = Number.MAX_VALUE;
  15100. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  15101. var mesh = renderList[meshIndex];
  15102. if (!mesh) {
  15103. continue;
  15104. }
  15105. var boundingInfo = mesh.getBoundingInfo();
  15106. if (!boundingInfo) {
  15107. continue;
  15108. }
  15109. var boundingBox = boundingInfo.boundingBox;
  15110. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  15111. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  15112. if (tempVector3.x < this._orthoLeft)
  15113. this._orthoLeft = tempVector3.x;
  15114. if (tempVector3.y < this._orthoBottom)
  15115. this._orthoBottom = tempVector3.y;
  15116. if (tempVector3.x > this._orthoRight)
  15117. this._orthoRight = tempVector3.x;
  15118. if (tempVector3.y > this._orthoTop)
  15119. this._orthoTop = tempVector3.y;
  15120. }
  15121. }
  15122. }
  15123. var xOffset = this._orthoRight - this._orthoLeft;
  15124. var yOffset = this._orthoTop - this._orthoBottom;
  15125. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  15126. }
  15127. return this;
  15128. };
  15129. /**
  15130. * Boolean : true by default.
  15131. */
  15132. DirectionalLight.prototype.needRefreshPerFrame = function () {
  15133. return true;
  15134. };
  15135. /**
  15136. * Boolean : false by default.
  15137. */
  15138. DirectionalLight.prototype.needCube = function () {
  15139. return false;
  15140. };
  15141. /**
  15142. * Returns the light direction (Vector3) for any passed face index.
  15143. */
  15144. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  15145. return this.direction;
  15146. };
  15147. /**
  15148. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  15149. */
  15150. DirectionalLight.prototype.computeTransformedPosition = function () {
  15151. if (this.parent && this.parent.getWorldMatrix) {
  15152. if (!this.transformedPosition) {
  15153. this.transformedPosition = BABYLON.Vector3.Zero();
  15154. }
  15155. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  15156. return true;
  15157. }
  15158. return false;
  15159. };
  15160. /**
  15161. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  15162. * Returns the DirectionalLight.
  15163. */
  15164. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  15165. if (this.parent && this.parent.getWorldMatrix) {
  15166. if (!this._transformedDirection) {
  15167. this._transformedDirection = BABYLON.Vector3.Zero();
  15168. }
  15169. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  15170. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  15171. return this;
  15172. }
  15173. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  15174. return this;
  15175. };
  15176. DirectionalLight.prototype._getWorldMatrix = function () {
  15177. if (!this._worldMatrix) {
  15178. this._worldMatrix = BABYLON.Matrix.Identity();
  15179. }
  15180. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  15181. return this._worldMatrix;
  15182. };
  15183. /**
  15184. * Returns the integer 1.
  15185. */
  15186. DirectionalLight.prototype.getTypeID = function () {
  15187. return 1;
  15188. };
  15189. return DirectionalLight;
  15190. }(BABYLON.Light));
  15191. __decorate([
  15192. BABYLON.serializeAsVector3()
  15193. ], DirectionalLight.prototype, "position", void 0);
  15194. __decorate([
  15195. BABYLON.serializeAsVector3()
  15196. ], DirectionalLight.prototype, "direction", void 0);
  15197. __decorate([
  15198. BABYLON.serialize()
  15199. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  15200. __decorate([
  15201. BABYLON.serialize()
  15202. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  15203. __decorate([
  15204. BABYLON.serialize()
  15205. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  15206. __decorate([
  15207. BABYLON.serialize()
  15208. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  15209. BABYLON.DirectionalLight = DirectionalLight;
  15210. })(BABYLON || (BABYLON = {}));
  15211. //# sourceMappingURL=babylon.directionalLight.js.map
  15212. var BABYLON;
  15213. (function (BABYLON) {
  15214. var ShadowGenerator = (function () {
  15215. /**
  15216. * Creates a ShadowGenerator object.
  15217. * A ShadowGenerator is the required tool to use the shadows.
  15218. * Each light casting shadows needs to use its own ShadowGenerator.
  15219. * Required parameters :
  15220. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  15221. * - `light` : the light object generating the shadows.
  15222. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  15223. */
  15224. function ShadowGenerator(mapSize, light) {
  15225. var _this = this;
  15226. // Members
  15227. this._filter = ShadowGenerator.FILTER_NONE;
  15228. this.blurScale = 2;
  15229. this._blurBoxOffset = 0;
  15230. this._bias = 0.00005;
  15231. this._lightDirection = BABYLON.Vector3.Zero();
  15232. this.forceBackFacesOnly = false;
  15233. this._darkness = 0;
  15234. this._transparencyShadow = false;
  15235. this._viewMatrix = BABYLON.Matrix.Zero();
  15236. this._projectionMatrix = BABYLON.Matrix.Zero();
  15237. this._transformMatrix = BABYLON.Matrix.Zero();
  15238. this._worldViewProjection = BABYLON.Matrix.Zero();
  15239. this._currentFaceIndex = 0;
  15240. this._currentFaceIndexCache = 0;
  15241. this._useFullFloat = true;
  15242. this._light = light;
  15243. this._scene = light.getScene();
  15244. this._mapSize = mapSize;
  15245. light._shadowGenerator = this;
  15246. light._markMeshesAsLightDirty();
  15247. // Texture type fallback from float to int if not supported.
  15248. var textureType;
  15249. var caps = this._scene.getEngine().getCaps();
  15250. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  15251. this._useFullFloat = true;
  15252. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  15253. }
  15254. else {
  15255. this._useFullFloat = false;
  15256. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  15257. }
  15258. // Render target
  15259. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  15260. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15261. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15262. this._shadowMap.anisotropicFilteringLevel = 1;
  15263. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15264. this._shadowMap.renderParticles = false;
  15265. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  15266. _this._currentFaceIndex = faceIndex;
  15267. });
  15268. this._shadowMap.onAfterUnbindObservable.add(function () {
  15269. if (!_this.useBlurExponentialShadowMap) {
  15270. return;
  15271. }
  15272. if (!_this._shadowMap2) {
  15273. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  15274. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15275. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15276. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15277. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  15278. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  15279. effect.setTexture("textureSampler", _this._shadowMap);
  15280. });
  15281. _this.blurBoxOffset = 1;
  15282. }
  15283. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  15284. });
  15285. // Custom render function
  15286. var renderSubMesh = function (subMesh) {
  15287. var mesh = subMesh.getRenderingMesh();
  15288. var scene = _this._scene;
  15289. var engine = scene.getEngine();
  15290. // Culling
  15291. engine.setState(subMesh.getMaterial().backFaceCulling);
  15292. // Managing instances
  15293. var batch = mesh._getInstancesRenderList(subMesh._id);
  15294. if (batch.mustReturn) {
  15295. return;
  15296. }
  15297. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15298. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  15299. engine.enableEffect(_this._effect);
  15300. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  15301. var material = subMesh.getMaterial();
  15302. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  15303. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  15304. _this._effect.setVector3("lightPosition", _this.getLight().position);
  15305. if (_this.getLight().needCube()) {
  15306. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  15307. }
  15308. // Alpha test
  15309. if (material && material.needAlphaTesting()) {
  15310. var alphaTexture = material.getAlphaTestTexture();
  15311. _this._effect.setTexture("diffuseSampler", alphaTexture);
  15312. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  15313. }
  15314. // Bones
  15315. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  15316. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  15317. }
  15318. if (_this.forceBackFacesOnly) {
  15319. engine.setState(true, 0, false, true);
  15320. }
  15321. // Draw
  15322. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  15323. if (_this.forceBackFacesOnly) {
  15324. engine.setState(true, 0, false, false);
  15325. }
  15326. }
  15327. else {
  15328. // Need to reset refresh rate of the shadowMap
  15329. _this._shadowMap.resetRefreshCounter();
  15330. }
  15331. };
  15332. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  15333. var index;
  15334. for (index = 0; index < opaqueSubMeshes.length; index++) {
  15335. renderSubMesh(opaqueSubMeshes.data[index]);
  15336. }
  15337. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  15338. renderSubMesh(alphaTestSubMeshes.data[index]);
  15339. }
  15340. if (_this._transparencyShadow) {
  15341. for (index = 0; index < transparentSubMeshes.length; index++) {
  15342. renderSubMesh(transparentSubMeshes.data[index]);
  15343. }
  15344. }
  15345. };
  15346. this._shadowMap.onClearObservable.add(function (engine) {
  15347. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  15348. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  15349. }
  15350. else {
  15351. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  15352. }
  15353. });
  15354. }
  15355. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  15356. // Static
  15357. get: function () {
  15358. return ShadowGenerator._FILTER_NONE;
  15359. },
  15360. enumerable: true,
  15361. configurable: true
  15362. });
  15363. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  15364. get: function () {
  15365. return ShadowGenerator._FILTER_POISSONSAMPLING;
  15366. },
  15367. enumerable: true,
  15368. configurable: true
  15369. });
  15370. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  15371. get: function () {
  15372. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  15373. },
  15374. enumerable: true,
  15375. configurable: true
  15376. });
  15377. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  15378. get: function () {
  15379. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  15380. },
  15381. enumerable: true,
  15382. configurable: true
  15383. });
  15384. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  15385. get: function () {
  15386. return this._bias;
  15387. },
  15388. set: function (bias) {
  15389. this._bias = bias;
  15390. },
  15391. enumerable: true,
  15392. configurable: true
  15393. });
  15394. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  15395. get: function () {
  15396. return this._blurBoxOffset;
  15397. },
  15398. set: function (value) {
  15399. var _this = this;
  15400. if (this._blurBoxOffset === value) {
  15401. return;
  15402. }
  15403. this._blurBoxOffset = value;
  15404. if (this._boxBlurPostprocess) {
  15405. this._boxBlurPostprocess.dispose();
  15406. }
  15407. var textureType;
  15408. var caps = this._scene.getEngine().getCaps();
  15409. if (this._useFullFloat) {
  15410. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  15411. }
  15412. else {
  15413. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  15414. }
  15415. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value, textureType);
  15416. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  15417. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  15418. });
  15419. },
  15420. enumerable: true,
  15421. configurable: true
  15422. });
  15423. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  15424. get: function () {
  15425. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  15426. },
  15427. set: function (value) {
  15428. this._depthScale = value;
  15429. },
  15430. enumerable: true,
  15431. configurable: true
  15432. });
  15433. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  15434. get: function () {
  15435. return this._filter;
  15436. },
  15437. set: function (value) {
  15438. if (this._filter === value) {
  15439. return;
  15440. }
  15441. this._filter = value;
  15442. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  15443. this._shadowMap.anisotropicFilteringLevel = 16;
  15444. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  15445. }
  15446. else {
  15447. this._shadowMap.anisotropicFilteringLevel = 1;
  15448. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  15449. }
  15450. this._light._markMeshesAsLightDirty();
  15451. },
  15452. enumerable: true,
  15453. configurable: true
  15454. });
  15455. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  15456. get: function () {
  15457. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  15458. return this.useExponentialShadowMap;
  15459. },
  15460. set: function (value) {
  15461. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  15462. this.useExponentialShadowMap = value;
  15463. },
  15464. enumerable: true,
  15465. configurable: true
  15466. });
  15467. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  15468. get: function () {
  15469. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  15470. },
  15471. set: function (value) {
  15472. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  15473. },
  15474. enumerable: true,
  15475. configurable: true
  15476. });
  15477. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  15478. get: function () {
  15479. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  15480. },
  15481. set: function (value) {
  15482. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  15483. },
  15484. enumerable: true,
  15485. configurable: true
  15486. });
  15487. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  15488. get: function () {
  15489. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  15490. return this.useBlurExponentialShadowMap;
  15491. },
  15492. set: function (value) {
  15493. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  15494. this.useBlurExponentialShadowMap = value;
  15495. },
  15496. enumerable: true,
  15497. configurable: true
  15498. });
  15499. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  15500. get: function () {
  15501. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  15502. },
  15503. set: function (value) {
  15504. if (this._light.needCube() && value) {
  15505. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  15506. }
  15507. else {
  15508. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  15509. }
  15510. },
  15511. enumerable: true,
  15512. configurable: true
  15513. });
  15514. /**
  15515. * Boolean : true when the ShadowGenerator is finally computed.
  15516. */
  15517. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  15518. var defines = [];
  15519. if (this._useFullFloat) {
  15520. defines.push("#define FULLFLOAT");
  15521. }
  15522. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  15523. defines.push("#define ESM");
  15524. }
  15525. if (this.getLight().needCube()) {
  15526. defines.push("#define CUBEMAP");
  15527. }
  15528. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15529. var mesh = subMesh.getMesh();
  15530. var material = subMesh.getMaterial();
  15531. // Alpha test
  15532. if (material && material.needAlphaTesting()) {
  15533. defines.push("#define ALPHATEST");
  15534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15535. attribs.push(BABYLON.VertexBuffer.UVKind);
  15536. defines.push("#define UV1");
  15537. }
  15538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15539. var alphaTexture = material.getAlphaTestTexture();
  15540. if (alphaTexture.coordinatesIndex === 1) {
  15541. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15542. defines.push("#define UV2");
  15543. }
  15544. }
  15545. }
  15546. // Bones
  15547. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  15548. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15549. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15550. if (mesh.numBoneInfluencers > 4) {
  15551. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  15552. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  15553. }
  15554. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  15555. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15556. }
  15557. else {
  15558. defines.push("#define NUM_BONE_INFLUENCERS 0");
  15559. }
  15560. // Instances
  15561. if (useInstances) {
  15562. defines.push("#define INSTANCES");
  15563. attribs.push("world0");
  15564. attribs.push("world1");
  15565. attribs.push("world2");
  15566. attribs.push("world3");
  15567. }
  15568. // Get correct effect
  15569. var join = defines.join("\n");
  15570. if (this._cachedDefines !== join) {
  15571. this._cachedDefines = join;
  15572. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  15573. }
  15574. return this._effect.isReady();
  15575. };
  15576. /**
  15577. * Returns a RenderTargetTexture object : the shadow map texture.
  15578. */
  15579. ShadowGenerator.prototype.getShadowMap = function () {
  15580. return this._shadowMap;
  15581. };
  15582. /**
  15583. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  15584. */
  15585. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  15586. if (this._shadowMap2) {
  15587. return this._shadowMap2;
  15588. }
  15589. return this._shadowMap;
  15590. };
  15591. /**
  15592. * Returns the associated light object.
  15593. */
  15594. ShadowGenerator.prototype.getLight = function () {
  15595. return this._light;
  15596. };
  15597. // Methods
  15598. /**
  15599. * Returns a Matrix object : the updated transformation matrix.
  15600. */
  15601. ShadowGenerator.prototype.getTransformMatrix = function () {
  15602. var scene = this._scene;
  15603. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  15604. return this._transformMatrix;
  15605. }
  15606. this._currentRenderID = scene.getRenderId();
  15607. this._currentFaceIndexCache = this._currentFaceIndex;
  15608. var lightPosition = this._light.position;
  15609. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  15610. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  15611. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  15612. }
  15613. if (this._light.computeTransformedPosition()) {
  15614. lightPosition = this._light.transformedPosition;
  15615. }
  15616. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  15617. this._cachedPosition = lightPosition.clone();
  15618. this._cachedDirection = this._lightDirection.clone();
  15619. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  15620. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  15621. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15622. }
  15623. return this._transformMatrix;
  15624. };
  15625. /**
  15626. * Returns the darkness value (float).
  15627. */
  15628. ShadowGenerator.prototype.getDarkness = function () {
  15629. return this._darkness;
  15630. };
  15631. /**
  15632. * Sets the ShadowGenerator darkness value (float <= 1.0).
  15633. * Returns the ShadowGenerator.
  15634. */
  15635. ShadowGenerator.prototype.setDarkness = function (darkness) {
  15636. if (darkness >= 1.0)
  15637. this._darkness = 1.0;
  15638. else if (darkness <= 0.0)
  15639. this._darkness = 0.0;
  15640. else
  15641. this._darkness = darkness;
  15642. return this;
  15643. };
  15644. /**
  15645. * Sets the ability to have transparent shadow (boolean).
  15646. * Returns the ShadowGenerator.
  15647. */
  15648. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  15649. this._transparencyShadow = hasShadow;
  15650. return this;
  15651. };
  15652. ShadowGenerator.prototype._packHalf = function (depth) {
  15653. var scale = depth * 255.0;
  15654. var fract = scale - Math.floor(scale);
  15655. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  15656. };
  15657. /**
  15658. * Disposes the ShadowGenerator.
  15659. * Returns nothing.
  15660. */
  15661. ShadowGenerator.prototype.dispose = function () {
  15662. this._shadowMap.dispose();
  15663. if (this._shadowMap2) {
  15664. this._shadowMap2.dispose();
  15665. }
  15666. if (this._downSamplePostprocess) {
  15667. this._downSamplePostprocess.dispose();
  15668. }
  15669. if (this._boxBlurPostprocess) {
  15670. this._boxBlurPostprocess.dispose();
  15671. }
  15672. this._light._shadowGenerator = null;
  15673. this._light._markMeshesAsLightDirty();
  15674. };
  15675. /**
  15676. * Serializes the ShadowGenerator and returns a serializationObject.
  15677. */
  15678. ShadowGenerator.prototype.serialize = function () {
  15679. var serializationObject = {};
  15680. serializationObject.lightId = this._light.id;
  15681. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15682. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  15683. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  15684. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15685. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15686. serializationObject.depthScale = this.depthScale;
  15687. serializationObject.darkness = this.getDarkness();
  15688. serializationObject.renderList = [];
  15689. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15690. var mesh = this.getShadowMap().renderList[meshIndex];
  15691. serializationObject.renderList.push(mesh.id);
  15692. }
  15693. return serializationObject;
  15694. };
  15695. /**
  15696. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15697. */
  15698. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15699. //casting to point light, as light is missing the position attr and typescript complains.
  15700. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15701. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15702. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15703. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15704. meshes.forEach(function (mesh) {
  15705. shadowGenerator.getShadowMap().renderList.push(mesh);
  15706. });
  15707. }
  15708. if (parsedShadowGenerator.usePoissonSampling) {
  15709. shadowGenerator.usePoissonSampling = true;
  15710. }
  15711. else if (parsedShadowGenerator.useExponentialShadowMap) {
  15712. shadowGenerator.useExponentialShadowMap = true;
  15713. }
  15714. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  15715. shadowGenerator.useBlurExponentialShadowMap = true;
  15716. }
  15717. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15718. shadowGenerator.useExponentialShadowMap = true;
  15719. }
  15720. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15721. shadowGenerator.useBlurExponentialShadowMap = true;
  15722. }
  15723. if (parsedShadowGenerator.depthScale) {
  15724. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  15725. }
  15726. if (parsedShadowGenerator.blurScale) {
  15727. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15728. }
  15729. if (parsedShadowGenerator.blurBoxOffset) {
  15730. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15731. }
  15732. if (parsedShadowGenerator.bias !== undefined) {
  15733. shadowGenerator.bias = parsedShadowGenerator.bias;
  15734. }
  15735. if (parsedShadowGenerator.darkness) {
  15736. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15737. }
  15738. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15739. return shadowGenerator;
  15740. };
  15741. return ShadowGenerator;
  15742. }());
  15743. ShadowGenerator._FILTER_NONE = 0;
  15744. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  15745. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15746. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  15747. BABYLON.ShadowGenerator = ShadowGenerator;
  15748. })(BABYLON || (BABYLON = {}));
  15749. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15750. var BABYLON;
  15751. (function (BABYLON) {
  15752. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15753. if (boxMin.x > sphereCenter.x + sphereRadius)
  15754. return false;
  15755. if (sphereCenter.x - sphereRadius > boxMax.x)
  15756. return false;
  15757. if (boxMin.y > sphereCenter.y + sphereRadius)
  15758. return false;
  15759. if (sphereCenter.y - sphereRadius > boxMax.y)
  15760. return false;
  15761. if (boxMin.z > sphereCenter.z + sphereRadius)
  15762. return false;
  15763. if (sphereCenter.z - sphereRadius > boxMax.z)
  15764. return false;
  15765. return true;
  15766. };
  15767. var getLowestRoot = (function () {
  15768. var result = { root: 0, found: false };
  15769. return function (a, b, c, maxR) {
  15770. result.root = 0;
  15771. result.found = false;
  15772. var determinant = b * b - 4.0 * a * c;
  15773. if (determinant < 0)
  15774. return result;
  15775. var sqrtD = Math.sqrt(determinant);
  15776. var r1 = (-b - sqrtD) / (2.0 * a);
  15777. var r2 = (-b + sqrtD) / (2.0 * a);
  15778. if (r1 > r2) {
  15779. var temp = r2;
  15780. r2 = r1;
  15781. r1 = temp;
  15782. }
  15783. if (r1 > 0 && r1 < maxR) {
  15784. result.root = r1;
  15785. result.found = true;
  15786. return result;
  15787. }
  15788. if (r2 > 0 && r2 < maxR) {
  15789. result.root = r2;
  15790. result.found = true;
  15791. return result;
  15792. }
  15793. return result;
  15794. };
  15795. })();
  15796. var Collider = (function () {
  15797. function Collider() {
  15798. this.radius = new BABYLON.Vector3(1, 1, 1);
  15799. this.retry = 0;
  15800. this.basePointWorld = BABYLON.Vector3.Zero();
  15801. this.velocityWorld = BABYLON.Vector3.Zero();
  15802. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15803. this._collisionPoint = BABYLON.Vector3.Zero();
  15804. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15805. this._tempVector = BABYLON.Vector3.Zero();
  15806. this._tempVector2 = BABYLON.Vector3.Zero();
  15807. this._tempVector3 = BABYLON.Vector3.Zero();
  15808. this._tempVector4 = BABYLON.Vector3.Zero();
  15809. this._edge = BABYLON.Vector3.Zero();
  15810. this._baseToVertex = BABYLON.Vector3.Zero();
  15811. this._destinationPoint = BABYLON.Vector3.Zero();
  15812. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15813. this._displacementVector = BABYLON.Vector3.Zero();
  15814. this._collisionMask = -1;
  15815. }
  15816. Object.defineProperty(Collider.prototype, "collisionMask", {
  15817. get: function () {
  15818. return this._collisionMask;
  15819. },
  15820. set: function (mask) {
  15821. this._collisionMask = !isNaN(mask) ? mask : -1;
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. // Methods
  15827. Collider.prototype._initialize = function (source, dir, e) {
  15828. this.velocity = dir;
  15829. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15830. this.basePoint = source;
  15831. source.multiplyToRef(this.radius, this.basePointWorld);
  15832. dir.multiplyToRef(this.radius, this.velocityWorld);
  15833. this.velocityWorldLength = this.velocityWorld.length();
  15834. this.epsilon = e;
  15835. this.collisionFound = false;
  15836. };
  15837. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15838. pa.subtractToRef(point, this._tempVector);
  15839. pb.subtractToRef(point, this._tempVector2);
  15840. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15841. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15842. if (d < 0)
  15843. return false;
  15844. pc.subtractToRef(point, this._tempVector3);
  15845. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15846. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15847. if (d < 0)
  15848. return false;
  15849. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15850. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15851. return d >= 0;
  15852. };
  15853. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15854. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15855. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15856. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15857. return false;
  15858. }
  15859. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15860. return false;
  15861. return true;
  15862. };
  15863. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15864. var t0;
  15865. var embeddedInPlane = false;
  15866. //defensive programming, actually not needed.
  15867. if (!trianglePlaneArray) {
  15868. trianglePlaneArray = [];
  15869. }
  15870. if (!trianglePlaneArray[faceIndex]) {
  15871. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15872. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15873. }
  15874. var trianglePlane = trianglePlaneArray[faceIndex];
  15875. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15876. return;
  15877. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15878. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15879. if (normalDotVelocity == 0) {
  15880. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15881. return;
  15882. embeddedInPlane = true;
  15883. t0 = 0;
  15884. }
  15885. else {
  15886. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15887. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15888. if (t0 > t1) {
  15889. var temp = t1;
  15890. t1 = t0;
  15891. t0 = temp;
  15892. }
  15893. if (t0 > 1.0 || t1 < 0.0)
  15894. return;
  15895. if (t0 < 0)
  15896. t0 = 0;
  15897. if (t0 > 1.0)
  15898. t0 = 1.0;
  15899. }
  15900. this._collisionPoint.copyFromFloats(0, 0, 0);
  15901. var found = false;
  15902. var t = 1.0;
  15903. if (!embeddedInPlane) {
  15904. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15905. this.velocity.scaleToRef(t0, this._tempVector);
  15906. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15907. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15908. found = true;
  15909. t = t0;
  15910. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15911. }
  15912. }
  15913. if (!found) {
  15914. var velocitySquaredLength = this.velocity.lengthSquared();
  15915. var a = velocitySquaredLength;
  15916. this.basePoint.subtractToRef(p1, this._tempVector);
  15917. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15918. var c = this._tempVector.lengthSquared() - 1.0;
  15919. var lowestRoot = getLowestRoot(a, b, c, t);
  15920. if (lowestRoot.found) {
  15921. t = lowestRoot.root;
  15922. found = true;
  15923. this._collisionPoint.copyFrom(p1);
  15924. }
  15925. this.basePoint.subtractToRef(p2, this._tempVector);
  15926. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15927. c = this._tempVector.lengthSquared() - 1.0;
  15928. lowestRoot = getLowestRoot(a, b, c, t);
  15929. if (lowestRoot.found) {
  15930. t = lowestRoot.root;
  15931. found = true;
  15932. this._collisionPoint.copyFrom(p2);
  15933. }
  15934. this.basePoint.subtractToRef(p3, this._tempVector);
  15935. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15936. c = this._tempVector.lengthSquared() - 1.0;
  15937. lowestRoot = getLowestRoot(a, b, c, t);
  15938. if (lowestRoot.found) {
  15939. t = lowestRoot.root;
  15940. found = true;
  15941. this._collisionPoint.copyFrom(p3);
  15942. }
  15943. p2.subtractToRef(p1, this._edge);
  15944. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15945. var edgeSquaredLength = this._edge.lengthSquared();
  15946. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15947. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15948. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15949. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15950. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15951. lowestRoot = getLowestRoot(a, b, c, t);
  15952. if (lowestRoot.found) {
  15953. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15954. if (f >= 0.0 && f <= 1.0) {
  15955. t = lowestRoot.root;
  15956. found = true;
  15957. this._edge.scaleInPlace(f);
  15958. p1.addToRef(this._edge, this._collisionPoint);
  15959. }
  15960. }
  15961. p3.subtractToRef(p2, this._edge);
  15962. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15963. edgeSquaredLength = this._edge.lengthSquared();
  15964. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15965. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15966. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15967. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15968. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15969. lowestRoot = getLowestRoot(a, b, c, t);
  15970. if (lowestRoot.found) {
  15971. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15972. if (f >= 0.0 && f <= 1.0) {
  15973. t = lowestRoot.root;
  15974. found = true;
  15975. this._edge.scaleInPlace(f);
  15976. p2.addToRef(this._edge, this._collisionPoint);
  15977. }
  15978. }
  15979. p1.subtractToRef(p3, this._edge);
  15980. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15981. edgeSquaredLength = this._edge.lengthSquared();
  15982. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15983. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15984. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15985. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15986. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15987. lowestRoot = getLowestRoot(a, b, c, t);
  15988. if (lowestRoot.found) {
  15989. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15990. if (f >= 0.0 && f <= 1.0) {
  15991. t = lowestRoot.root;
  15992. found = true;
  15993. this._edge.scaleInPlace(f);
  15994. p3.addToRef(this._edge, this._collisionPoint);
  15995. }
  15996. }
  15997. }
  15998. if (found) {
  15999. var distToCollision = t * this.velocity.length();
  16000. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  16001. if (!this.intersectionPoint) {
  16002. this.intersectionPoint = this._collisionPoint.clone();
  16003. }
  16004. else {
  16005. this.intersectionPoint.copyFrom(this._collisionPoint);
  16006. }
  16007. this.nearestDistance = distToCollision;
  16008. this.collisionFound = true;
  16009. }
  16010. }
  16011. };
  16012. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  16013. for (var i = indexStart; i < indexEnd; i += 3) {
  16014. var p1 = pts[indices[i] - decal];
  16015. var p2 = pts[indices[i + 1] - decal];
  16016. var p3 = pts[indices[i + 2] - decal];
  16017. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  16018. }
  16019. };
  16020. Collider.prototype._getResponse = function (pos, vel) {
  16021. pos.addToRef(vel, this._destinationPoint);
  16022. vel.scaleInPlace((this.nearestDistance / vel.length()));
  16023. this.basePoint.addToRef(vel, pos);
  16024. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  16025. this._slidePlaneNormal.normalize();
  16026. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  16027. pos.addInPlace(this._displacementVector);
  16028. this.intersectionPoint.addInPlace(this._displacementVector);
  16029. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  16030. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  16031. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  16032. };
  16033. return Collider;
  16034. }());
  16035. BABYLON.Collider = Collider;
  16036. })(BABYLON || (BABYLON = {}));
  16037. //# sourceMappingURL=babylon.collider.js.map
  16038. var BABYLON;
  16039. (function (BABYLON) {
  16040. //WebWorker code will be inserted to this variable.
  16041. BABYLON.CollisionWorker = "";
  16042. var WorkerTaskType;
  16043. (function (WorkerTaskType) {
  16044. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  16045. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  16046. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  16047. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  16048. var WorkerReplyType;
  16049. (function (WorkerReplyType) {
  16050. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  16051. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  16052. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  16053. var CollisionCoordinatorWorker = (function () {
  16054. function CollisionCoordinatorWorker() {
  16055. var _this = this;
  16056. this._scaledPosition = BABYLON.Vector3.Zero();
  16057. this._scaledVelocity = BABYLON.Vector3.Zero();
  16058. this.onMeshUpdated = function (mesh) {
  16059. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  16060. };
  16061. this.onGeometryUpdated = function (geometry) {
  16062. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  16063. };
  16064. this._afterRender = function () {
  16065. if (!_this._init)
  16066. return;
  16067. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  16068. return;
  16069. }
  16070. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  16071. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  16072. if (_this._runningUpdated > 4) {
  16073. return;
  16074. }
  16075. ++_this._runningUpdated;
  16076. var payload = {
  16077. updatedMeshes: _this._addUpdateMeshesList,
  16078. updatedGeometries: _this._addUpdateGeometriesList,
  16079. removedGeometries: _this._toRemoveGeometryArray,
  16080. removedMeshes: _this._toRemoveMeshesArray
  16081. };
  16082. var message = {
  16083. payload: payload,
  16084. taskType: WorkerTaskType.UPDATE
  16085. };
  16086. var serializable = [];
  16087. for (var id in payload.updatedGeometries) {
  16088. if (payload.updatedGeometries.hasOwnProperty(id)) {
  16089. //prepare transferables
  16090. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  16091. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  16092. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  16093. }
  16094. }
  16095. _this._worker.postMessage(message, serializable);
  16096. _this._addUpdateMeshesList = {};
  16097. _this._addUpdateGeometriesList = {};
  16098. _this._toRemoveGeometryArray = [];
  16099. _this._toRemoveMeshesArray = [];
  16100. };
  16101. this._onMessageFromWorker = function (e) {
  16102. var returnData = e.data;
  16103. if (returnData.error != WorkerReplyType.SUCCESS) {
  16104. //TODO what errors can be returned from the worker?
  16105. BABYLON.Tools.Warn("error returned from worker!");
  16106. return;
  16107. }
  16108. switch (returnData.taskType) {
  16109. case WorkerTaskType.INIT:
  16110. _this._init = true;
  16111. //Update the worked with ALL of the scene's current state
  16112. _this._scene.meshes.forEach(function (mesh) {
  16113. _this.onMeshAdded(mesh);
  16114. });
  16115. _this._scene.getGeometries().forEach(function (geometry) {
  16116. _this.onGeometryAdded(geometry);
  16117. });
  16118. break;
  16119. case WorkerTaskType.UPDATE:
  16120. _this._runningUpdated--;
  16121. break;
  16122. case WorkerTaskType.COLLIDE:
  16123. _this._runningCollisionTask = false;
  16124. var returnPayload = returnData.payload;
  16125. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  16126. return;
  16127. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  16128. //cleanup
  16129. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  16130. break;
  16131. }
  16132. };
  16133. this._collisionsCallbackArray = [];
  16134. this._init = false;
  16135. this._runningUpdated = 0;
  16136. this._runningCollisionTask = false;
  16137. this._addUpdateMeshesList = {};
  16138. this._addUpdateGeometriesList = {};
  16139. this._toRemoveGeometryArray = [];
  16140. this._toRemoveMeshesArray = [];
  16141. }
  16142. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  16143. if (!this._init)
  16144. return;
  16145. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  16146. return;
  16147. position.divideToRef(collider.radius, this._scaledPosition);
  16148. velocity.divideToRef(collider.radius, this._scaledVelocity);
  16149. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  16150. var payload = {
  16151. collider: {
  16152. position: this._scaledPosition.asArray(),
  16153. velocity: this._scaledVelocity.asArray(),
  16154. radius: collider.radius.asArray()
  16155. },
  16156. collisionId: collisionIndex,
  16157. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  16158. maximumRetry: maximumRetry
  16159. };
  16160. var message = {
  16161. payload: payload,
  16162. taskType: WorkerTaskType.COLLIDE
  16163. };
  16164. this._worker.postMessage(message);
  16165. };
  16166. CollisionCoordinatorWorker.prototype.init = function (scene) {
  16167. this._scene = scene;
  16168. this._scene.registerAfterRender(this._afterRender);
  16169. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  16170. this._worker = new Worker(workerUrl);
  16171. this._worker.onmessage = this._onMessageFromWorker;
  16172. var message = {
  16173. payload: {},
  16174. taskType: WorkerTaskType.INIT
  16175. };
  16176. this._worker.postMessage(message);
  16177. };
  16178. CollisionCoordinatorWorker.prototype.destroy = function () {
  16179. this._scene.unregisterAfterRender(this._afterRender);
  16180. this._worker.terminate();
  16181. };
  16182. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  16183. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  16184. this.onMeshUpdated(mesh);
  16185. };
  16186. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  16187. this._toRemoveMeshesArray.push(mesh.uniqueId);
  16188. };
  16189. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  16190. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  16191. geometry.onGeometryUpdated = this.onGeometryUpdated;
  16192. this.onGeometryUpdated(geometry);
  16193. };
  16194. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  16195. this._toRemoveGeometryArray.push(geometry.id);
  16196. };
  16197. return CollisionCoordinatorWorker;
  16198. }());
  16199. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  16200. var submeshes = [];
  16201. if (mesh.subMeshes) {
  16202. submeshes = mesh.subMeshes.map(function (sm, idx) {
  16203. return {
  16204. position: idx,
  16205. verticesStart: sm.verticesStart,
  16206. verticesCount: sm.verticesCount,
  16207. indexStart: sm.indexStart,
  16208. indexCount: sm.indexCount,
  16209. hasMaterial: !!sm.getMaterial(),
  16210. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  16211. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  16212. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  16213. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  16214. };
  16215. });
  16216. }
  16217. var geometryId = null;
  16218. if (mesh instanceof BABYLON.Mesh) {
  16219. geometryId = mesh.geometry ? mesh.geometry.id : null;
  16220. }
  16221. else if (mesh instanceof BABYLON.InstancedMesh) {
  16222. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  16223. }
  16224. return {
  16225. uniqueId: mesh.uniqueId,
  16226. id: mesh.id,
  16227. name: mesh.name,
  16228. geometryId: geometryId,
  16229. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  16230. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  16231. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  16232. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  16233. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  16234. subMeshes: submeshes,
  16235. checkCollisions: mesh.checkCollisions
  16236. };
  16237. };
  16238. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  16239. return {
  16240. id: geometry.id,
  16241. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  16242. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  16243. indices: new Uint32Array(geometry.getIndices() || []),
  16244. };
  16245. };
  16246. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  16247. var CollisionCoordinatorLegacy = (function () {
  16248. function CollisionCoordinatorLegacy() {
  16249. this._scaledPosition = BABYLON.Vector3.Zero();
  16250. this._scaledVelocity = BABYLON.Vector3.Zero();
  16251. this._finalPosition = BABYLON.Vector3.Zero();
  16252. }
  16253. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  16254. position.divideToRef(collider.radius, this._scaledPosition);
  16255. velocity.divideToRef(collider.radius, this._scaledVelocity);
  16256. collider.collidedMesh = null;
  16257. collider.retry = 0;
  16258. collider.initialVelocity = this._scaledVelocity;
  16259. collider.initialPosition = this._scaledPosition;
  16260. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  16261. this._finalPosition.multiplyInPlace(collider.radius);
  16262. //run the callback
  16263. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  16264. };
  16265. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  16266. this._scene = scene;
  16267. };
  16268. CollisionCoordinatorLegacy.prototype.destroy = function () {
  16269. //Legacy need no destruction method.
  16270. };
  16271. //No update in legacy mode
  16272. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  16273. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  16274. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  16275. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  16276. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  16277. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  16278. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  16279. if (excludedMesh === void 0) { excludedMesh = null; }
  16280. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  16281. if (collider.retry >= maximumRetry) {
  16282. finalPosition.copyFrom(position);
  16283. return;
  16284. }
  16285. // Check if this is a mesh else camera or -1
  16286. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  16287. collider._initialize(position, velocity, closeDistance);
  16288. // Check all meshes
  16289. for (var index = 0; index < this._scene.meshes.length; index++) {
  16290. var mesh = this._scene.meshes[index];
  16291. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  16292. mesh._checkCollision(collider);
  16293. }
  16294. }
  16295. if (!collider.collisionFound) {
  16296. position.addToRef(velocity, finalPosition);
  16297. return;
  16298. }
  16299. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  16300. collider._getResponse(position, velocity);
  16301. }
  16302. if (velocity.length() <= closeDistance) {
  16303. finalPosition.copyFrom(position);
  16304. return;
  16305. }
  16306. collider.retry++;
  16307. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  16308. };
  16309. return CollisionCoordinatorLegacy;
  16310. }());
  16311. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  16312. })(BABYLON || (BABYLON = {}));
  16313. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  16314. var BABYLON;
  16315. (function (BABYLON) {
  16316. var Camera = (function (_super) {
  16317. __extends(Camera, _super);
  16318. function Camera(name, position, scene) {
  16319. var _this = _super.call(this, name, scene) || this;
  16320. _this.upVector = BABYLON.Vector3.Up();
  16321. _this.orthoLeft = null;
  16322. _this.orthoRight = null;
  16323. _this.orthoBottom = null;
  16324. _this.orthoTop = null;
  16325. _this.fov = 0.8;
  16326. _this.minZ = 1.0;
  16327. _this.maxZ = 10000.0;
  16328. _this.inertia = 0.9;
  16329. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16330. _this.isIntermediate = false;
  16331. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16332. _this.layerMask = 0x0FFFFFFF;
  16333. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16334. // Camera rig members
  16335. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16336. _this._rigCameras = new Array();
  16337. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16338. // Cache
  16339. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16340. _this._projectionMatrix = new BABYLON.Matrix();
  16341. _this._doNotComputeProjectionMatrix = false;
  16342. _this._postProcesses = new Array();
  16343. _this._transformMatrix = BABYLON.Matrix.Zero();
  16344. _this._activeMeshes = new BABYLON.SmartArray(256);
  16345. _this._globalPosition = BABYLON.Vector3.Zero();
  16346. _this._refreshFrustumPlanes = true;
  16347. _this.getScene().addCamera(_this);
  16348. if (!_this.getScene().activeCamera) {
  16349. _this.getScene().activeCamera = _this;
  16350. }
  16351. _this.position = position;
  16352. return _this;
  16353. }
  16354. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16355. get: function () {
  16356. return Camera._PERSPECTIVE_CAMERA;
  16357. },
  16358. enumerable: true,
  16359. configurable: true
  16360. });
  16361. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16362. get: function () {
  16363. return Camera._ORTHOGRAPHIC_CAMERA;
  16364. },
  16365. enumerable: true,
  16366. configurable: true
  16367. });
  16368. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16369. get: function () {
  16370. return Camera._FOVMODE_VERTICAL_FIXED;
  16371. },
  16372. enumerable: true,
  16373. configurable: true
  16374. });
  16375. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16376. get: function () {
  16377. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16383. get: function () {
  16384. return Camera._RIG_MODE_NONE;
  16385. },
  16386. enumerable: true,
  16387. configurable: true
  16388. });
  16389. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16390. get: function () {
  16391. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16392. },
  16393. enumerable: true,
  16394. configurable: true
  16395. });
  16396. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16397. get: function () {
  16398. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16399. },
  16400. enumerable: true,
  16401. configurable: true
  16402. });
  16403. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16404. get: function () {
  16405. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16406. },
  16407. enumerable: true,
  16408. configurable: true
  16409. });
  16410. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16411. get: function () {
  16412. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16413. },
  16414. enumerable: true,
  16415. configurable: true
  16416. });
  16417. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16418. get: function () {
  16419. return Camera._RIG_MODE_VR;
  16420. },
  16421. enumerable: true,
  16422. configurable: true
  16423. });
  16424. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16425. get: function () {
  16426. return Camera._RIG_MODE_WEBVR;
  16427. },
  16428. enumerable: true,
  16429. configurable: true
  16430. });
  16431. Camera.prototype.getClassName = function () {
  16432. return "Camera";
  16433. };
  16434. /**
  16435. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16436. */
  16437. Camera.prototype.toString = function (fullDetails) {
  16438. var ret = "Name: " + this.name;
  16439. ret += ", type: " + this.getClassName();
  16440. if (this.animations) {
  16441. for (var i = 0; i < this.animations.length; i++) {
  16442. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16443. }
  16444. }
  16445. if (fullDetails) {
  16446. }
  16447. return ret;
  16448. };
  16449. Object.defineProperty(Camera.prototype, "globalPosition", {
  16450. get: function () {
  16451. return this._globalPosition;
  16452. },
  16453. enumerable: true,
  16454. configurable: true
  16455. });
  16456. Camera.prototype.getActiveMeshes = function () {
  16457. return this._activeMeshes;
  16458. };
  16459. Camera.prototype.isActiveMesh = function (mesh) {
  16460. return (this._activeMeshes.indexOf(mesh) !== -1);
  16461. };
  16462. //Cache
  16463. Camera.prototype._initCache = function () {
  16464. _super.prototype._initCache.call(this);
  16465. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16466. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16467. this._cache.mode = undefined;
  16468. this._cache.minZ = undefined;
  16469. this._cache.maxZ = undefined;
  16470. this._cache.fov = undefined;
  16471. this._cache.fovMode = undefined;
  16472. this._cache.aspectRatio = undefined;
  16473. this._cache.orthoLeft = undefined;
  16474. this._cache.orthoRight = undefined;
  16475. this._cache.orthoBottom = undefined;
  16476. this._cache.orthoTop = undefined;
  16477. this._cache.renderWidth = undefined;
  16478. this._cache.renderHeight = undefined;
  16479. };
  16480. Camera.prototype._updateCache = function (ignoreParentClass) {
  16481. if (!ignoreParentClass) {
  16482. _super.prototype._updateCache.call(this);
  16483. }
  16484. var engine = this.getEngine();
  16485. this._cache.position.copyFrom(this.position);
  16486. this._cache.upVector.copyFrom(this.upVector);
  16487. this._cache.mode = this.mode;
  16488. this._cache.minZ = this.minZ;
  16489. this._cache.maxZ = this.maxZ;
  16490. this._cache.fov = this.fov;
  16491. this._cache.fovMode = this.fovMode;
  16492. this._cache.aspectRatio = engine.getAspectRatio(this);
  16493. this._cache.orthoLeft = this.orthoLeft;
  16494. this._cache.orthoRight = this.orthoRight;
  16495. this._cache.orthoBottom = this.orthoBottom;
  16496. this._cache.orthoTop = this.orthoTop;
  16497. this._cache.renderWidth = engine.getRenderWidth();
  16498. this._cache.renderHeight = engine.getRenderHeight();
  16499. };
  16500. Camera.prototype._updateFromScene = function () {
  16501. this.updateCache();
  16502. this.update();
  16503. };
  16504. // Synchronized
  16505. Camera.prototype._isSynchronized = function () {
  16506. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16507. };
  16508. Camera.prototype._isSynchronizedViewMatrix = function () {
  16509. if (!_super.prototype._isSynchronized.call(this))
  16510. return false;
  16511. return this._cache.position.equals(this.position)
  16512. && this._cache.upVector.equals(this.upVector)
  16513. && this.isSynchronizedWithParent();
  16514. };
  16515. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16516. var check = this._cache.mode === this.mode
  16517. && this._cache.minZ === this.minZ
  16518. && this._cache.maxZ === this.maxZ;
  16519. if (!check) {
  16520. return false;
  16521. }
  16522. var engine = this.getEngine();
  16523. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16524. check = this._cache.fov === this.fov
  16525. && this._cache.fovMode === this.fovMode
  16526. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16527. }
  16528. else {
  16529. check = this._cache.orthoLeft === this.orthoLeft
  16530. && this._cache.orthoRight === this.orthoRight
  16531. && this._cache.orthoBottom === this.orthoBottom
  16532. && this._cache.orthoTop === this.orthoTop
  16533. && this._cache.renderWidth === engine.getRenderWidth()
  16534. && this._cache.renderHeight === engine.getRenderHeight();
  16535. }
  16536. return check;
  16537. };
  16538. // Controls
  16539. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16540. };
  16541. Camera.prototype.detachControl = function (element) {
  16542. };
  16543. Camera.prototype.update = function () {
  16544. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16545. this._updateRigCameras();
  16546. }
  16547. this._checkInputs();
  16548. };
  16549. Camera.prototype._checkInputs = function () {
  16550. };
  16551. Object.defineProperty(Camera.prototype, "rigCameras", {
  16552. get: function () {
  16553. return this._rigCameras;
  16554. },
  16555. enumerable: true,
  16556. configurable: true
  16557. });
  16558. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16559. get: function () {
  16560. return this._rigPostProcess;
  16561. },
  16562. enumerable: true,
  16563. configurable: true
  16564. });
  16565. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16566. // invalidate framebuffer
  16567. if (this._postProcesses.length > 0) {
  16568. this._postProcesses[0].markTextureDirty();
  16569. }
  16570. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16571. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16572. var cam = this._rigCameras[i];
  16573. var rigPostProcess = cam._rigPostProcess;
  16574. // for VR rig, there does not have to be a post process
  16575. if (rigPostProcess) {
  16576. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16577. if (isPass) {
  16578. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16579. cam.isIntermediate = this._postProcesses.length === 0;
  16580. }
  16581. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16582. rigPostProcess.markTextureDirty();
  16583. }
  16584. else {
  16585. cam._postProcesses = this._postProcesses.slice(0);
  16586. }
  16587. }
  16588. };
  16589. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16590. if (insertAt === void 0) { insertAt = null; }
  16591. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16592. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16593. return 0;
  16594. }
  16595. if (insertAt == null || insertAt < 0) {
  16596. this._postProcesses.push(postProcess);
  16597. }
  16598. else {
  16599. this._postProcesses.splice(insertAt, 0, postProcess);
  16600. }
  16601. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16602. return this._postProcesses.indexOf(postProcess);
  16603. };
  16604. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  16605. if (atIndices === void 0) { atIndices = null; }
  16606. var result = [];
  16607. var i;
  16608. var index;
  16609. if (!atIndices) {
  16610. var idx = this._postProcesses.indexOf(postProcess);
  16611. if (idx !== -1) {
  16612. this._postProcesses.splice(idx, 1);
  16613. }
  16614. }
  16615. else {
  16616. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  16617. // iterate descending, so can just splice as we go
  16618. for (i = atIndices.length - 1; i >= 0; i--) {
  16619. if (this._postProcesses[atIndices[i]] !== postProcess) {
  16620. result.push(i);
  16621. continue;
  16622. }
  16623. index = atIndices[i];
  16624. this._postProcesses.splice(index, 1);
  16625. }
  16626. }
  16627. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16628. return result;
  16629. };
  16630. Camera.prototype.getWorldMatrix = function () {
  16631. if (!this._worldMatrix) {
  16632. this._worldMatrix = BABYLON.Matrix.Identity();
  16633. }
  16634. var viewMatrix = this.getViewMatrix();
  16635. viewMatrix.invertToRef(this._worldMatrix);
  16636. return this._worldMatrix;
  16637. };
  16638. Camera.prototype._getViewMatrix = function () {
  16639. return BABYLON.Matrix.Identity();
  16640. };
  16641. Camera.prototype.getViewMatrix = function (force) {
  16642. this._computedViewMatrix = this._computeViewMatrix(force);
  16643. if (!force && this._isSynchronizedViewMatrix()) {
  16644. return this._computedViewMatrix;
  16645. }
  16646. this._refreshFrustumPlanes = true;
  16647. if (!this.parent || !this.parent.getWorldMatrix) {
  16648. this._globalPosition.copyFrom(this.position);
  16649. }
  16650. else {
  16651. if (!this._worldMatrix) {
  16652. this._worldMatrix = BABYLON.Matrix.Identity();
  16653. }
  16654. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16655. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16656. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16657. this._computedViewMatrix.invert();
  16658. this._markSyncedWithParent();
  16659. }
  16660. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16661. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16662. }
  16663. this._currentRenderId = this.getScene().getRenderId();
  16664. return this._computedViewMatrix;
  16665. };
  16666. Camera.prototype._computeViewMatrix = function (force) {
  16667. if (!force && this._isSynchronizedViewMatrix()) {
  16668. return this._computedViewMatrix;
  16669. }
  16670. this._computedViewMatrix = this._getViewMatrix();
  16671. this._currentRenderId = this.getScene().getRenderId();
  16672. return this._computedViewMatrix;
  16673. };
  16674. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16675. this._doNotComputeProjectionMatrix = true;
  16676. if (projection !== undefined) {
  16677. this._projectionMatrix = projection;
  16678. }
  16679. };
  16680. ;
  16681. Camera.prototype.unfreezeProjectionMatrix = function () {
  16682. this._doNotComputeProjectionMatrix = false;
  16683. };
  16684. ;
  16685. Camera.prototype.getProjectionMatrix = function (force) {
  16686. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16687. return this._projectionMatrix;
  16688. }
  16689. this._refreshFrustumPlanes = true;
  16690. var engine = this.getEngine();
  16691. var scene = this.getScene();
  16692. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16693. if (this.minZ <= 0) {
  16694. this.minZ = 0.1;
  16695. }
  16696. if (scene.useRightHandedSystem) {
  16697. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16698. }
  16699. else {
  16700. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16701. }
  16702. return this._projectionMatrix;
  16703. }
  16704. var halfWidth = engine.getRenderWidth() / 2.0;
  16705. var halfHeight = engine.getRenderHeight() / 2.0;
  16706. if (scene.useRightHandedSystem) {
  16707. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16708. }
  16709. else {
  16710. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16711. }
  16712. return this._projectionMatrix;
  16713. };
  16714. Camera.prototype.getTranformationMatrix = function () {
  16715. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16716. return this._transformMatrix;
  16717. };
  16718. Camera.prototype.updateFrustumPlanes = function () {
  16719. if (!this._refreshFrustumPlanes) {
  16720. return;
  16721. }
  16722. this.getTranformationMatrix();
  16723. if (!this._frustumPlanes) {
  16724. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16725. }
  16726. else {
  16727. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16728. }
  16729. this._refreshFrustumPlanes = false;
  16730. };
  16731. Camera.prototype.isInFrustum = function (target) {
  16732. this.updateFrustumPlanes();
  16733. return target.isInFrustum(this._frustumPlanes);
  16734. };
  16735. Camera.prototype.isCompletelyInFrustum = function (target) {
  16736. this.updateFrustumPlanes();
  16737. return target.isCompletelyInFrustum(this._frustumPlanes);
  16738. };
  16739. Camera.prototype.dispose = function () {
  16740. // Animations
  16741. this.getScene().stopAnimation(this);
  16742. // Remove from scene
  16743. this.getScene().removeCamera(this);
  16744. while (this._rigCameras.length > 0) {
  16745. this._rigCameras.pop().dispose();
  16746. }
  16747. // Postprocesses
  16748. var i = this._postProcesses.length;
  16749. while (--i >= 0) {
  16750. this._postProcesses[i].dispose(this);
  16751. }
  16752. _super.prototype.dispose.call(this);
  16753. };
  16754. // ---- Camera rigs section ----
  16755. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16756. while (this._rigCameras.length > 0) {
  16757. this._rigCameras.pop().dispose();
  16758. }
  16759. this.cameraRigMode = mode;
  16760. this._cameraRigParams = {};
  16761. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16762. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16763. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16764. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16765. // create the rig cameras, unless none
  16766. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16767. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16768. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16769. }
  16770. switch (this.cameraRigMode) {
  16771. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16772. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16773. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16774. break;
  16775. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16776. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16777. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16778. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16779. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16780. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16781. break;
  16782. case Camera.RIG_MODE_VR:
  16783. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16784. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16785. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16786. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16787. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16788. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16789. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16790. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16791. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16792. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16793. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16794. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16795. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16796. if (metrics.compensateDistortion) {
  16797. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16798. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16799. }
  16800. break;
  16801. case Camera.RIG_MODE_WEBVR:
  16802. if (rigParams.vrDisplay) {
  16803. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16804. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16805. //Left eye
  16806. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16807. this._rigCameras[0].setCameraRigParameter("left", true);
  16808. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16809. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16810. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16811. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16812. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16813. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16814. this._rigCameras[0].parent = this;
  16815. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16816. //Right eye
  16817. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16818. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16819. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16820. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16821. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16822. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16823. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16824. this._rigCameras[1].parent = this;
  16825. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16826. }
  16827. break;
  16828. }
  16829. this._cascadePostProcessesToRigCams();
  16830. this.
  16831. update();
  16832. };
  16833. Camera.prototype._getVRProjectionMatrix = function () {
  16834. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16835. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16836. return this._projectionMatrix;
  16837. };
  16838. Camera.prototype._updateCameraRotationMatrix = function () {
  16839. //Here for WebVR
  16840. };
  16841. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16842. //Here for WebVR
  16843. };
  16844. /**
  16845. * This function MUST be overwritten by the different WebVR cameras available.
  16846. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16847. */
  16848. Camera.prototype._getWebVRProjectionMatrix = function () {
  16849. return BABYLON.Matrix.Identity();
  16850. };
  16851. /**
  16852. * This function MUST be overwritten by the different WebVR cameras available.
  16853. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16854. */
  16855. Camera.prototype._getWebVRViewMatrix = function () {
  16856. return BABYLON.Matrix.Identity();
  16857. };
  16858. Camera.prototype.setCameraRigParameter = function (name, value) {
  16859. if (!this._cameraRigParams) {
  16860. this._cameraRigParams = {};
  16861. }
  16862. this._cameraRigParams[name] = value;
  16863. //provisionnally:
  16864. if (name === "interaxialDistance") {
  16865. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16866. }
  16867. };
  16868. /**
  16869. * needs to be overridden by children so sub has required properties to be copied
  16870. */
  16871. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16872. return null;
  16873. };
  16874. /**
  16875. * May need to be overridden by children
  16876. */
  16877. Camera.prototype._updateRigCameras = function () {
  16878. for (var i = 0; i < this._rigCameras.length; i++) {
  16879. this._rigCameras[i].minZ = this.minZ;
  16880. this._rigCameras[i].maxZ = this.maxZ;
  16881. this._rigCameras[i].fov = this.fov;
  16882. }
  16883. // only update viewport when ANAGLYPH
  16884. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16885. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16886. }
  16887. };
  16888. Camera.prototype._setupInputs = function () {
  16889. };
  16890. Camera.prototype.serialize = function () {
  16891. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16892. // Type
  16893. serializationObject.type = this.getClassName();
  16894. // Parent
  16895. if (this.parent) {
  16896. serializationObject.parentId = this.parent.id;
  16897. }
  16898. if (this.inputs) {
  16899. this.inputs.serialize(serializationObject);
  16900. }
  16901. // Animations
  16902. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16903. serializationObject.ranges = this.serializeAnimationRanges();
  16904. return serializationObject;
  16905. };
  16906. Camera.prototype.clone = function (name) {
  16907. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16908. };
  16909. Camera.prototype.getDirection = function (localAxis) {
  16910. var result = BABYLON.Vector3.Zero();
  16911. this.getDirectionToRef(localAxis, result);
  16912. return result;
  16913. };
  16914. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16915. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16916. };
  16917. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16918. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16919. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16920. switch (type) {
  16921. case "ArcRotateCamera":
  16922. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16923. case "DeviceOrientationCamera":
  16924. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16925. case "FollowCamera":
  16926. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16927. case "ArcFollowCamera":
  16928. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16929. case "GamepadCamera":
  16930. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16931. case "TouchCamera":
  16932. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16933. case "VirtualJoysticksCamera":
  16934. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16935. case "WebVRFreeCamera":
  16936. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16937. case "WebVRGamepadCamera":
  16938. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16939. case "VRDeviceOrientationFreeCamera":
  16940. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16941. case "VRDeviceOrientationGamepadCamera":
  16942. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16943. case "AnaglyphArcRotateCamera":
  16944. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16945. case "AnaglyphFreeCamera":
  16946. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16947. case "AnaglyphGamepadCamera":
  16948. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16949. case "AnaglyphUniversalCamera":
  16950. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16951. case "StereoscopicArcRotateCamera":
  16952. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16953. case "StereoscopicFreeCamera":
  16954. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16955. case "StereoscopicGamepadCamera":
  16956. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16957. case "StereoscopicUniversalCamera":
  16958. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16959. case "FreeCamera":
  16960. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16961. default:
  16962. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16963. }
  16964. };
  16965. Camera.Parse = function (parsedCamera, scene) {
  16966. var type = parsedCamera.type;
  16967. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16968. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16969. // Parent
  16970. if (parsedCamera.parentId) {
  16971. camera._waitingParentId = parsedCamera.parentId;
  16972. }
  16973. //If camera has an input manager, let it parse inputs settings
  16974. if (camera.inputs) {
  16975. camera.inputs.parse(parsedCamera);
  16976. camera._setupInputs();
  16977. }
  16978. // Target
  16979. if (parsedCamera.target) {
  16980. if (camera.setTarget) {
  16981. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16982. }
  16983. }
  16984. // Apply 3d rig, when found
  16985. if (parsedCamera.cameraRigMode) {
  16986. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16987. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16988. }
  16989. // Animations
  16990. if (parsedCamera.animations) {
  16991. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16992. var parsedAnimation = parsedCamera.animations[animationIndex];
  16993. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16994. }
  16995. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16996. }
  16997. if (parsedCamera.autoAnimate) {
  16998. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16999. }
  17000. return camera;
  17001. };
  17002. return Camera;
  17003. }(BABYLON.Node));
  17004. // Statics
  17005. Camera._PERSPECTIVE_CAMERA = 0;
  17006. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17007. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17008. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17009. Camera._RIG_MODE_NONE = 0;
  17010. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17011. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17012. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17013. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17014. Camera._RIG_MODE_VR = 20;
  17015. Camera._RIG_MODE_WEBVR = 21;
  17016. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17017. __decorate([
  17018. BABYLON.serializeAsVector3()
  17019. ], Camera.prototype, "position", void 0);
  17020. __decorate([
  17021. BABYLON.serializeAsVector3()
  17022. ], Camera.prototype, "upVector", void 0);
  17023. __decorate([
  17024. BABYLON.serialize()
  17025. ], Camera.prototype, "orthoLeft", void 0);
  17026. __decorate([
  17027. BABYLON.serialize()
  17028. ], Camera.prototype, "orthoRight", void 0);
  17029. __decorate([
  17030. BABYLON.serialize()
  17031. ], Camera.prototype, "orthoBottom", void 0);
  17032. __decorate([
  17033. BABYLON.serialize()
  17034. ], Camera.prototype, "orthoTop", void 0);
  17035. __decorate([
  17036. BABYLON.serialize()
  17037. ], Camera.prototype, "fov", void 0);
  17038. __decorate([
  17039. BABYLON.serialize()
  17040. ], Camera.prototype, "minZ", void 0);
  17041. __decorate([
  17042. BABYLON.serialize()
  17043. ], Camera.prototype, "maxZ", void 0);
  17044. __decorate([
  17045. BABYLON.serialize()
  17046. ], Camera.prototype, "inertia", void 0);
  17047. __decorate([
  17048. BABYLON.serialize()
  17049. ], Camera.prototype, "mode", void 0);
  17050. __decorate([
  17051. BABYLON.serialize()
  17052. ], Camera.prototype, "layerMask", void 0);
  17053. __decorate([
  17054. BABYLON.serialize()
  17055. ], Camera.prototype, "fovMode", void 0);
  17056. __decorate([
  17057. BABYLON.serialize()
  17058. ], Camera.prototype, "cameraRigMode", void 0);
  17059. __decorate([
  17060. BABYLON.serialize()
  17061. ], Camera.prototype, "interaxialDistance", void 0);
  17062. __decorate([
  17063. BABYLON.serialize()
  17064. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17065. BABYLON.Camera = Camera;
  17066. })(BABYLON || (BABYLON = {}));
  17067. //# sourceMappingURL=babylon.camera.js.map
  17068. var BABYLON;
  17069. (function (BABYLON) {
  17070. BABYLON.CameraInputTypes = {};
  17071. var CameraInputsManager = (function () {
  17072. function CameraInputsManager(camera) {
  17073. this.attached = {};
  17074. this.camera = camera;
  17075. this.checkInputs = function () { };
  17076. }
  17077. CameraInputsManager.prototype.add = function (input) {
  17078. var type = input.getSimpleName();
  17079. if (this.attached[type]) {
  17080. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  17081. return;
  17082. }
  17083. this.attached[type] = input;
  17084. input.camera = this.camera;
  17085. //for checkInputs, we are dynamically creating a function
  17086. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  17087. if (input.checkInputs) {
  17088. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  17089. }
  17090. if (this.attachedElement) {
  17091. input.attachControl(this.attachedElement);
  17092. }
  17093. };
  17094. CameraInputsManager.prototype.remove = function (inputToRemove) {
  17095. for (var cam in this.attached) {
  17096. var input = this.attached[cam];
  17097. if (input === inputToRemove) {
  17098. input.detachControl(this.attachedElement);
  17099. delete this.attached[cam];
  17100. this.rebuildInputCheck();
  17101. }
  17102. }
  17103. };
  17104. CameraInputsManager.prototype.removeByType = function (inputType) {
  17105. for (var cam in this.attached) {
  17106. var input = this.attached[cam];
  17107. if (input.getTypeName() === inputType) {
  17108. input.detachControl(this.attachedElement);
  17109. delete this.attached[cam];
  17110. this.rebuildInputCheck();
  17111. }
  17112. }
  17113. };
  17114. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  17115. var current = this.checkInputs;
  17116. return function () {
  17117. current();
  17118. fn();
  17119. };
  17120. };
  17121. CameraInputsManager.prototype.attachInput = function (input) {
  17122. input.attachControl(this.attachedElement, this.noPreventDefault);
  17123. };
  17124. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  17125. if (this.attachedElement) {
  17126. return;
  17127. }
  17128. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  17129. this.attachedElement = element;
  17130. this.noPreventDefault = noPreventDefault;
  17131. for (var cam in this.attached) {
  17132. var input = this.attached[cam];
  17133. this.attached[cam].attachControl(element, noPreventDefault);
  17134. }
  17135. };
  17136. CameraInputsManager.prototype.detachElement = function (element) {
  17137. if (this.attachedElement !== element) {
  17138. return;
  17139. }
  17140. for (var cam in this.attached) {
  17141. var input = this.attached[cam];
  17142. this.attached[cam].detachControl(element);
  17143. }
  17144. this.attachedElement = null;
  17145. };
  17146. CameraInputsManager.prototype.rebuildInputCheck = function () {
  17147. this.checkInputs = function () { };
  17148. for (var cam in this.attached) {
  17149. var input = this.attached[cam];
  17150. if (input.checkInputs) {
  17151. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  17152. }
  17153. }
  17154. };
  17155. CameraInputsManager.prototype.clear = function () {
  17156. if (this.attachedElement) {
  17157. this.detachElement(this.attachedElement);
  17158. }
  17159. this.attached = {};
  17160. this.attachedElement = null;
  17161. this.checkInputs = function () { };
  17162. };
  17163. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  17164. var inputs = {};
  17165. for (var cam in this.attached) {
  17166. var input = this.attached[cam];
  17167. var res = BABYLON.SerializationHelper.Serialize(input);
  17168. inputs[input.getTypeName()] = res;
  17169. }
  17170. serializedCamera.inputsmgr = inputs;
  17171. };
  17172. CameraInputsManager.prototype.parse = function (parsedCamera) {
  17173. var parsedInputs = parsedCamera.inputsmgr;
  17174. if (parsedInputs) {
  17175. this.clear();
  17176. for (var n in parsedInputs) {
  17177. var construct = BABYLON.CameraInputTypes[n];
  17178. if (construct) {
  17179. var parsedinput = parsedInputs[n];
  17180. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  17181. this.add(input);
  17182. }
  17183. }
  17184. }
  17185. else {
  17186. //2016-03-08 this part is for managing backward compatibility
  17187. for (var n in this.attached) {
  17188. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  17189. if (construct) {
  17190. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  17191. this.remove(this.attached[n]);
  17192. this.add(input);
  17193. }
  17194. }
  17195. }
  17196. };
  17197. return CameraInputsManager;
  17198. }());
  17199. BABYLON.CameraInputsManager = CameraInputsManager;
  17200. })(BABYLON || (BABYLON = {}));
  17201. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  17202. var BABYLON;
  17203. (function (BABYLON) {
  17204. var FreeCameraMouseInput = (function () {
  17205. function FreeCameraMouseInput(touchEnabled) {
  17206. if (touchEnabled === void 0) { touchEnabled = true; }
  17207. this.touchEnabled = touchEnabled;
  17208. this.buttons = [0, 1, 2];
  17209. this.angularSensibility = 2000.0;
  17210. }
  17211. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  17212. var _this = this;
  17213. var engine = this.camera.getEngine();
  17214. if (!this._pointerInput) {
  17215. this._pointerInput = function (p, s) {
  17216. var evt = p.event;
  17217. if (!_this.touchEnabled && evt.pointerType === "touch") {
  17218. return;
  17219. }
  17220. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17221. return;
  17222. }
  17223. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17224. try {
  17225. evt.srcElement.setPointerCapture(evt.pointerId);
  17226. }
  17227. catch (e) {
  17228. //Nothing to do with the error. Execution will continue.
  17229. }
  17230. _this.previousPosition = {
  17231. x: evt.clientX,
  17232. y: evt.clientY
  17233. };
  17234. if (!noPreventDefault) {
  17235. evt.preventDefault();
  17236. element.focus();
  17237. }
  17238. }
  17239. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17240. try {
  17241. evt.srcElement.releasePointerCapture(evt.pointerId);
  17242. }
  17243. catch (e) {
  17244. //Nothing to do with the error.
  17245. }
  17246. _this.previousPosition = null;
  17247. if (!noPreventDefault) {
  17248. evt.preventDefault();
  17249. }
  17250. }
  17251. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17252. if (!_this.previousPosition || engine.isPointerLock) {
  17253. return;
  17254. }
  17255. var offsetX = evt.clientX - _this.previousPosition.x;
  17256. var offsetY = evt.clientY - _this.previousPosition.y;
  17257. if (_this.camera.getScene().useRightHandedSystem) {
  17258. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  17259. }
  17260. else {
  17261. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  17262. }
  17263. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  17264. _this.previousPosition = {
  17265. x: evt.clientX,
  17266. y: evt.clientY
  17267. };
  17268. if (!noPreventDefault) {
  17269. evt.preventDefault();
  17270. }
  17271. }
  17272. };
  17273. }
  17274. this._onMouseMove = function (evt) {
  17275. if (!engine.isPointerLock) {
  17276. return;
  17277. }
  17278. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17279. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17280. if (_this.camera.getScene().useRightHandedSystem) {
  17281. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  17282. }
  17283. else {
  17284. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  17285. }
  17286. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  17287. _this.previousPosition = null;
  17288. if (!noPreventDefault) {
  17289. evt.preventDefault();
  17290. }
  17291. };
  17292. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17293. element.addEventListener("mousemove", this._onMouseMove, false);
  17294. };
  17295. FreeCameraMouseInput.prototype.detachControl = function (element) {
  17296. if (this._observer && element) {
  17297. this.camera.getScene().onPointerObservable.remove(this._observer);
  17298. element.removeEventListener("mousemove", this._onMouseMove);
  17299. this._observer = null;
  17300. this._onMouseMove = null;
  17301. this.previousPosition = null;
  17302. }
  17303. };
  17304. FreeCameraMouseInput.prototype.getTypeName = function () {
  17305. return "FreeCameraMouseInput";
  17306. };
  17307. FreeCameraMouseInput.prototype.getSimpleName = function () {
  17308. return "mouse";
  17309. };
  17310. return FreeCameraMouseInput;
  17311. }());
  17312. __decorate([
  17313. BABYLON.serialize()
  17314. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  17315. __decorate([
  17316. BABYLON.serialize()
  17317. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  17318. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  17319. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  17320. })(BABYLON || (BABYLON = {}));
  17321. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  17322. var BABYLON;
  17323. (function (BABYLON) {
  17324. var FreeCameraKeyboardMoveInput = (function () {
  17325. function FreeCameraKeyboardMoveInput() {
  17326. this._keys = [];
  17327. this.keysUp = [38];
  17328. this.keysDown = [40];
  17329. this.keysLeft = [37];
  17330. this.keysRight = [39];
  17331. }
  17332. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17333. var _this = this;
  17334. if (!this._onKeyDown) {
  17335. element.tabIndex = 1;
  17336. this._onKeyDown = function (evt) {
  17337. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17338. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17339. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17340. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17341. var index = _this._keys.indexOf(evt.keyCode);
  17342. if (index === -1) {
  17343. _this._keys.push(evt.keyCode);
  17344. }
  17345. if (!noPreventDefault) {
  17346. evt.preventDefault();
  17347. }
  17348. }
  17349. };
  17350. this._onKeyUp = function (evt) {
  17351. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17352. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17353. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17354. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17355. var index = _this._keys.indexOf(evt.keyCode);
  17356. if (index >= 0) {
  17357. _this._keys.splice(index, 1);
  17358. }
  17359. if (!noPreventDefault) {
  17360. evt.preventDefault();
  17361. }
  17362. }
  17363. };
  17364. element.addEventListener("keydown", this._onKeyDown, false);
  17365. element.addEventListener("keyup", this._onKeyUp, false);
  17366. BABYLON.Tools.RegisterTopRootEvents([
  17367. { name: "blur", handler: this._onLostFocus }
  17368. ]);
  17369. }
  17370. };
  17371. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17372. if (this._onKeyDown) {
  17373. element.removeEventListener("keydown", this._onKeyDown);
  17374. element.removeEventListener("keyup", this._onKeyUp);
  17375. BABYLON.Tools.UnregisterTopRootEvents([
  17376. { name: "blur", handler: this._onLostFocus }
  17377. ]);
  17378. this._keys = [];
  17379. this._onKeyDown = null;
  17380. this._onKeyUp = null;
  17381. }
  17382. };
  17383. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17384. if (this._onKeyDown) {
  17385. var camera = this.camera;
  17386. // Keyboard
  17387. for (var index = 0; index < this._keys.length; index++) {
  17388. var keyCode = this._keys[index];
  17389. var speed = camera._computeLocalCameraSpeed();
  17390. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17391. camera._localDirection.copyFromFloats(-speed, 0, 0);
  17392. }
  17393. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17394. camera._localDirection.copyFromFloats(0, 0, speed);
  17395. }
  17396. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17397. camera._localDirection.copyFromFloats(speed, 0, 0);
  17398. }
  17399. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17400. camera._localDirection.copyFromFloats(0, 0, -speed);
  17401. }
  17402. if (camera.getScene().useRightHandedSystem) {
  17403. camera._localDirection.z *= -1;
  17404. }
  17405. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  17406. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  17407. camera.cameraDirection.addInPlace(camera._transformedDirection);
  17408. }
  17409. }
  17410. };
  17411. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17412. return "FreeCameraKeyboardMoveInput";
  17413. };
  17414. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  17415. this._keys = [];
  17416. };
  17417. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17418. return "keyboard";
  17419. };
  17420. return FreeCameraKeyboardMoveInput;
  17421. }());
  17422. __decorate([
  17423. BABYLON.serialize()
  17424. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17425. __decorate([
  17426. BABYLON.serialize()
  17427. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17428. __decorate([
  17429. BABYLON.serialize()
  17430. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17431. __decorate([
  17432. BABYLON.serialize()
  17433. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17434. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  17435. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  17436. })(BABYLON || (BABYLON = {}));
  17437. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  17438. var BABYLON;
  17439. (function (BABYLON) {
  17440. var FreeCameraTouchInput = (function () {
  17441. function FreeCameraTouchInput() {
  17442. this._offsetX = null;
  17443. this._offsetY = null;
  17444. this._pointerCount = 0;
  17445. this._pointerPressed = [];
  17446. this.touchAngularSensibility = 200000.0;
  17447. this.touchMoveSensibility = 250.0;
  17448. }
  17449. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  17450. var _this = this;
  17451. var previousPosition;
  17452. if (this._pointerInput === undefined) {
  17453. this._onLostFocus = function (evt) {
  17454. _this._offsetX = null;
  17455. _this._offsetY = null;
  17456. };
  17457. this._pointerInput = function (p, s) {
  17458. var evt = p.event;
  17459. if (evt.pointerType === "mouse") {
  17460. return;
  17461. }
  17462. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17463. if (!noPreventDefault) {
  17464. evt.preventDefault();
  17465. }
  17466. _this._pointerPressed.push(evt.pointerId);
  17467. if (_this._pointerPressed.length !== 1) {
  17468. return;
  17469. }
  17470. previousPosition = {
  17471. x: evt.clientX,
  17472. y: evt.clientY
  17473. };
  17474. }
  17475. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17476. if (!noPreventDefault) {
  17477. evt.preventDefault();
  17478. }
  17479. var index = _this._pointerPressed.indexOf(evt.pointerId);
  17480. if (index === -1) {
  17481. return;
  17482. }
  17483. _this._pointerPressed.splice(index, 1);
  17484. if (index != 0) {
  17485. return;
  17486. }
  17487. previousPosition = null;
  17488. _this._offsetX = null;
  17489. _this._offsetY = null;
  17490. }
  17491. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17492. if (!noPreventDefault) {
  17493. evt.preventDefault();
  17494. }
  17495. if (!previousPosition) {
  17496. return;
  17497. }
  17498. var index = _this._pointerPressed.indexOf(evt.pointerId);
  17499. if (index != 0) {
  17500. return;
  17501. }
  17502. _this._offsetX = evt.clientX - previousPosition.x;
  17503. _this._offsetY = -(evt.clientY - previousPosition.y);
  17504. }
  17505. };
  17506. }
  17507. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17508. element.addEventListener("blur", this._onLostFocus);
  17509. };
  17510. FreeCameraTouchInput.prototype.detachControl = function (element) {
  17511. if (this._pointerInput && element) {
  17512. this.camera.getScene().onPointerObservable.remove(this._observer);
  17513. this._observer = null;
  17514. element.removeEventListener("blur", this._onLostFocus);
  17515. this._onLostFocus = null;
  17516. this._pointerPressed = [];
  17517. this._offsetX = null;
  17518. this._offsetY = null;
  17519. this._pointerCount = 0;
  17520. }
  17521. };
  17522. FreeCameraTouchInput.prototype.checkInputs = function () {
  17523. if (this._offsetX) {
  17524. var camera = this.camera;
  17525. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  17526. if (this._pointerPressed.length > 1) {
  17527. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  17528. }
  17529. else {
  17530. var speed = camera._computeLocalCameraSpeed();
  17531. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  17532. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  17533. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  17534. }
  17535. }
  17536. };
  17537. FreeCameraTouchInput.prototype.getTypeName = function () {
  17538. return "FreeCameraTouchInput";
  17539. };
  17540. FreeCameraTouchInput.prototype.getSimpleName = function () {
  17541. return "touch";
  17542. };
  17543. return FreeCameraTouchInput;
  17544. }());
  17545. __decorate([
  17546. BABYLON.serialize()
  17547. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  17548. __decorate([
  17549. BABYLON.serialize()
  17550. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  17551. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  17552. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  17553. })(BABYLON || (BABYLON = {}));
  17554. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  17555. var BABYLON;
  17556. (function (BABYLON) {
  17557. var FreeCameraDeviceOrientationInput = (function () {
  17558. function FreeCameraDeviceOrientationInput() {
  17559. var _this = this;
  17560. this._screenOrientationAngle = 0;
  17561. this._screenQuaternion = new BABYLON.Quaternion();
  17562. this._alpha = 0;
  17563. this._beta = 0;
  17564. this._gamma = 0;
  17565. this._orientationChanged = function () {
  17566. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  17567. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  17568. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  17569. };
  17570. this._deviceOrientation = function (evt) {
  17571. _this._alpha = evt.alpha;
  17572. _this._beta = evt.beta;
  17573. _this._gamma = evt.gamma;
  17574. };
  17575. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  17576. this._orientationChanged();
  17577. }
  17578. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  17579. get: function () {
  17580. return this._camera;
  17581. },
  17582. set: function (camera) {
  17583. this._camera = camera;
  17584. if (!this._camera.rotationQuaternion)
  17585. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17591. window.addEventListener("orientationchange", this._orientationChanged);
  17592. window.addEventListener("deviceorientation", this._deviceOrientation);
  17593. //In certain cases, the attach control is called AFTER orientation was changed,
  17594. //So this is needed.
  17595. this._orientationChanged();
  17596. };
  17597. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  17598. window.removeEventListener("orientationchange", this._orientationChanged);
  17599. window.removeEventListener("deviceorientation", this._deviceOrientation);
  17600. };
  17601. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  17602. //if no device orientation provided, don't update the rotation.
  17603. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  17604. if (!this._alpha)
  17605. return;
  17606. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  17607. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  17608. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  17609. //Mirror on XY Plane
  17610. this._camera.rotationQuaternion.z *= -1;
  17611. this._camera.rotationQuaternion.w *= -1;
  17612. };
  17613. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  17614. return "FreeCameraDeviceOrientationInput";
  17615. };
  17616. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  17617. return "deviceOrientation";
  17618. };
  17619. return FreeCameraDeviceOrientationInput;
  17620. }());
  17621. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  17622. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  17623. })(BABYLON || (BABYLON = {}));
  17624. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  17625. var BABYLON;
  17626. (function (BABYLON) {
  17627. var FreeCameraGamepadInput = (function () {
  17628. function FreeCameraGamepadInput() {
  17629. this.gamepadAngularSensibility = 200;
  17630. this.gamepadMoveSensibility = 40;
  17631. // private members
  17632. this._cameraTransform = BABYLON.Matrix.Identity();
  17633. this._deltaTransform = BABYLON.Vector3.Zero();
  17634. this._vector3 = BABYLON.Vector3.Zero();
  17635. this._vector2 = BABYLON.Vector2.Zero();
  17636. }
  17637. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17638. var _this = this;
  17639. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17640. };
  17641. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  17642. if (this._gamepads) {
  17643. this._gamepads.dispose();
  17644. }
  17645. this.gamepad = null;
  17646. };
  17647. FreeCameraGamepadInput.prototype.checkInputs = function () {
  17648. if (this.gamepad && this.gamepad.leftStick) {
  17649. var camera = this.camera;
  17650. var LSValues = this.gamepad.leftStick;
  17651. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  17652. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17653. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17654. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17655. var RSValues = this.gamepad.rightStick;
  17656. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  17657. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  17658. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  17659. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  17660. if (!camera.rotationQuaternion) {
  17661. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  17662. }
  17663. else {
  17664. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  17665. }
  17666. var speed = camera._computeLocalCameraSpeed() * 50.0;
  17667. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  17668. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  17669. camera.cameraDirection.addInPlace(this._deltaTransform);
  17670. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  17671. camera.cameraRotation.addInPlace(this._vector2);
  17672. }
  17673. };
  17674. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17675. // Only the first gamepad found can control the camera
  17676. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17677. // prioritize XBOX gamepads.
  17678. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17679. this.gamepad = gamepad;
  17680. }
  17681. }
  17682. };
  17683. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17684. return "FreeCameraGamepadInput";
  17685. };
  17686. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17687. return "gamepad";
  17688. };
  17689. return FreeCameraGamepadInput;
  17690. }());
  17691. __decorate([
  17692. BABYLON.serialize()
  17693. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17694. __decorate([
  17695. BABYLON.serialize()
  17696. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17697. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17698. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17699. })(BABYLON || (BABYLON = {}));
  17700. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  17701. var BABYLON;
  17702. (function (BABYLON) {
  17703. var ArcRotateCameraKeyboardMoveInput = (function () {
  17704. function ArcRotateCameraKeyboardMoveInput() {
  17705. this._keys = [];
  17706. this.keysUp = [38];
  17707. this.keysDown = [40];
  17708. this.keysLeft = [37];
  17709. this.keysRight = [39];
  17710. }
  17711. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17712. var _this = this;
  17713. element.tabIndex = 1;
  17714. this._onKeyDown = function (evt) {
  17715. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17716. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17717. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17718. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17719. var index = _this._keys.indexOf(evt.keyCode);
  17720. if (index === -1) {
  17721. _this._keys.push(evt.keyCode);
  17722. }
  17723. if (evt.preventDefault) {
  17724. if (!noPreventDefault) {
  17725. evt.preventDefault();
  17726. }
  17727. }
  17728. }
  17729. };
  17730. this._onKeyUp = function (evt) {
  17731. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17732. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17733. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17734. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17735. var index = _this._keys.indexOf(evt.keyCode);
  17736. if (index >= 0) {
  17737. _this._keys.splice(index, 1);
  17738. }
  17739. if (evt.preventDefault) {
  17740. if (!noPreventDefault) {
  17741. evt.preventDefault();
  17742. }
  17743. }
  17744. }
  17745. };
  17746. this._onLostFocus = function () {
  17747. _this._keys = [];
  17748. };
  17749. element.addEventListener("keydown", this._onKeyDown, false);
  17750. element.addEventListener("keyup", this._onKeyUp, false);
  17751. BABYLON.Tools.RegisterTopRootEvents([
  17752. { name: "blur", handler: this._onLostFocus }
  17753. ]);
  17754. };
  17755. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17756. if (element) {
  17757. element.removeEventListener("keydown", this._onKeyDown);
  17758. element.removeEventListener("keyup", this._onKeyUp);
  17759. }
  17760. BABYLON.Tools.UnregisterTopRootEvents([
  17761. { name: "blur", handler: this._onLostFocus }
  17762. ]);
  17763. this._keys = [];
  17764. this._onKeyDown = null;
  17765. this._onKeyUp = null;
  17766. this._onLostFocus = null;
  17767. };
  17768. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17769. if (this._onKeyDown) {
  17770. var camera = this.camera;
  17771. for (var index = 0; index < this._keys.length; index++) {
  17772. var keyCode = this._keys[index];
  17773. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17774. camera.inertialAlphaOffset -= 0.01;
  17775. }
  17776. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17777. camera.inertialBetaOffset -= 0.01;
  17778. }
  17779. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17780. camera.inertialAlphaOffset += 0.01;
  17781. }
  17782. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17783. camera.inertialBetaOffset += 0.01;
  17784. }
  17785. }
  17786. }
  17787. };
  17788. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17789. return "ArcRotateCameraKeyboardMoveInput";
  17790. };
  17791. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17792. return "keyboard";
  17793. };
  17794. return ArcRotateCameraKeyboardMoveInput;
  17795. }());
  17796. __decorate([
  17797. BABYLON.serialize()
  17798. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17799. __decorate([
  17800. BABYLON.serialize()
  17801. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17802. __decorate([
  17803. BABYLON.serialize()
  17804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17805. __decorate([
  17806. BABYLON.serialize()
  17807. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17808. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17809. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17810. })(BABYLON || (BABYLON = {}));
  17811. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  17812. var BABYLON;
  17813. (function (BABYLON) {
  17814. var ArcRotateCameraMouseWheelInput = (function () {
  17815. function ArcRotateCameraMouseWheelInput() {
  17816. this.wheelPrecision = 3.0;
  17817. }
  17818. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17819. var _this = this;
  17820. this._wheel = function (p, s) {
  17821. //sanity check - this should be a PointerWheel event.
  17822. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17823. return;
  17824. var event = p.event;
  17825. var delta = 0;
  17826. if (event.wheelDelta) {
  17827. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17828. }
  17829. else if (event.detail) {
  17830. delta = -event.detail / _this.wheelPrecision;
  17831. }
  17832. if (delta)
  17833. _this.camera.inertialRadiusOffset += delta;
  17834. if (event.preventDefault) {
  17835. if (!noPreventDefault) {
  17836. event.preventDefault();
  17837. }
  17838. }
  17839. };
  17840. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17841. };
  17842. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17843. if (this._observer && element) {
  17844. this.camera.getScene().onPointerObservable.remove(this._observer);
  17845. this._observer = null;
  17846. this._wheel = null;
  17847. }
  17848. };
  17849. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17850. return "ArcRotateCameraMouseWheelInput";
  17851. };
  17852. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17853. return "mousewheel";
  17854. };
  17855. return ArcRotateCameraMouseWheelInput;
  17856. }());
  17857. __decorate([
  17858. BABYLON.serialize()
  17859. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17860. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17861. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17862. })(BABYLON || (BABYLON = {}));
  17863. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  17864. var BABYLON;
  17865. (function (BABYLON) {
  17866. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17867. var ArcRotateCameraPointersInput = (function () {
  17868. function ArcRotateCameraPointersInput() {
  17869. this.buttons = [0, 1, 2];
  17870. this.angularSensibilityX = 1000.0;
  17871. this.angularSensibilityY = 1000.0;
  17872. this.pinchPrecision = 6.0;
  17873. this.panningSensibility = 50.0;
  17874. this._isPanClick = false;
  17875. this.pinchInwards = true;
  17876. }
  17877. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17878. var _this = this;
  17879. var engine = this.camera.getEngine();
  17880. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17881. var pointA, pointB;
  17882. var previousPinchDistance = 0;
  17883. this._pointerInput = function (p, s) {
  17884. var evt = p.event;
  17885. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17886. return;
  17887. }
  17888. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17889. try {
  17890. evt.srcElement.setPointerCapture(evt.pointerId);
  17891. }
  17892. catch (e) {
  17893. //Nothing to do with the error. Execution will continue.
  17894. }
  17895. // Manage panning with pan button click
  17896. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17897. // manage pointers
  17898. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17899. if (pointA === undefined) {
  17900. pointA = cacheSoloPointer;
  17901. }
  17902. else if (pointB === undefined) {
  17903. pointB = cacheSoloPointer;
  17904. }
  17905. if (!noPreventDefault) {
  17906. evt.preventDefault();
  17907. element.focus();
  17908. }
  17909. }
  17910. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17911. try {
  17912. evt.srcElement.releasePointerCapture(evt.pointerId);
  17913. }
  17914. catch (e) {
  17915. //Nothing to do with the error.
  17916. }
  17917. cacheSoloPointer = null;
  17918. previousPinchDistance = 0;
  17919. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17920. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17921. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17922. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17923. pointA = pointB = undefined;
  17924. if (!noPreventDefault) {
  17925. evt.preventDefault();
  17926. }
  17927. }
  17928. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17929. if (!noPreventDefault) {
  17930. evt.preventDefault();
  17931. }
  17932. // One button down
  17933. if (pointA && pointB === undefined) {
  17934. if (_this.panningSensibility !== 0 &&
  17935. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17936. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17937. _this.camera
  17938. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17939. _this.camera
  17940. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17941. }
  17942. else {
  17943. var offsetX = evt.clientX - cacheSoloPointer.x;
  17944. var offsetY = evt.clientY - cacheSoloPointer.y;
  17945. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17946. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17947. }
  17948. cacheSoloPointer.x = evt.clientX;
  17949. cacheSoloPointer.y = evt.clientY;
  17950. }
  17951. else if (pointA && pointB) {
  17952. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17953. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17954. ed.x = evt.clientX;
  17955. ed.y = evt.clientY;
  17956. var direction = _this.pinchInwards ? 1 : -1;
  17957. var distX = pointA.x - pointB.x;
  17958. var distY = pointA.y - pointB.y;
  17959. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17960. if (previousPinchDistance === 0) {
  17961. previousPinchDistance = pinchSquaredDistance;
  17962. return;
  17963. }
  17964. if (pinchSquaredDistance !== previousPinchDistance) {
  17965. _this.camera
  17966. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17967. (_this.pinchPrecision *
  17968. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17969. direction);
  17970. previousPinchDistance = pinchSquaredDistance;
  17971. }
  17972. }
  17973. }
  17974. };
  17975. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17976. this._onContextMenu = function (evt) {
  17977. evt.preventDefault();
  17978. };
  17979. if (!this.camera._useCtrlForPanning) {
  17980. element.addEventListener("contextmenu", this._onContextMenu, false);
  17981. }
  17982. this._onLostFocus = function () {
  17983. //this._keys = [];
  17984. pointA = pointB = undefined;
  17985. previousPinchDistance = 0;
  17986. cacheSoloPointer = null;
  17987. };
  17988. this._onMouseMove = function (evt) {
  17989. if (!engine.isPointerLock) {
  17990. return;
  17991. }
  17992. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17993. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17994. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17995. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17996. if (!noPreventDefault) {
  17997. evt.preventDefault();
  17998. }
  17999. };
  18000. this._onGestureStart = function (e) {
  18001. if (window.MSGesture === undefined) {
  18002. return;
  18003. }
  18004. if (!_this._MSGestureHandler) {
  18005. _this._MSGestureHandler = new MSGesture();
  18006. _this._MSGestureHandler.target = element;
  18007. }
  18008. _this._MSGestureHandler.addPointer(e.pointerId);
  18009. };
  18010. this._onGesture = function (e) {
  18011. _this.camera.radius *= e.scale;
  18012. if (e.preventDefault) {
  18013. if (!noPreventDefault) {
  18014. e.stopPropagation();
  18015. e.preventDefault();
  18016. }
  18017. }
  18018. };
  18019. element.addEventListener("mousemove", this._onMouseMove, false);
  18020. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  18021. element.addEventListener("MSGestureChange", this._onGesture, false);
  18022. element.addEventListener("keydown", this._onKeyDown, false);
  18023. element.addEventListener("keyup", this._onKeyUp, false);
  18024. BABYLON.Tools.RegisterTopRootEvents([
  18025. { name: "blur", handler: this._onLostFocus }
  18026. ]);
  18027. };
  18028. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  18029. if (element && this._observer) {
  18030. this.camera.getScene().onPointerObservable.remove(this._observer);
  18031. this._observer = null;
  18032. element.removeEventListener("contextmenu", this._onContextMenu);
  18033. element.removeEventListener("mousemove", this._onMouseMove);
  18034. element.removeEventListener("MSPointerDown", this._onGestureStart);
  18035. element.removeEventListener("MSGestureChange", this._onGesture);
  18036. element.removeEventListener("keydown", this._onKeyDown);
  18037. element.removeEventListener("keyup", this._onKeyUp);
  18038. this._isPanClick = false;
  18039. this.pinchInwards = true;
  18040. this._onKeyDown = null;
  18041. this._onKeyUp = null;
  18042. this._onMouseMove = null;
  18043. this._onGestureStart = null;
  18044. this._onGesture = null;
  18045. this._MSGestureHandler = null;
  18046. this._onLostFocus = null;
  18047. this._onContextMenu = null;
  18048. }
  18049. BABYLON.Tools.UnregisterTopRootEvents([
  18050. { name: "blur", handler: this._onLostFocus }
  18051. ]);
  18052. };
  18053. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  18054. return "ArcRotateCameraPointersInput";
  18055. };
  18056. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  18057. return "pointers";
  18058. };
  18059. return ArcRotateCameraPointersInput;
  18060. }());
  18061. __decorate([
  18062. BABYLON.serialize()
  18063. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  18064. __decorate([
  18065. BABYLON.serialize()
  18066. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  18067. __decorate([
  18068. BABYLON.serialize()
  18069. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  18070. __decorate([
  18071. BABYLON.serialize()
  18072. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  18073. __decorate([
  18074. BABYLON.serialize()
  18075. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  18076. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  18077. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  18078. })(BABYLON || (BABYLON = {}));
  18079. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  18080. var BABYLON;
  18081. (function (BABYLON) {
  18082. var ArcRotateCameraGamepadInput = (function () {
  18083. function ArcRotateCameraGamepadInput() {
  18084. this.gamepadRotationSensibility = 80;
  18085. this.gamepadMoveSensibility = 40;
  18086. }
  18087. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  18088. var _this = this;
  18089. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  18090. };
  18091. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  18092. if (this._gamepads) {
  18093. this._gamepads.dispose();
  18094. }
  18095. this.gamepad = null;
  18096. };
  18097. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  18098. if (this.gamepad) {
  18099. var camera = this.camera;
  18100. var RSValues = this.gamepad.rightStick;
  18101. if (RSValues.x != 0) {
  18102. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  18103. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  18104. camera.inertialAlphaOffset += normalizedRX;
  18105. }
  18106. }
  18107. if (RSValues.y != 0) {
  18108. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  18109. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  18110. camera.inertialBetaOffset += normalizedRY;
  18111. }
  18112. }
  18113. var LSValues = this.gamepad.leftStick;
  18114. if (LSValues.y != 0) {
  18115. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  18116. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  18117. this.camera.inertialRadiusOffset -= normalizedLY;
  18118. }
  18119. }
  18120. }
  18121. };
  18122. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  18123. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  18124. // prioritize XBOX gamepads.
  18125. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  18126. this.gamepad = gamepad;
  18127. }
  18128. }
  18129. };
  18130. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  18131. return "ArcRotateCameraGamepadInput";
  18132. };
  18133. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  18134. return "gamepad";
  18135. };
  18136. return ArcRotateCameraGamepadInput;
  18137. }());
  18138. __decorate([
  18139. BABYLON.serialize()
  18140. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  18141. __decorate([
  18142. BABYLON.serialize()
  18143. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  18144. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  18145. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  18146. })(BABYLON || (BABYLON = {}));
  18147. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  18148. var BABYLON;
  18149. (function (BABYLON) {
  18150. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  18151. function ArcRotateCameraVRDeviceOrientationInput() {
  18152. this.alphaCorrection = 1;
  18153. this.betaCorrection = 1;
  18154. this.gammaCorrection = 1;
  18155. this._alpha = 0;
  18156. this._beta = 0;
  18157. this._gamma = 0;
  18158. this._dirty = false;
  18159. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18160. }
  18161. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  18162. this.camera.attachControl(element, noPreventDefault);
  18163. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18164. };
  18165. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  18166. var camera = this.camera;
  18167. this._alpha = +evt.alpha | 0;
  18168. this._beta = +evt.beta | 0;
  18169. this._gamma = +evt.gamma | 0;
  18170. this._dirty = true;
  18171. };
  18172. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  18173. if (this._dirty) {
  18174. this._dirty = false;
  18175. if (this._gamma < 0) {
  18176. this._gamma = 180 + this._gamma;
  18177. }
  18178. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  18179. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  18180. }
  18181. };
  18182. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  18183. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18184. };
  18185. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  18186. return "ArcRotateCameraVRDeviceOrientationInput";
  18187. };
  18188. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  18189. return "VRDeviceOrientation";
  18190. };
  18191. return ArcRotateCameraVRDeviceOrientationInput;
  18192. }());
  18193. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  18194. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  18195. })(BABYLON || (BABYLON = {}));
  18196. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  18197. /// <reference path="babylon.camera.ts" />
  18198. var BABYLON;
  18199. (function (BABYLON) {
  18200. var TargetCamera = (function (_super) {
  18201. __extends(TargetCamera, _super);
  18202. function TargetCamera(name, position, scene) {
  18203. var _this = _super.call(this, name, position, scene) || this;
  18204. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  18205. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  18206. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  18207. _this.speed = 2.0;
  18208. _this.noRotationConstraint = false;
  18209. _this.lockedTarget = null;
  18210. _this._currentTarget = BABYLON.Vector3.Zero();
  18211. _this._viewMatrix = BABYLON.Matrix.Zero();
  18212. _this._camMatrix = BABYLON.Matrix.Zero();
  18213. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  18214. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  18215. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  18216. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  18217. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  18218. _this._lookAtTemp = BABYLON.Matrix.Zero();
  18219. _this._tempMatrix = BABYLON.Matrix.Zero();
  18220. return _this;
  18221. }
  18222. TargetCamera.prototype.getFrontPosition = function (distance) {
  18223. var direction = this.getTarget().subtract(this.position);
  18224. direction.normalize();
  18225. direction.scaleInPlace(distance);
  18226. return this.globalPosition.add(direction);
  18227. };
  18228. TargetCamera.prototype._getLockedTargetPosition = function () {
  18229. if (!this.lockedTarget) {
  18230. return null;
  18231. }
  18232. if (this.lockedTarget.absolutePosition) {
  18233. this.lockedTarget.computeWorldMatrix();
  18234. }
  18235. return this.lockedTarget.absolutePosition || this.lockedTarget;
  18236. };
  18237. // Cache
  18238. TargetCamera.prototype._initCache = function () {
  18239. _super.prototype._initCache.call(this);
  18240. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18241. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18242. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18243. };
  18244. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  18245. if (!ignoreParentClass) {
  18246. _super.prototype._updateCache.call(this);
  18247. }
  18248. var lockedTargetPosition = this._getLockedTargetPosition();
  18249. if (!lockedTargetPosition) {
  18250. this._cache.lockedTarget = null;
  18251. }
  18252. else {
  18253. if (!this._cache.lockedTarget) {
  18254. this._cache.lockedTarget = lockedTargetPosition.clone();
  18255. }
  18256. else {
  18257. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  18258. }
  18259. }
  18260. this._cache.rotation.copyFrom(this.rotation);
  18261. if (this.rotationQuaternion)
  18262. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18263. };
  18264. // Synchronized
  18265. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  18266. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  18267. return false;
  18268. }
  18269. var lockedTargetPosition = this._getLockedTargetPosition();
  18270. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  18271. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  18272. };
  18273. // Methods
  18274. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  18275. var engine = this.getEngine();
  18276. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  18277. };
  18278. // Target
  18279. TargetCamera.prototype.setTarget = function (target) {
  18280. this.upVector.normalize();
  18281. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  18282. this._camMatrix.invert();
  18283. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  18284. var vDir = target.subtract(this.position);
  18285. if (vDir.x >= 0.0) {
  18286. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  18287. }
  18288. else {
  18289. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  18290. }
  18291. this.rotation.z = 0;
  18292. if (isNaN(this.rotation.x)) {
  18293. this.rotation.x = 0;
  18294. }
  18295. if (isNaN(this.rotation.y)) {
  18296. this.rotation.y = 0;
  18297. }
  18298. if (isNaN(this.rotation.z)) {
  18299. this.rotation.z = 0;
  18300. }
  18301. if (this.rotationQuaternion) {
  18302. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  18303. }
  18304. };
  18305. /**
  18306. * Return the current target position of the camera. This value is expressed in local space.
  18307. */
  18308. TargetCamera.prototype.getTarget = function () {
  18309. return this._currentTarget;
  18310. };
  18311. TargetCamera.prototype._decideIfNeedsToMove = function () {
  18312. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18313. };
  18314. TargetCamera.prototype._updatePosition = function () {
  18315. if (this.parent) {
  18316. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  18317. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  18318. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  18319. return;
  18320. }
  18321. this.position.addInPlace(this.cameraDirection);
  18322. };
  18323. TargetCamera.prototype._checkInputs = function () {
  18324. var needToMove = this._decideIfNeedsToMove();
  18325. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  18326. // Move
  18327. if (needToMove) {
  18328. this._updatePosition();
  18329. }
  18330. // Rotate
  18331. if (needToRotate) {
  18332. this.rotation.x += this.cameraRotation.x;
  18333. this.rotation.y += this.cameraRotation.y;
  18334. //rotate, if quaternion is set and rotation was used
  18335. if (this.rotationQuaternion) {
  18336. var len = this.rotation.lengthSquared();
  18337. if (len) {
  18338. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  18339. }
  18340. }
  18341. if (!this.noRotationConstraint) {
  18342. var limit = (Math.PI / 2) * 0.95;
  18343. if (this.rotation.x > limit)
  18344. this.rotation.x = limit;
  18345. if (this.rotation.x < -limit)
  18346. this.rotation.x = -limit;
  18347. }
  18348. }
  18349. // Inertia
  18350. if (needToMove) {
  18351. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  18352. this.cameraDirection.x = 0;
  18353. }
  18354. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  18355. this.cameraDirection.y = 0;
  18356. }
  18357. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  18358. this.cameraDirection.z = 0;
  18359. }
  18360. this.cameraDirection.scaleInPlace(this.inertia);
  18361. }
  18362. if (needToRotate) {
  18363. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  18364. this.cameraRotation.x = 0;
  18365. }
  18366. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  18367. this.cameraRotation.y = 0;
  18368. }
  18369. this.cameraRotation.scaleInPlace(this.inertia);
  18370. }
  18371. _super.prototype._checkInputs.call(this);
  18372. };
  18373. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  18374. if (this.rotationQuaternion) {
  18375. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  18376. //update the up vector!
  18377. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  18378. }
  18379. else {
  18380. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18381. }
  18382. };
  18383. TargetCamera.prototype._getViewMatrix = function () {
  18384. if (!this.lockedTarget) {
  18385. // Compute
  18386. this._updateCameraRotationMatrix();
  18387. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18388. // Computing target and final matrix
  18389. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18390. }
  18391. else {
  18392. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  18393. }
  18394. if (this.getScene().useRightHandedSystem) {
  18395. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  18396. }
  18397. else {
  18398. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  18399. }
  18400. return this._viewMatrix;
  18401. };
  18402. /**
  18403. * @override
  18404. * Override Camera.createRigCamera
  18405. */
  18406. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18407. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  18408. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  18409. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  18410. if (!this.rotationQuaternion) {
  18411. this.rotationQuaternion = new BABYLON.Quaternion();
  18412. }
  18413. rigCamera._cameraRigParams = {};
  18414. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  18415. }
  18416. return rigCamera;
  18417. }
  18418. return null;
  18419. };
  18420. /**
  18421. * @override
  18422. * Override Camera._updateRigCameras
  18423. */
  18424. TargetCamera.prototype._updateRigCameras = function () {
  18425. var camLeft = this._rigCameras[0];
  18426. var camRight = this._rigCameras[1];
  18427. switch (this.cameraRigMode) {
  18428. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18429. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18430. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18431. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18432. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  18433. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  18434. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  18435. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  18436. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  18437. camLeft.setTarget(this.getTarget());
  18438. camRight.setTarget(this.getTarget());
  18439. break;
  18440. case BABYLON.Camera.RIG_MODE_VR:
  18441. if (camLeft.rotationQuaternion) {
  18442. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18443. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18444. }
  18445. else {
  18446. camLeft.rotation.copyFrom(this.rotation);
  18447. camRight.rotation.copyFrom(this.rotation);
  18448. }
  18449. camLeft.position.copyFrom(this.position);
  18450. camRight.position.copyFrom(this.position);
  18451. break;
  18452. }
  18453. _super.prototype._updateRigCameras.call(this);
  18454. };
  18455. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  18456. if (!this._rigCamTransformMatrix) {
  18457. this._rigCamTransformMatrix = new BABYLON.Matrix();
  18458. }
  18459. var target = this.getTarget();
  18460. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  18461. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  18462. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  18463. };
  18464. TargetCamera.prototype.getClassName = function () {
  18465. return "TargetCamera";
  18466. };
  18467. return TargetCamera;
  18468. }(BABYLON.Camera));
  18469. __decorate([
  18470. BABYLON.serializeAsVector3()
  18471. ], TargetCamera.prototype, "rotation", void 0);
  18472. __decorate([
  18473. BABYLON.serialize()
  18474. ], TargetCamera.prototype, "speed", void 0);
  18475. __decorate([
  18476. BABYLON.serializeAsMeshReference("lockedTargetId")
  18477. ], TargetCamera.prototype, "lockedTarget", void 0);
  18478. BABYLON.TargetCamera = TargetCamera;
  18479. })(BABYLON || (BABYLON = {}));
  18480. //# sourceMappingURL=babylon.targetCamera.js.map
  18481. var BABYLON;
  18482. (function (BABYLON) {
  18483. var FreeCamera = (function (_super) {
  18484. __extends(FreeCamera, _super);
  18485. function FreeCamera(name, position, scene) {
  18486. var _this = _super.call(this, name, position, scene) || this;
  18487. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18488. _this.checkCollisions = false;
  18489. _this.applyGravity = false;
  18490. _this._collider = new BABYLON.Collider();
  18491. _this._needMoveForGravity = false;
  18492. _this._oldPosition = BABYLON.Vector3.Zero();
  18493. _this._diffPosition = BABYLON.Vector3.Zero();
  18494. _this._newPosition = BABYLON.Vector3.Zero();
  18495. // Collisions
  18496. _this._collisionMask = -1;
  18497. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18498. if (collidedMesh === void 0) { collidedMesh = null; }
  18499. //TODO move this to the collision coordinator!
  18500. if (_this.getScene().workerCollisions)
  18501. newPosition.multiplyInPlace(_this._collider.radius);
  18502. var updatePosition = function (newPos) {
  18503. _this._newPosition.copyFrom(newPos);
  18504. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  18505. var oldPosition = _this.position.clone();
  18506. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  18507. _this.position.addInPlace(_this._diffPosition);
  18508. if (_this.onCollide && collidedMesh) {
  18509. _this.onCollide(collidedMesh);
  18510. }
  18511. }
  18512. };
  18513. updatePosition(newPosition);
  18514. };
  18515. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  18516. _this.inputs.addKeyboard().addMouse();
  18517. return _this;
  18518. }
  18519. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  18520. //-- begin properties for backward compatibility for inputs
  18521. get: function () {
  18522. var mouse = this.inputs.attached["mouse"];
  18523. if (mouse)
  18524. return mouse.angularSensibility;
  18525. },
  18526. set: function (value) {
  18527. var mouse = this.inputs.attached["mouse"];
  18528. if (mouse)
  18529. mouse.angularSensibility = value;
  18530. },
  18531. enumerable: true,
  18532. configurable: true
  18533. });
  18534. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  18535. get: function () {
  18536. var keyboard = this.inputs.attached["keyboard"];
  18537. if (keyboard)
  18538. return keyboard.keysUp;
  18539. },
  18540. set: function (value) {
  18541. var keyboard = this.inputs.attached["keyboard"];
  18542. if (keyboard)
  18543. keyboard.keysUp = value;
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  18549. get: function () {
  18550. var keyboard = this.inputs.attached["keyboard"];
  18551. if (keyboard)
  18552. return keyboard.keysDown;
  18553. },
  18554. set: function (value) {
  18555. var keyboard = this.inputs.attached["keyboard"];
  18556. if (keyboard)
  18557. keyboard.keysDown = value;
  18558. },
  18559. enumerable: true,
  18560. configurable: true
  18561. });
  18562. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  18563. get: function () {
  18564. var keyboard = this.inputs.attached["keyboard"];
  18565. if (keyboard)
  18566. return keyboard.keysLeft;
  18567. },
  18568. set: function (value) {
  18569. var keyboard = this.inputs.attached["keyboard"];
  18570. if (keyboard)
  18571. keyboard.keysLeft = value;
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  18577. get: function () {
  18578. var keyboard = this.inputs.attached["keyboard"];
  18579. if (keyboard)
  18580. return keyboard.keysRight;
  18581. },
  18582. set: function (value) {
  18583. var keyboard = this.inputs.attached["keyboard"];
  18584. if (keyboard)
  18585. keyboard.keysRight = value;
  18586. },
  18587. enumerable: true,
  18588. configurable: true
  18589. });
  18590. // Controls
  18591. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  18592. this.inputs.attachElement(element, noPreventDefault);
  18593. };
  18594. FreeCamera.prototype.detachControl = function (element) {
  18595. this.inputs.detachElement(element);
  18596. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  18597. this.cameraRotation = new BABYLON.Vector2(0, 0);
  18598. };
  18599. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  18600. get: function () {
  18601. return this._collisionMask;
  18602. },
  18603. set: function (mask) {
  18604. this._collisionMask = !isNaN(mask) ? mask : -1;
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. FreeCamera.prototype._collideWithWorld = function (velocity) {
  18610. var globalPosition;
  18611. if (this.parent) {
  18612. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  18613. }
  18614. else {
  18615. globalPosition = this.position;
  18616. }
  18617. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  18618. this._collider.radius = this.ellipsoid;
  18619. this._collider.collisionMask = this._collisionMask;
  18620. //no need for clone, as long as gravity is not on.
  18621. var actualVelocity = velocity;
  18622. //add gravity to the velocity to prevent the dual-collision checking
  18623. if (this.applyGravity) {
  18624. //this prevents mending with cameraDirection, a global variable of the free camera class.
  18625. actualVelocity = velocity.add(this.getScene().gravity);
  18626. }
  18627. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18628. };
  18629. FreeCamera.prototype._checkInputs = function () {
  18630. if (!this._localDirection) {
  18631. this._localDirection = BABYLON.Vector3.Zero();
  18632. this._transformedDirection = BABYLON.Vector3.Zero();
  18633. }
  18634. this.inputs.checkInputs();
  18635. _super.prototype._checkInputs.call(this);
  18636. };
  18637. FreeCamera.prototype._decideIfNeedsToMove = function () {
  18638. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18639. };
  18640. FreeCamera.prototype._updatePosition = function () {
  18641. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  18642. this._collideWithWorld(this.cameraDirection);
  18643. }
  18644. else {
  18645. _super.prototype._updatePosition.call(this);
  18646. }
  18647. };
  18648. FreeCamera.prototype.dispose = function () {
  18649. this.inputs.clear();
  18650. _super.prototype.dispose.call(this);
  18651. };
  18652. FreeCamera.prototype.getClassName = function () {
  18653. return "FreeCamera";
  18654. };
  18655. return FreeCamera;
  18656. }(BABYLON.TargetCamera));
  18657. __decorate([
  18658. BABYLON.serializeAsVector3()
  18659. ], FreeCamera.prototype, "ellipsoid", void 0);
  18660. __decorate([
  18661. BABYLON.serialize()
  18662. ], FreeCamera.prototype, "checkCollisions", void 0);
  18663. __decorate([
  18664. BABYLON.serialize()
  18665. ], FreeCamera.prototype, "applyGravity", void 0);
  18666. BABYLON.FreeCamera = FreeCamera;
  18667. })(BABYLON || (BABYLON = {}));
  18668. //# sourceMappingURL=babylon.freeCamera.js.map
  18669. var BABYLON;
  18670. (function (BABYLON) {
  18671. var FreeCameraInputsManager = (function (_super) {
  18672. __extends(FreeCameraInputsManager, _super);
  18673. function FreeCameraInputsManager(camera) {
  18674. return _super.call(this, camera) || this;
  18675. }
  18676. FreeCameraInputsManager.prototype.addKeyboard = function () {
  18677. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18678. return this;
  18679. };
  18680. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18681. if (touchEnabled === void 0) { touchEnabled = true; }
  18682. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18683. return this;
  18684. };
  18685. FreeCameraInputsManager.prototype.addGamepad = function () {
  18686. this.add(new BABYLON.FreeCameraGamepadInput());
  18687. return this;
  18688. };
  18689. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18690. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18691. return this;
  18692. };
  18693. FreeCameraInputsManager.prototype.addTouch = function () {
  18694. this.add(new BABYLON.FreeCameraTouchInput());
  18695. return this;
  18696. };
  18697. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18698. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18699. return this;
  18700. };
  18701. return FreeCameraInputsManager;
  18702. }(BABYLON.CameraInputsManager));
  18703. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18704. })(BABYLON || (BABYLON = {}));
  18705. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18706. /// <reference path="babylon.targetCamera.ts" />
  18707. var BABYLON;
  18708. (function (BABYLON) {
  18709. var FollowCamera = (function (_super) {
  18710. __extends(FollowCamera, _super);
  18711. function FollowCamera(name, position, scene, lockedTarget) {
  18712. var _this = _super.call(this, name, position, scene) || this;
  18713. _this.radius = 12;
  18714. _this.rotationOffset = 0;
  18715. _this.heightOffset = 4;
  18716. _this.cameraAcceleration = 0.05;
  18717. _this.maxCameraSpeed = 20;
  18718. _this.lockedTarget = lockedTarget;
  18719. return _this;
  18720. }
  18721. FollowCamera.prototype.getRadians = function (degrees) {
  18722. return degrees * Math.PI / 180;
  18723. };
  18724. FollowCamera.prototype.follow = function (cameraTarget) {
  18725. if (!cameraTarget)
  18726. return;
  18727. var yRotation;
  18728. if (cameraTarget.rotationQuaternion) {
  18729. var rotMatrix = new BABYLON.Matrix();
  18730. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18731. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18732. }
  18733. else {
  18734. yRotation = cameraTarget.rotation.y;
  18735. }
  18736. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18737. var targetPosition = cameraTarget.getAbsolutePosition();
  18738. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18739. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18740. var dx = targetX - this.position.x;
  18741. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18742. var dz = (targetZ) - this.position.z;
  18743. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18744. var vy = dy * this.cameraAcceleration;
  18745. var vz = dz * this.cameraAcceleration * 2;
  18746. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18747. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18748. }
  18749. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18750. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18751. }
  18752. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18753. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18754. }
  18755. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18756. this.setTarget(targetPosition);
  18757. };
  18758. FollowCamera.prototype._checkInputs = function () {
  18759. _super.prototype._checkInputs.call(this);
  18760. this.follow(this.lockedTarget);
  18761. };
  18762. FollowCamera.prototype.getClassName = function () {
  18763. return "FollowCamera";
  18764. };
  18765. return FollowCamera;
  18766. }(BABYLON.TargetCamera));
  18767. __decorate([
  18768. BABYLON.serialize()
  18769. ], FollowCamera.prototype, "radius", void 0);
  18770. __decorate([
  18771. BABYLON.serialize()
  18772. ], FollowCamera.prototype, "rotationOffset", void 0);
  18773. __decorate([
  18774. BABYLON.serialize()
  18775. ], FollowCamera.prototype, "heightOffset", void 0);
  18776. __decorate([
  18777. BABYLON.serialize()
  18778. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18779. __decorate([
  18780. BABYLON.serialize()
  18781. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18782. __decorate([
  18783. BABYLON.serializeAsMeshReference("lockedTargetId")
  18784. ], FollowCamera.prototype, "lockedTarget", void 0);
  18785. BABYLON.FollowCamera = FollowCamera;
  18786. var ArcFollowCamera = (function (_super) {
  18787. __extends(ArcFollowCamera, _super);
  18788. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18789. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18790. _this.alpha = alpha;
  18791. _this.beta = beta;
  18792. _this.radius = radius;
  18793. _this.target = target;
  18794. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18795. _this.follow();
  18796. return _this;
  18797. }
  18798. ArcFollowCamera.prototype.follow = function () {
  18799. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18800. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18801. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18802. var targetPosition = this.target.getAbsolutePosition();
  18803. this.position = targetPosition.add(this._cartesianCoordinates);
  18804. this.setTarget(targetPosition);
  18805. };
  18806. ArcFollowCamera.prototype._checkInputs = function () {
  18807. _super.prototype._checkInputs.call(this);
  18808. this.follow();
  18809. };
  18810. ArcFollowCamera.prototype.getClassName = function () {
  18811. return "ArcFollowCamera";
  18812. };
  18813. return ArcFollowCamera;
  18814. }(BABYLON.TargetCamera));
  18815. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18816. })(BABYLON || (BABYLON = {}));
  18817. //# sourceMappingURL=babylon.followCamera.js.map
  18818. /// <reference path="babylon.freeCamera.ts" />
  18819. var BABYLON;
  18820. (function (BABYLON) {
  18821. // We're mainly based on the logic defined into the FreeCamera code
  18822. var TouchCamera = (function (_super) {
  18823. __extends(TouchCamera, _super);
  18824. //-- end properties for backward compatibility for inputs
  18825. function TouchCamera(name, position, scene) {
  18826. var _this = _super.call(this, name, position, scene) || this;
  18827. _this.inputs.addTouch();
  18828. _this._setupInputs();
  18829. return _this;
  18830. }
  18831. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18832. //-- Begin properties for backward compatibility for inputs
  18833. get: function () {
  18834. var touch = this.inputs.attached["touch"];
  18835. if (touch)
  18836. return touch.touchAngularSensibility;
  18837. },
  18838. set: function (value) {
  18839. var touch = this.inputs.attached["touch"];
  18840. if (touch)
  18841. touch.touchAngularSensibility = value;
  18842. },
  18843. enumerable: true,
  18844. configurable: true
  18845. });
  18846. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18847. get: function () {
  18848. var touch = this.inputs.attached["touch"];
  18849. if (touch)
  18850. return touch.touchMoveSensibility;
  18851. },
  18852. set: function (value) {
  18853. var touch = this.inputs.attached["touch"];
  18854. if (touch)
  18855. touch.touchMoveSensibility = value;
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. TouchCamera.prototype.getClassName = function () {
  18861. return "TouchCamera";
  18862. };
  18863. TouchCamera.prototype._setupInputs = function () {
  18864. var mouse = this.inputs.attached["mouse"];
  18865. if (mouse) {
  18866. mouse.touchEnabled = false;
  18867. }
  18868. };
  18869. return TouchCamera;
  18870. }(BABYLON.FreeCamera));
  18871. BABYLON.TouchCamera = TouchCamera;
  18872. })(BABYLON || (BABYLON = {}));
  18873. //# sourceMappingURL=babylon.touchCamera.js.map
  18874. /// <reference path="babylon.targetCamera.ts" />
  18875. /// <reference path="..\Tools\babylon.tools.ts" />
  18876. var BABYLON;
  18877. (function (BABYLON) {
  18878. var ArcRotateCamera = (function (_super) {
  18879. __extends(ArcRotateCamera, _super);
  18880. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18881. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18882. _this.inertialAlphaOffset = 0;
  18883. _this.inertialBetaOffset = 0;
  18884. _this.inertialRadiusOffset = 0;
  18885. _this.lowerAlphaLimit = null;
  18886. _this.upperAlphaLimit = null;
  18887. _this.lowerBetaLimit = 0.01;
  18888. _this.upperBetaLimit = Math.PI;
  18889. _this.lowerRadiusLimit = null;
  18890. _this.upperRadiusLimit = null;
  18891. _this.inertialPanningX = 0;
  18892. _this.inertialPanningY = 0;
  18893. //-- end properties for backward compatibility for inputs
  18894. _this.zoomOnFactor = 1;
  18895. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18896. _this.allowUpsideDown = true;
  18897. _this._viewMatrix = new BABYLON.Matrix();
  18898. // Panning
  18899. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18900. _this.checkCollisions = false;
  18901. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18902. _this._collider = new BABYLON.Collider();
  18903. _this._previousPosition = BABYLON.Vector3.Zero();
  18904. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18905. _this._newPosition = BABYLON.Vector3.Zero();
  18906. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18907. if (collidedMesh === void 0) { collidedMesh = null; }
  18908. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18909. newPosition.multiplyInPlace(_this._collider.radius);
  18910. }
  18911. if (!collidedMesh) {
  18912. _this._previousPosition.copyFrom(_this.position);
  18913. }
  18914. else {
  18915. _this.setPosition(newPosition);
  18916. if (_this.onCollide) {
  18917. _this.onCollide(collidedMesh);
  18918. }
  18919. }
  18920. // Recompute because of constraints
  18921. var cosa = Math.cos(_this.alpha);
  18922. var sina = Math.sin(_this.alpha);
  18923. var cosb = Math.cos(_this.beta);
  18924. var sinb = Math.sin(_this.beta);
  18925. if (sinb === 0) {
  18926. sinb = 0.0001;
  18927. }
  18928. var target = _this._getTargetPosition();
  18929. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18930. _this.position.copyFrom(_this._newPosition);
  18931. var up = _this.upVector;
  18932. if (_this.allowUpsideDown && _this.beta < 0) {
  18933. up = up.clone();
  18934. up = up.negate();
  18935. }
  18936. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18937. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18938. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18939. _this._collisionTriggered = false;
  18940. };
  18941. if (!target) {
  18942. _this.target = BABYLON.Vector3.Zero();
  18943. }
  18944. else {
  18945. _this.target = target;
  18946. }
  18947. _this.alpha = alpha;
  18948. _this.beta = beta;
  18949. _this.radius = radius;
  18950. _this.getViewMatrix();
  18951. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18952. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18953. return _this;
  18954. }
  18955. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18956. //-- begin properties for backward compatibility for inputs
  18957. get: function () {
  18958. var pointers = this.inputs.attached["pointers"];
  18959. if (pointers)
  18960. return pointers.angularSensibilityX;
  18961. },
  18962. set: function (value) {
  18963. var pointers = this.inputs.attached["pointers"];
  18964. if (pointers) {
  18965. pointers.angularSensibilityX = value;
  18966. }
  18967. },
  18968. enumerable: true,
  18969. configurable: true
  18970. });
  18971. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18972. get: function () {
  18973. var pointers = this.inputs.attached["pointers"];
  18974. if (pointers)
  18975. return pointers.angularSensibilityY;
  18976. },
  18977. set: function (value) {
  18978. var pointers = this.inputs.attached["pointers"];
  18979. if (pointers) {
  18980. pointers.angularSensibilityY = value;
  18981. }
  18982. },
  18983. enumerable: true,
  18984. configurable: true
  18985. });
  18986. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18987. get: function () {
  18988. var pointers = this.inputs.attached["pointers"];
  18989. if (pointers)
  18990. return pointers.pinchPrecision;
  18991. },
  18992. set: function (value) {
  18993. var pointers = this.inputs.attached["pointers"];
  18994. if (pointers) {
  18995. pointers.pinchPrecision = value;
  18996. }
  18997. },
  18998. enumerable: true,
  18999. configurable: true
  19000. });
  19001. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  19002. get: function () {
  19003. var pointers = this.inputs.attached["pointers"];
  19004. if (pointers)
  19005. return pointers.panningSensibility;
  19006. },
  19007. set: function (value) {
  19008. var pointers = this.inputs.attached["pointers"];
  19009. if (pointers) {
  19010. pointers.panningSensibility = value;
  19011. }
  19012. },
  19013. enumerable: true,
  19014. configurable: true
  19015. });
  19016. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  19017. get: function () {
  19018. var keyboard = this.inputs.attached["keyboard"];
  19019. if (keyboard)
  19020. return keyboard.keysUp;
  19021. },
  19022. set: function (value) {
  19023. var keyboard = this.inputs.attached["keyboard"];
  19024. if (keyboard)
  19025. keyboard.keysUp = value;
  19026. },
  19027. enumerable: true,
  19028. configurable: true
  19029. });
  19030. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  19031. get: function () {
  19032. var keyboard = this.inputs.attached["keyboard"];
  19033. if (keyboard)
  19034. return keyboard.keysDown;
  19035. },
  19036. set: function (value) {
  19037. var keyboard = this.inputs.attached["keyboard"];
  19038. if (keyboard)
  19039. keyboard.keysDown = value;
  19040. },
  19041. enumerable: true,
  19042. configurable: true
  19043. });
  19044. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  19045. get: function () {
  19046. var keyboard = this.inputs.attached["keyboard"];
  19047. if (keyboard)
  19048. return keyboard.keysLeft;
  19049. },
  19050. set: function (value) {
  19051. var keyboard = this.inputs.attached["keyboard"];
  19052. if (keyboard)
  19053. keyboard.keysLeft = value;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  19059. get: function () {
  19060. var keyboard = this.inputs.attached["keyboard"];
  19061. if (keyboard)
  19062. return keyboard.keysRight;
  19063. },
  19064. set: function (value) {
  19065. var keyboard = this.inputs.attached["keyboard"];
  19066. if (keyboard)
  19067. keyboard.keysRight = value;
  19068. },
  19069. enumerable: true,
  19070. configurable: true
  19071. });
  19072. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  19073. get: function () {
  19074. var mousewheel = this.inputs.attached["mousewheel"];
  19075. if (mousewheel)
  19076. return mousewheel.wheelPrecision;
  19077. },
  19078. set: function (value) {
  19079. var mousewheel = this.inputs.attached["mousewheel"];
  19080. if (mousewheel)
  19081. mousewheel.wheelPrecision = value;
  19082. },
  19083. enumerable: true,
  19084. configurable: true
  19085. });
  19086. // Cache
  19087. ArcRotateCamera.prototype._initCache = function () {
  19088. _super.prototype._initCache.call(this);
  19089. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19090. this._cache.alpha = undefined;
  19091. this._cache.beta = undefined;
  19092. this._cache.radius = undefined;
  19093. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  19094. };
  19095. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  19096. if (!ignoreParentClass) {
  19097. _super.prototype._updateCache.call(this);
  19098. }
  19099. this._cache.target.copyFrom(this._getTargetPosition());
  19100. this._cache.alpha = this.alpha;
  19101. this._cache.beta = this.beta;
  19102. this._cache.radius = this.radius;
  19103. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  19104. };
  19105. ArcRotateCamera.prototype._getTargetPosition = function () {
  19106. if (this.target.getAbsolutePosition) {
  19107. var pos = this.target.getAbsolutePosition();
  19108. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  19109. }
  19110. return this.target;
  19111. };
  19112. // Synchronized
  19113. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  19114. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  19115. return false;
  19116. return this._cache.target.equals(this.target)
  19117. && this._cache.alpha === this.alpha
  19118. && this._cache.beta === this.beta
  19119. && this._cache.radius === this.radius
  19120. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  19121. };
  19122. // Methods
  19123. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  19124. var _this = this;
  19125. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  19126. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  19127. this._useCtrlForPanning = useCtrlForPanning;
  19128. this._panningMouseButton = panningMouseButton;
  19129. this.inputs.attachElement(element, noPreventDefault);
  19130. this._reset = function () {
  19131. _this.inertialAlphaOffset = 0;
  19132. _this.inertialBetaOffset = 0;
  19133. _this.inertialRadiusOffset = 0;
  19134. };
  19135. };
  19136. ArcRotateCamera.prototype.detachControl = function (element) {
  19137. this.inputs.detachElement(element);
  19138. if (this._reset) {
  19139. this._reset();
  19140. }
  19141. };
  19142. ArcRotateCamera.prototype._checkInputs = function () {
  19143. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  19144. if (this._collisionTriggered) {
  19145. return;
  19146. }
  19147. this.inputs.checkInputs();
  19148. // Inertia
  19149. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  19150. if (this.getScene().useRightHandedSystem) {
  19151. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  19152. }
  19153. else {
  19154. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  19155. }
  19156. this.beta += this.inertialBetaOffset;
  19157. this.radius -= this.inertialRadiusOffset;
  19158. this.inertialAlphaOffset *= this.inertia;
  19159. this.inertialBetaOffset *= this.inertia;
  19160. this.inertialRadiusOffset *= this.inertia;
  19161. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  19162. this.inertialAlphaOffset = 0;
  19163. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  19164. this.inertialBetaOffset = 0;
  19165. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  19166. this.inertialRadiusOffset = 0;
  19167. }
  19168. // Panning inertia
  19169. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  19170. if (!this._localDirection) {
  19171. this._localDirection = BABYLON.Vector3.Zero();
  19172. this._transformedDirection = BABYLON.Vector3.Zero();
  19173. }
  19174. this.inertialPanningX *= this.inertia;
  19175. this.inertialPanningY *= this.inertia;
  19176. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  19177. this.inertialPanningX = 0;
  19178. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  19179. this.inertialPanningY = 0;
  19180. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  19181. this._localDirection.multiplyInPlace(this.panningAxis);
  19182. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  19183. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  19184. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  19185. if (!this.panningAxis.y) {
  19186. this._transformedDirection.y = 0;
  19187. }
  19188. if (!this.target.getAbsolutePosition) {
  19189. this.target.addInPlace(this._transformedDirection);
  19190. }
  19191. }
  19192. // Limits
  19193. this._checkLimits();
  19194. _super.prototype._checkInputs.call(this);
  19195. };
  19196. ArcRotateCamera.prototype._checkLimits = function () {
  19197. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  19198. if (this.allowUpsideDown && this.beta > Math.PI) {
  19199. this.beta = this.beta - (2 * Math.PI);
  19200. }
  19201. }
  19202. else {
  19203. if (this.beta < this.lowerBetaLimit) {
  19204. this.beta = this.lowerBetaLimit;
  19205. }
  19206. }
  19207. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  19208. if (this.allowUpsideDown && this.beta < -Math.PI) {
  19209. this.beta = this.beta + (2 * Math.PI);
  19210. }
  19211. }
  19212. else {
  19213. if (this.beta > this.upperBetaLimit) {
  19214. this.beta = this.upperBetaLimit;
  19215. }
  19216. }
  19217. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  19218. this.alpha = this.lowerAlphaLimit;
  19219. }
  19220. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  19221. this.alpha = this.upperAlphaLimit;
  19222. }
  19223. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  19224. this.radius = this.lowerRadiusLimit;
  19225. }
  19226. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  19227. this.radius = this.upperRadiusLimit;
  19228. }
  19229. };
  19230. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  19231. var radiusv3 = this.position.subtract(this._getTargetPosition());
  19232. this.radius = radiusv3.length();
  19233. // Alpha
  19234. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  19235. if (radiusv3.z < 0) {
  19236. this.alpha = 2 * Math.PI - this.alpha;
  19237. }
  19238. // Beta
  19239. this.beta = Math.acos(radiusv3.y / this.radius);
  19240. this._checkLimits();
  19241. };
  19242. ArcRotateCamera.prototype.setPosition = function (position) {
  19243. if (this.position.equals(position)) {
  19244. return;
  19245. }
  19246. this.position.copyFrom(position);
  19247. this.rebuildAnglesAndRadius();
  19248. };
  19249. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  19250. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  19251. if (allowSamePosition === void 0) { allowSamePosition = false; }
  19252. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  19253. return;
  19254. }
  19255. if (toBoundingCenter && target.getBoundingInfo) {
  19256. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  19257. }
  19258. else {
  19259. this._targetBoundingCenter = null;
  19260. }
  19261. this.target = target;
  19262. this.rebuildAnglesAndRadius();
  19263. };
  19264. ArcRotateCamera.prototype._getViewMatrix = function () {
  19265. // Compute
  19266. var cosa = Math.cos(this.alpha);
  19267. var sina = Math.sin(this.alpha);
  19268. var cosb = Math.cos(this.beta);
  19269. var sinb = Math.sin(this.beta);
  19270. if (sinb === 0) {
  19271. sinb = 0.0001;
  19272. }
  19273. var target = this._getTargetPosition();
  19274. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  19275. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  19276. this._collider.radius = this.collisionRadius;
  19277. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  19278. this._collisionTriggered = true;
  19279. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  19280. }
  19281. else {
  19282. this.position.copyFrom(this._newPosition);
  19283. var up = this.upVector;
  19284. if (this.allowUpsideDown && sinb < 0) {
  19285. up = up.clone();
  19286. up = up.negate();
  19287. }
  19288. if (this.getScene().useRightHandedSystem) {
  19289. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  19290. }
  19291. else {
  19292. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  19293. }
  19294. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  19295. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  19296. }
  19297. this._currentTarget = target;
  19298. return this._viewMatrix;
  19299. };
  19300. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  19301. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  19302. meshes = meshes || this.getScene().meshes;
  19303. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  19304. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  19305. this.radius = distance * this.zoomOnFactor;
  19306. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  19307. };
  19308. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  19309. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  19310. var meshesOrMinMaxVector;
  19311. var distance;
  19312. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  19313. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  19314. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  19315. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  19316. }
  19317. else {
  19318. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  19319. distance = meshesOrMinMaxVectorAndDistance.distance;
  19320. }
  19321. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  19322. if (!doNotUpdateMaxZ) {
  19323. this.maxZ = distance * 2;
  19324. }
  19325. };
  19326. /**
  19327. * @override
  19328. * Override Camera.createRigCamera
  19329. */
  19330. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  19331. var alphaShift;
  19332. switch (this.cameraRigMode) {
  19333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19334. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19335. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19336. case BABYLON.Camera.RIG_MODE_VR:
  19337. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  19338. break;
  19339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19340. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  19341. break;
  19342. }
  19343. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  19344. rigCam._cameraRigParams = {};
  19345. return rigCam;
  19346. };
  19347. /**
  19348. * @override
  19349. * Override Camera._updateRigCameras
  19350. */
  19351. ArcRotateCamera.prototype._updateRigCameras = function () {
  19352. var camLeft = this._rigCameras[0];
  19353. var camRight = this._rigCameras[1];
  19354. camLeft.beta = camRight.beta = this.beta;
  19355. camLeft.radius = camRight.radius = this.radius;
  19356. switch (this.cameraRigMode) {
  19357. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19358. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19359. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19360. case BABYLON.Camera.RIG_MODE_VR:
  19361. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  19362. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  19363. break;
  19364. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19365. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  19366. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  19367. break;
  19368. }
  19369. _super.prototype._updateRigCameras.call(this);
  19370. };
  19371. ArcRotateCamera.prototype.dispose = function () {
  19372. this.inputs.clear();
  19373. _super.prototype.dispose.call(this);
  19374. };
  19375. ArcRotateCamera.prototype.getClassName = function () {
  19376. return "ArcRotateCamera";
  19377. };
  19378. return ArcRotateCamera;
  19379. }(BABYLON.TargetCamera));
  19380. __decorate([
  19381. BABYLON.serialize()
  19382. ], ArcRotateCamera.prototype, "alpha", void 0);
  19383. __decorate([
  19384. BABYLON.serialize()
  19385. ], ArcRotateCamera.prototype, "beta", void 0);
  19386. __decorate([
  19387. BABYLON.serialize()
  19388. ], ArcRotateCamera.prototype, "radius", void 0);
  19389. __decorate([
  19390. BABYLON.serializeAsVector3()
  19391. ], ArcRotateCamera.prototype, "target", void 0);
  19392. __decorate([
  19393. BABYLON.serialize()
  19394. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  19395. __decorate([
  19396. BABYLON.serialize()
  19397. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  19398. __decorate([
  19399. BABYLON.serialize()
  19400. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  19401. __decorate([
  19402. BABYLON.serialize()
  19403. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  19404. __decorate([
  19405. BABYLON.serialize()
  19406. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  19407. __decorate([
  19408. BABYLON.serialize()
  19409. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  19410. __decorate([
  19411. BABYLON.serialize()
  19412. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  19413. __decorate([
  19414. BABYLON.serialize()
  19415. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  19416. __decorate([
  19417. BABYLON.serialize()
  19418. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  19419. __decorate([
  19420. BABYLON.serialize()
  19421. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  19422. __decorate([
  19423. BABYLON.serialize()
  19424. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  19425. __decorate([
  19426. BABYLON.serialize()
  19427. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  19428. __decorate([
  19429. BABYLON.serialize()
  19430. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  19431. BABYLON.ArcRotateCamera = ArcRotateCamera;
  19432. })(BABYLON || (BABYLON = {}));
  19433. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  19434. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  19435. var BABYLON;
  19436. (function (BABYLON) {
  19437. var ArcRotateCameraInputsManager = (function (_super) {
  19438. __extends(ArcRotateCameraInputsManager, _super);
  19439. function ArcRotateCameraInputsManager(camera) {
  19440. return _super.call(this, camera) || this;
  19441. }
  19442. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  19443. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  19444. return this;
  19445. };
  19446. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  19447. this.add(new BABYLON.ArcRotateCameraPointersInput());
  19448. return this;
  19449. };
  19450. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  19451. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  19452. return this;
  19453. };
  19454. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  19455. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  19456. return this;
  19457. };
  19458. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  19459. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  19460. return this;
  19461. };
  19462. return ArcRotateCameraInputsManager;
  19463. }(BABYLON.CameraInputsManager));
  19464. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  19465. })(BABYLON || (BABYLON = {}));
  19466. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  19467. var BABYLON;
  19468. (function (BABYLON) {
  19469. var RenderingManager = (function () {
  19470. function RenderingManager(scene) {
  19471. this._renderingGroups = new Array();
  19472. this._autoClearDepthStencil = {};
  19473. this._customOpaqueSortCompareFn = {};
  19474. this._customAlphaTestSortCompareFn = {};
  19475. this._customTransparentSortCompareFn = {};
  19476. this._renderinGroupInfo = null;
  19477. this._scene = scene;
  19478. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  19479. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  19480. }
  19481. }
  19482. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  19483. if (depth === void 0) { depth = true; }
  19484. if (stencil === void 0) { stencil = true; }
  19485. if (this._depthStencilBufferAlreadyCleaned) {
  19486. return;
  19487. }
  19488. this._scene.getEngine().clear(null, false, depth, stencil);
  19489. this._depthStencilBufferAlreadyCleaned = true;
  19490. };
  19491. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  19492. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  19493. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  19494. var info = null;
  19495. if (observable) {
  19496. if (!this._renderinGroupInfo) {
  19497. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  19498. }
  19499. info = this._renderinGroupInfo;
  19500. info.scene = this._scene;
  19501. info.camera = this._scene.activeCamera;
  19502. }
  19503. // Dispatch sprites
  19504. if (renderSprites) {
  19505. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  19506. var manager = this._scene.spriteManagers[index];
  19507. this.dispatchSprites(manager);
  19508. }
  19509. }
  19510. // Render
  19511. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19512. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  19513. var renderingGroup = this._renderingGroups[index];
  19514. if (!renderingGroup && !observable)
  19515. continue;
  19516. this._currentIndex = index;
  19517. var renderingGroupMask = 0;
  19518. // Fire PRECLEAR stage
  19519. if (observable) {
  19520. renderingGroupMask = Math.pow(2, index);
  19521. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  19522. info.renderingGroupId = index;
  19523. observable.notifyObservers(info, renderingGroupMask);
  19524. }
  19525. // Clear depth/stencil if needed
  19526. var autoClear = this._autoClearDepthStencil[index];
  19527. if (autoClear && autoClear.autoClear) {
  19528. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  19529. }
  19530. if (observable) {
  19531. // Fire PREOPAQUE stage
  19532. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  19533. observable.notifyObservers(info, renderingGroupMask);
  19534. // Fire PRETRANSPARENT stage
  19535. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  19536. observable.notifyObservers(info, renderingGroupMask);
  19537. }
  19538. if (renderingGroup)
  19539. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  19540. // Fire POSTTRANSPARENT stage
  19541. if (observable) {
  19542. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  19543. observable.notifyObservers(info, renderingGroupMask);
  19544. }
  19545. }
  19546. };
  19547. RenderingManager.prototype.reset = function () {
  19548. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19549. var renderingGroup = this._renderingGroups[index];
  19550. if (renderingGroup) {
  19551. renderingGroup.prepare();
  19552. }
  19553. }
  19554. };
  19555. RenderingManager.prototype.dispose = function () {
  19556. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  19557. var renderingGroup = this._renderingGroups[index];
  19558. if (renderingGroup) {
  19559. renderingGroup.dispose();
  19560. }
  19561. }
  19562. this._renderingGroups.length = 0;
  19563. };
  19564. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  19565. if (!this._renderingGroups[renderingGroupId]) {
  19566. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  19567. }
  19568. };
  19569. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  19570. var renderingGroupId = spriteManager.renderingGroupId || 0;
  19571. this._prepareRenderingGroup(renderingGroupId);
  19572. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  19573. };
  19574. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  19575. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19576. this._prepareRenderingGroup(renderingGroupId);
  19577. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19578. };
  19579. RenderingManager.prototype.dispatch = function (subMesh) {
  19580. var mesh = subMesh.getMesh();
  19581. var renderingGroupId = mesh.renderingGroupId || 0;
  19582. this._prepareRenderingGroup(renderingGroupId);
  19583. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  19584. };
  19585. /**
  19586. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19587. * This allowed control for front to back rendering or reversly depending of the special needs.
  19588. *
  19589. * @param renderingGroupId The rendering group id corresponding to its index
  19590. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19591. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19592. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19593. */
  19594. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19595. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19596. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19597. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19598. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19599. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19600. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19601. if (this._renderingGroups[renderingGroupId]) {
  19602. var group = this._renderingGroups[renderingGroupId];
  19603. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19604. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19605. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19606. }
  19607. };
  19608. /**
  19609. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19610. *
  19611. * @param renderingGroupId The rendering group id corresponding to its index
  19612. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19613. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19614. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19615. */
  19616. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19617. if (depth === void 0) { depth = true; }
  19618. if (stencil === void 0) { stencil = true; }
  19619. this._autoClearDepthStencil[renderingGroupId] = {
  19620. autoClear: autoClearDepthStencil,
  19621. depth: depth,
  19622. stencil: stencil
  19623. };
  19624. };
  19625. return RenderingManager;
  19626. }());
  19627. /**
  19628. * The max id used for rendering groups (not included)
  19629. */
  19630. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19631. /**
  19632. * The min id used for rendering groups (included)
  19633. */
  19634. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19635. BABYLON.RenderingManager = RenderingManager;
  19636. })(BABYLON || (BABYLON = {}));
  19637. //# sourceMappingURL=babylon.renderingManager.js.map
  19638. var BABYLON;
  19639. (function (BABYLON) {
  19640. var RenderingGroup = (function () {
  19641. /**
  19642. * Creates a new rendering group.
  19643. * @param index The rendering group index
  19644. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19645. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19646. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19647. */
  19648. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19649. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19650. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19651. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19652. this.index = index;
  19653. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19654. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19655. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19656. this._particleSystems = new BABYLON.SmartArray(256);
  19657. this._spriteManagers = new BABYLON.SmartArray(256);
  19658. this._scene = scene;
  19659. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19660. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19661. this.transparentSortCompareFn = transparentSortCompareFn;
  19662. }
  19663. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19664. /**
  19665. * Set the opaque sort comparison function.
  19666. * If null the sub meshes will be render in the order they were created
  19667. */
  19668. set: function (value) {
  19669. this._opaqueSortCompareFn = value;
  19670. if (value) {
  19671. this._renderOpaque = this.renderOpaqueSorted;
  19672. }
  19673. else {
  19674. this._renderOpaque = RenderingGroup.renderUnsorted;
  19675. }
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19681. /**
  19682. * Set the alpha test sort comparison function.
  19683. * If null the sub meshes will be render in the order they were created
  19684. */
  19685. set: function (value) {
  19686. this._alphaTestSortCompareFn = value;
  19687. if (value) {
  19688. this._renderAlphaTest = this.renderAlphaTestSorted;
  19689. }
  19690. else {
  19691. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19692. }
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19698. /**
  19699. * Set the transparent sort comparison function.
  19700. * If null the sub meshes will be render in the order they were created
  19701. */
  19702. set: function (value) {
  19703. if (value) {
  19704. this._transparentSortCompareFn = value;
  19705. }
  19706. else {
  19707. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19708. }
  19709. this._renderTransparent = this.renderTransparentSorted;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. /**
  19715. * Render all the sub meshes contained in the group.
  19716. * @param customRenderFunction Used to override the default render behaviour of the group.
  19717. * @returns true if rendered some submeshes.
  19718. */
  19719. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19720. if (customRenderFunction) {
  19721. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19722. return;
  19723. }
  19724. var engine = this._scene.getEngine();
  19725. // Opaque
  19726. if (this._opaqueSubMeshes.length !== 0) {
  19727. this._renderOpaque(this._opaqueSubMeshes);
  19728. }
  19729. // Alpha test
  19730. if (this._alphaTestSubMeshes.length !== 0) {
  19731. engine.setAlphaTesting(true);
  19732. this._renderAlphaTest(this._alphaTestSubMeshes);
  19733. engine.setAlphaTesting(false);
  19734. }
  19735. var stencilState = engine.getStencilBuffer();
  19736. engine.setStencilBuffer(false);
  19737. // Sprites
  19738. if (renderSprites) {
  19739. this._renderSprites();
  19740. }
  19741. // Particles
  19742. if (renderParticles) {
  19743. this._renderParticles(activeMeshes);
  19744. }
  19745. if (this.onBeforeTransparentRendering) {
  19746. this.onBeforeTransparentRendering();
  19747. }
  19748. // Transparent
  19749. if (this._transparentSubMeshes.length !== 0) {
  19750. this._renderTransparent(this._transparentSubMeshes);
  19751. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19752. }
  19753. engine.setStencilBuffer(stencilState);
  19754. };
  19755. /**
  19756. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19757. * @param subMeshes The submeshes to render
  19758. */
  19759. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19760. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19761. };
  19762. /**
  19763. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19764. * @param subMeshes The submeshes to render
  19765. */
  19766. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19767. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19768. };
  19769. /**
  19770. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19771. * @param subMeshes The submeshes to render
  19772. */
  19773. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19774. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19775. };
  19776. /**
  19777. * Renders the submeshes in a specified order.
  19778. * @param subMeshes The submeshes to sort before render
  19779. * @param sortCompareFn The comparison function use to sort
  19780. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19781. * @param transparent Specifies to activate blending if true
  19782. */
  19783. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19784. var subIndex = 0;
  19785. var subMesh;
  19786. for (; subIndex < subMeshes.length; subIndex++) {
  19787. subMesh = subMeshes.data[subIndex];
  19788. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19789. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19790. }
  19791. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19792. sortedArray.sort(sortCompareFn);
  19793. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19794. subMesh = sortedArray[subIndex];
  19795. subMesh.render(transparent);
  19796. }
  19797. };
  19798. /**
  19799. * Renders the submeshes in the order they were dispatched (no sort applied).
  19800. * @param subMeshes The submeshes to render
  19801. */
  19802. RenderingGroup.renderUnsorted = function (subMeshes) {
  19803. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19804. var submesh = subMeshes.data[subIndex];
  19805. submesh.render(false);
  19806. }
  19807. };
  19808. /**
  19809. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19810. * are rendered back to front if in the same alpha index.
  19811. *
  19812. * @param a The first submesh
  19813. * @param b The second submesh
  19814. * @returns The result of the comparison
  19815. */
  19816. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19817. // Alpha index first
  19818. if (a._alphaIndex > b._alphaIndex) {
  19819. return 1;
  19820. }
  19821. if (a._alphaIndex < b._alphaIndex) {
  19822. return -1;
  19823. }
  19824. // Then distance to camera
  19825. return RenderingGroup.backToFrontSortCompare(a, b);
  19826. };
  19827. /**
  19828. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19829. * are rendered back to front.
  19830. *
  19831. * @param a The first submesh
  19832. * @param b The second submesh
  19833. * @returns The result of the comparison
  19834. */
  19835. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19836. // Then distance to camera
  19837. if (a._distanceToCamera < b._distanceToCamera) {
  19838. return 1;
  19839. }
  19840. if (a._distanceToCamera > b._distanceToCamera) {
  19841. return -1;
  19842. }
  19843. return 0;
  19844. };
  19845. /**
  19846. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19847. * are rendered front to back (prevent overdraw).
  19848. *
  19849. * @param a The first submesh
  19850. * @param b The second submesh
  19851. * @returns The result of the comparison
  19852. */
  19853. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19854. // Then distance to camera
  19855. if (a._distanceToCamera < b._distanceToCamera) {
  19856. return -1;
  19857. }
  19858. if (a._distanceToCamera > b._distanceToCamera) {
  19859. return 1;
  19860. }
  19861. return 0;
  19862. };
  19863. /**
  19864. * Resets the different lists of submeshes to prepare a new frame.
  19865. */
  19866. RenderingGroup.prototype.prepare = function () {
  19867. this._opaqueSubMeshes.reset();
  19868. this._transparentSubMeshes.reset();
  19869. this._alphaTestSubMeshes.reset();
  19870. this._particleSystems.reset();
  19871. this._spriteManagers.reset();
  19872. };
  19873. RenderingGroup.prototype.dispose = function () {
  19874. this._opaqueSubMeshes.dispose();
  19875. this._transparentSubMeshes.dispose();
  19876. this._alphaTestSubMeshes.dispose();
  19877. this._particleSystems.dispose();
  19878. this._spriteManagers.dispose();
  19879. };
  19880. /**
  19881. * Inserts the submesh in its correct queue depending on its material.
  19882. * @param subMesh The submesh to dispatch
  19883. */
  19884. RenderingGroup.prototype.dispatch = function (subMesh) {
  19885. var material = subMesh.getMaterial();
  19886. var mesh = subMesh.getMesh();
  19887. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19888. this._transparentSubMeshes.push(subMesh);
  19889. }
  19890. else if (material.needAlphaTesting()) {
  19891. this._alphaTestSubMeshes.push(subMesh);
  19892. }
  19893. else {
  19894. this._opaqueSubMeshes.push(subMesh); // Opaque
  19895. }
  19896. };
  19897. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19898. this._spriteManagers.push(spriteManager);
  19899. };
  19900. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19901. this._particleSystems.push(particleSystem);
  19902. };
  19903. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19904. if (this._particleSystems.length === 0) {
  19905. return;
  19906. }
  19907. // Particles
  19908. var activeCamera = this._scene.activeCamera;
  19909. this._scene._particlesDuration.beginMonitoring();
  19910. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19911. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19912. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19913. continue;
  19914. }
  19915. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19916. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19917. }
  19918. }
  19919. this._scene._particlesDuration.endMonitoring(false);
  19920. };
  19921. RenderingGroup.prototype._renderSprites = function () {
  19922. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19923. return;
  19924. }
  19925. // Sprites
  19926. var activeCamera = this._scene.activeCamera;
  19927. this._scene._spritesDuration.beginMonitoring();
  19928. for (var id = 0; id < this._spriteManagers.length; id++) {
  19929. var spriteManager = this._spriteManagers.data[id];
  19930. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19931. spriteManager.render();
  19932. }
  19933. }
  19934. this._scene._spritesDuration.endMonitoring(false);
  19935. };
  19936. return RenderingGroup;
  19937. }());
  19938. BABYLON.RenderingGroup = RenderingGroup;
  19939. })(BABYLON || (BABYLON = {}));
  19940. //# sourceMappingURL=babylon.renderingGroup.js.map
  19941. var BABYLON;
  19942. (function (BABYLON) {
  19943. var PostProcessManager = (function () {
  19944. function PostProcessManager(scene) {
  19945. this._vertexBuffers = {};
  19946. this._scene = scene;
  19947. }
  19948. PostProcessManager.prototype._prepareBuffers = function () {
  19949. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  19950. return;
  19951. }
  19952. // VBO
  19953. var vertices = [];
  19954. vertices.push(1, 1);
  19955. vertices.push(-1, 1);
  19956. vertices.push(-1, -1);
  19957. vertices.push(1, -1);
  19958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  19959. // Indices
  19960. var indices = [];
  19961. indices.push(0);
  19962. indices.push(1);
  19963. indices.push(2);
  19964. indices.push(0);
  19965. indices.push(2);
  19966. indices.push(3);
  19967. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  19968. };
  19969. // Methods
  19970. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  19971. var postProcesses = this._scene.activeCamera._postProcesses;
  19972. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  19973. return false;
  19974. }
  19975. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  19976. return true;
  19977. };
  19978. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  19979. var engine = this._scene.getEngine();
  19980. for (var index = 0; index < postProcesses.length; index++) {
  19981. if (index < postProcesses.length - 1) {
  19982. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  19983. }
  19984. else {
  19985. if (targetTexture) {
  19986. engine.bindFramebuffer(targetTexture);
  19987. }
  19988. else {
  19989. engine.restoreDefaultFramebuffer();
  19990. }
  19991. }
  19992. var pp = postProcesses[index];
  19993. var effect = pp.apply();
  19994. if (effect) {
  19995. pp.onBeforeRenderObservable.notifyObservers(effect);
  19996. // VBOs
  19997. this._prepareBuffers();
  19998. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  19999. // Draw order
  20000. engine.draw(true, 0, 6);
  20001. pp.onAfterRenderObservable.notifyObservers(effect);
  20002. }
  20003. }
  20004. // Restore depth buffer
  20005. engine.setDepthBuffer(true);
  20006. engine.setDepthWrite(true);
  20007. };
  20008. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  20009. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  20010. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  20011. return;
  20012. }
  20013. var engine = this._scene.getEngine();
  20014. for (var index = 0, len = postProcesses.length; index < len; index++) {
  20015. if (index < len - 1) {
  20016. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  20017. }
  20018. else {
  20019. if (targetTexture) {
  20020. engine.bindFramebuffer(targetTexture, faceIndex);
  20021. }
  20022. else {
  20023. engine.restoreDefaultFramebuffer();
  20024. }
  20025. }
  20026. if (doNotPresent) {
  20027. break;
  20028. }
  20029. var pp = postProcesses[index];
  20030. var effect = pp.apply();
  20031. if (effect) {
  20032. pp.onBeforeRenderObservable.notifyObservers(effect);
  20033. // VBOs
  20034. this._prepareBuffers();
  20035. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  20036. // Draw order
  20037. engine.draw(true, 0, 6);
  20038. pp.onAfterRenderObservable.notifyObservers(effect);
  20039. }
  20040. }
  20041. // Restore depth buffer
  20042. engine.setDepthBuffer(true);
  20043. engine.setDepthWrite(true);
  20044. };
  20045. PostProcessManager.prototype.dispose = function () {
  20046. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  20047. if (buffer) {
  20048. buffer.dispose();
  20049. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  20050. }
  20051. if (this._indexBuffer) {
  20052. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20053. this._indexBuffer = null;
  20054. }
  20055. };
  20056. return PostProcessManager;
  20057. }());
  20058. BABYLON.PostProcessManager = PostProcessManager;
  20059. })(BABYLON || (BABYLON = {}));
  20060. //# sourceMappingURL=babylon.postProcessManager.js.map
  20061. var BABYLON;
  20062. (function (BABYLON) {
  20063. var PostProcessRenderPipelineManager = (function () {
  20064. function PostProcessRenderPipelineManager() {
  20065. this._renderPipelines = {};
  20066. }
  20067. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20068. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20069. };
  20070. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20071. var renderPipeline = this._renderPipelines[renderPipelineName];
  20072. if (!renderPipeline) {
  20073. return;
  20074. }
  20075. renderPipeline._attachCameras(cameras, unique);
  20076. };
  20077. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20078. var renderPipeline = this._renderPipelines[renderPipelineName];
  20079. if (!renderPipeline) {
  20080. return;
  20081. }
  20082. renderPipeline._detachCameras(cameras);
  20083. };
  20084. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20085. var renderPipeline = this._renderPipelines[renderPipelineName];
  20086. if (!renderPipeline) {
  20087. return;
  20088. }
  20089. renderPipeline._enableEffect(renderEffectName, cameras);
  20090. };
  20091. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20092. var renderPipeline = this._renderPipelines[renderPipelineName];
  20093. if (!renderPipeline) {
  20094. return;
  20095. }
  20096. renderPipeline._disableEffect(renderEffectName, cameras);
  20097. };
  20098. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20099. var renderPipeline = this._renderPipelines[renderPipelineName];
  20100. if (!renderPipeline) {
  20101. return;
  20102. }
  20103. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20104. };
  20105. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20106. var renderPipeline = this._renderPipelines[renderPipelineName];
  20107. if (!renderPipeline) {
  20108. return;
  20109. }
  20110. renderPipeline._disableDisplayOnlyPass(cameras);
  20111. };
  20112. PostProcessRenderPipelineManager.prototype.update = function () {
  20113. for (var renderPipelineName in this._renderPipelines) {
  20114. var pipeline = this._renderPipelines[renderPipelineName];
  20115. if (!pipeline.isSupported) {
  20116. pipeline.dispose();
  20117. delete this._renderPipelines[renderPipelineName];
  20118. }
  20119. else {
  20120. pipeline._update();
  20121. }
  20122. }
  20123. };
  20124. return PostProcessRenderPipelineManager;
  20125. }());
  20126. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20127. })(BABYLON || (BABYLON = {}));
  20128. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20129. var BABYLON;
  20130. (function (BABYLON) {
  20131. var BoundingBoxRenderer = (function () {
  20132. function BoundingBoxRenderer(scene) {
  20133. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20134. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20135. this.showBackLines = true;
  20136. this.renderList = new BABYLON.SmartArray(32);
  20137. this._vertexBuffers = {};
  20138. this._scene = scene;
  20139. }
  20140. BoundingBoxRenderer.prototype._prepareRessources = function () {
  20141. if (this._colorShader) {
  20142. return;
  20143. }
  20144. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  20145. attributes: [BABYLON.VertexBuffer.PositionKind],
  20146. uniforms: ["worldViewProjection", "color"]
  20147. });
  20148. var engine = this._scene.getEngine();
  20149. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20150. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20151. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  20152. };
  20153. BoundingBoxRenderer.prototype.reset = function () {
  20154. this.renderList.reset();
  20155. };
  20156. BoundingBoxRenderer.prototype.render = function () {
  20157. if (this.renderList.length === 0) {
  20158. return;
  20159. }
  20160. this._prepareRessources();
  20161. if (!this._colorShader.isReady()) {
  20162. return;
  20163. }
  20164. var engine = this._scene.getEngine();
  20165. engine.setDepthWrite(false);
  20166. this._colorShader._preBind();
  20167. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20168. var boundingBox = this.renderList.data[boundingBoxIndex];
  20169. var min = boundingBox.minimum;
  20170. var max = boundingBox.maximum;
  20171. var diff = max.subtract(min);
  20172. var median = min.add(diff.scale(0.5));
  20173. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  20174. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  20175. .multiply(boundingBox.getWorldMatrix());
  20176. // VBOs
  20177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  20178. if (this.showBackLines) {
  20179. // Back
  20180. engine.setDepthFunctionToGreaterOrEqual();
  20181. this._scene.resetCachedMaterial();
  20182. this._colorShader.setColor4("color", this.backColor.toColor4());
  20183. this._colorShader.bind(worldMatrix);
  20184. // Draw order
  20185. engine.draw(false, 0, 24);
  20186. }
  20187. // Front
  20188. engine.setDepthFunctionToLess();
  20189. this._scene.resetCachedMaterial();
  20190. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20191. this._colorShader.bind(worldMatrix);
  20192. // Draw order
  20193. engine.draw(false, 0, 24);
  20194. }
  20195. this._colorShader.unbind();
  20196. engine.setDepthFunctionToLessOrEqual();
  20197. engine.setDepthWrite(true);
  20198. };
  20199. BoundingBoxRenderer.prototype.dispose = function () {
  20200. if (!this._colorShader) {
  20201. return;
  20202. }
  20203. this.renderList.dispose();
  20204. this._colorShader.dispose();
  20205. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  20206. if (buffer) {
  20207. buffer.dispose();
  20208. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  20209. }
  20210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20211. };
  20212. return BoundingBoxRenderer;
  20213. }());
  20214. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20215. })(BABYLON || (BABYLON = {}));
  20216. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20217. var BABYLON;
  20218. (function (BABYLON) {
  20219. var ClickInfo = (function () {
  20220. function ClickInfo() {
  20221. this._singleClick = false;
  20222. this._doubleClick = false;
  20223. this._hasSwiped = false;
  20224. this._ignore = false;
  20225. }
  20226. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20227. get: function () {
  20228. return this._singleClick;
  20229. },
  20230. set: function (b) {
  20231. this._singleClick = b;
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20237. get: function () {
  20238. return this._doubleClick;
  20239. },
  20240. set: function (b) {
  20241. this._doubleClick = b;
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20247. get: function () {
  20248. return this._hasSwiped;
  20249. },
  20250. set: function (b) {
  20251. this._hasSwiped = b;
  20252. },
  20253. enumerable: true,
  20254. configurable: true
  20255. });
  20256. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20257. get: function () {
  20258. return this._ignore;
  20259. },
  20260. set: function (b) {
  20261. this._ignore = b;
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. return ClickInfo;
  20267. }());
  20268. var PointerEventTypes = (function () {
  20269. function PointerEventTypes() {
  20270. }
  20271. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  20272. get: function () {
  20273. return PointerEventTypes._POINTERDOWN;
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  20279. get: function () {
  20280. return PointerEventTypes._POINTERUP;
  20281. },
  20282. enumerable: true,
  20283. configurable: true
  20284. });
  20285. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  20286. get: function () {
  20287. return PointerEventTypes._POINTERMOVE;
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  20293. get: function () {
  20294. return PointerEventTypes._POINTERWHEEL;
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  20300. get: function () {
  20301. return PointerEventTypes._POINTERPICK;
  20302. },
  20303. enumerable: true,
  20304. configurable: true
  20305. });
  20306. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  20307. get: function () {
  20308. return PointerEventTypes._POINTERTAP;
  20309. },
  20310. enumerable: true,
  20311. configurable: true
  20312. });
  20313. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  20314. get: function () {
  20315. return PointerEventTypes._POINTERDOUBLETAP;
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. return PointerEventTypes;
  20321. }());
  20322. PointerEventTypes._POINTERDOWN = 0x01;
  20323. PointerEventTypes._POINTERUP = 0x02;
  20324. PointerEventTypes._POINTERMOVE = 0x04;
  20325. PointerEventTypes._POINTERWHEEL = 0x08;
  20326. PointerEventTypes._POINTERPICK = 0x10;
  20327. PointerEventTypes._POINTERTAP = 0x20;
  20328. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  20329. BABYLON.PointerEventTypes = PointerEventTypes;
  20330. var PointerInfoBase = (function () {
  20331. function PointerInfoBase(type, event) {
  20332. this.type = type;
  20333. this.event = event;
  20334. }
  20335. return PointerInfoBase;
  20336. }());
  20337. BABYLON.PointerInfoBase = PointerInfoBase;
  20338. /**
  20339. * This class is used to store pointer related info for the onPrePointerObservable event.
  20340. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  20341. */
  20342. var PointerInfoPre = (function (_super) {
  20343. __extends(PointerInfoPre, _super);
  20344. function PointerInfoPre(type, event, localX, localY) {
  20345. var _this = _super.call(this, type, event) || this;
  20346. _this.skipOnPointerObservable = false;
  20347. _this.localPosition = new BABYLON.Vector2(localX, localY);
  20348. return _this;
  20349. }
  20350. return PointerInfoPre;
  20351. }(PointerInfoBase));
  20352. BABYLON.PointerInfoPre = PointerInfoPre;
  20353. /**
  20354. * This type contains all the data related to a pointer event in Babylon.js.
  20355. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  20356. */
  20357. var PointerInfo = (function (_super) {
  20358. __extends(PointerInfo, _super);
  20359. function PointerInfo(type, event, pickInfo) {
  20360. var _this = _super.call(this, type, event) || this;
  20361. _this.pickInfo = pickInfo;
  20362. return _this;
  20363. }
  20364. return PointerInfo;
  20365. }(PointerInfoBase));
  20366. BABYLON.PointerInfo = PointerInfo;
  20367. /**
  20368. * This class is used by the onRenderingGroupObservable
  20369. */
  20370. var RenderingGroupInfo = (function () {
  20371. function RenderingGroupInfo() {
  20372. }
  20373. return RenderingGroupInfo;
  20374. }());
  20375. /**
  20376. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20377. * This stage will be fired no matter what
  20378. */
  20379. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20380. /**
  20381. * Called before opaque object are rendered.
  20382. * This stage will be fired only if there's 3D Opaque content to render
  20383. */
  20384. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20385. /**
  20386. * Called after the opaque objects are rendered and before the transparent ones
  20387. * This stage will be fired only if there's 3D transparent content to render
  20388. */
  20389. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20390. /**
  20391. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20392. * This stage will be fired no matter what
  20393. */
  20394. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20395. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20396. /**
  20397. * Represents a scene to be rendered by the engine.
  20398. * @see http://doc.babylonjs.com/page.php?p=21911
  20399. */
  20400. var Scene = (function () {
  20401. /**
  20402. * @constructor
  20403. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20404. */
  20405. function Scene(engine) {
  20406. // Members
  20407. this.autoClear = true;
  20408. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20409. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20410. this.forceWireframe = false;
  20411. this._forcePointsCloud = false;
  20412. this.forceShowBoundingBoxes = false;
  20413. this.animationsEnabled = true;
  20414. this.constantlyUpdateMeshUnderPointer = false;
  20415. this.useRightHandedSystem = false;
  20416. this.hoverCursor = "pointer";
  20417. // Metadata
  20418. this.metadata = null;
  20419. // Events
  20420. /**
  20421. * An event triggered when the scene is disposed.
  20422. * @type {BABYLON.Observable}
  20423. */
  20424. this.onDisposeObservable = new BABYLON.Observable();
  20425. /**
  20426. * An event triggered before rendering the scene
  20427. * @type {BABYLON.Observable}
  20428. */
  20429. this.onBeforeRenderObservable = new BABYLON.Observable();
  20430. /**
  20431. * An event triggered after rendering the scene
  20432. * @type {BABYLON.Observable}
  20433. */
  20434. this.onAfterRenderObservable = new BABYLON.Observable();
  20435. /**
  20436. * An event triggered when the scene is ready
  20437. * @type {BABYLON.Observable}
  20438. */
  20439. this.onReadyObservable = new BABYLON.Observable();
  20440. /**
  20441. * An event triggered before rendering a camera
  20442. * @type {BABYLON.Observable}
  20443. */
  20444. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20445. /**
  20446. * An event triggered after rendering a camera
  20447. * @type {BABYLON.Observable}
  20448. */
  20449. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20450. /**
  20451. * An event triggered when a camera is created
  20452. * @type {BABYLON.Observable}
  20453. */
  20454. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20455. /**
  20456. * An event triggered when a camera is removed
  20457. * @type {BABYLON.Observable}
  20458. */
  20459. this.onCameraRemovedObservable = new BABYLON.Observable();
  20460. /**
  20461. * An event triggered when a light is created
  20462. * @type {BABYLON.Observable}
  20463. */
  20464. this.onNewLightAddedObservable = new BABYLON.Observable();
  20465. /**
  20466. * An event triggered when a light is removed
  20467. * @type {BABYLON.Observable}
  20468. */
  20469. this.onLightRemovedObservable = new BABYLON.Observable();
  20470. /**
  20471. * An event triggered when a geometry is created
  20472. * @type {BABYLON.Observable}
  20473. */
  20474. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20475. /**
  20476. * An event triggered when a geometry is removed
  20477. * @type {BABYLON.Observable}
  20478. */
  20479. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20480. /**
  20481. * An event triggered when a mesh is created
  20482. * @type {BABYLON.Observable}
  20483. */
  20484. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20485. /**
  20486. * An event triggered when a mesh is removed
  20487. * @type {BABYLON.Observable}
  20488. */
  20489. this.onMeshRemovedObservable = new BABYLON.Observable();
  20490. /**
  20491. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20492. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20493. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  20494. */
  20495. this.onRenderingGroupObservable = new BABYLON.Observable();
  20496. // Animations
  20497. this.animations = [];
  20498. /**
  20499. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  20500. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  20501. */
  20502. this.onPrePointerObservable = new BABYLON.Observable();
  20503. /**
  20504. * Observable event triggered each time an input event is received from the rendering canvas
  20505. */
  20506. this.onPointerObservable = new BABYLON.Observable();
  20507. this._meshPickProceed = false;
  20508. this._previousHasSwiped = false;
  20509. this._currentPickResult = null;
  20510. this._previousPickResult = null;
  20511. this._isButtonPressed = false;
  20512. this._doubleClickOccured = false;
  20513. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  20514. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20515. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20516. this._startingPointerTime = 0;
  20517. this._previousStartingPointerTime = 0;
  20518. // Fog
  20519. /**
  20520. * is fog enabled on this scene.
  20521. * @type {boolean}
  20522. */
  20523. this._fogEnabled = true;
  20524. this._fogMode = Scene.FOGMODE_NONE;
  20525. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20526. this.fogDensity = 0.1;
  20527. this.fogStart = 0;
  20528. this.fogEnd = 1000.0;
  20529. // Lights
  20530. /**
  20531. * is shadow enabled on this scene.
  20532. * @type {boolean}
  20533. */
  20534. this._shadowsEnabled = true;
  20535. /**
  20536. * is light enabled on this scene.
  20537. * @type {boolean}
  20538. */
  20539. this._lightsEnabled = true;
  20540. /**
  20541. * All of the lights added to this scene.
  20542. * @see BABYLON.Light
  20543. * @type {BABYLON.Light[]}
  20544. */
  20545. this.lights = new Array();
  20546. // Cameras
  20547. /**
  20548. * All of the cameras added to this scene.
  20549. * @see BABYLON.Camera
  20550. * @type {BABYLON.Camera[]}
  20551. */
  20552. this.cameras = new Array();
  20553. this.activeCameras = new Array();
  20554. // Meshes
  20555. /**
  20556. * All of the (abstract) meshes added to this scene.
  20557. * @see BABYLON.AbstractMesh
  20558. * @type {BABYLON.AbstractMesh[]}
  20559. */
  20560. this.meshes = new Array();
  20561. // Geometries
  20562. this._geometries = new Array();
  20563. this.materials = new Array();
  20564. this.multiMaterials = new Array();
  20565. // Textures
  20566. this._texturesEnabled = true;
  20567. this.textures = new Array();
  20568. // Particles
  20569. this.particlesEnabled = true;
  20570. this.particleSystems = new Array();
  20571. // Sprites
  20572. this.spritesEnabled = true;
  20573. this.spriteManagers = new Array();
  20574. // Layers
  20575. this.layers = new Array();
  20576. this.highlightLayers = new Array();
  20577. // Skeletons
  20578. this._skeletonsEnabled = true;
  20579. this.skeletons = new Array();
  20580. // Morph targets
  20581. this.morphTargetManagers = new Array();
  20582. // Lens flares
  20583. this.lensFlaresEnabled = true;
  20584. this.lensFlareSystems = new Array();
  20585. // Collisions
  20586. this.collisionsEnabled = true;
  20587. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20588. // Postprocesses
  20589. this.postProcessesEnabled = true;
  20590. // Customs render targets
  20591. this.renderTargetsEnabled = true;
  20592. this.dumpNextRenderTargets = false;
  20593. this.customRenderTargets = new Array();
  20594. // Imported meshes
  20595. this.importedMeshesFiles = new Array();
  20596. // Probes
  20597. this.probesEnabled = true;
  20598. this.reflectionProbes = new Array();
  20599. this._actionManagers = new Array();
  20600. this._meshesForIntersections = new BABYLON.SmartArray(256);
  20601. // Procedural textures
  20602. this.proceduralTexturesEnabled = true;
  20603. this._proceduralTextures = new Array();
  20604. this.soundTracks = new Array();
  20605. this._audioEnabled = true;
  20606. this._headphone = false;
  20607. // Performance counters
  20608. this._totalMeshesCounter = new BABYLON.PerfCounter();
  20609. this._totalLightsCounter = new BABYLON.PerfCounter();
  20610. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  20611. this._totalTexturesCounter = new BABYLON.PerfCounter();
  20612. this._totalVertices = new BABYLON.PerfCounter();
  20613. this._activeIndices = new BABYLON.PerfCounter();
  20614. this._activeParticles = new BABYLON.PerfCounter();
  20615. this._lastFrameDuration = new BABYLON.PerfCounter();
  20616. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  20617. this._renderTargetsDuration = new BABYLON.PerfCounter();
  20618. this._particlesDuration = new BABYLON.PerfCounter();
  20619. this._renderDuration = new BABYLON.PerfCounter();
  20620. this._spritesDuration = new BABYLON.PerfCounter();
  20621. this._activeBones = new BABYLON.PerfCounter();
  20622. this._animationTime = 0;
  20623. this.animationTimeScale = 1;
  20624. this._renderId = 0;
  20625. this._executeWhenReadyTimeoutId = -1;
  20626. this._intermediateRendering = false;
  20627. this._viewUpdateFlag = -1;
  20628. this._projectionUpdateFlag = -1;
  20629. this._toBeDisposed = new BABYLON.SmartArray(256);
  20630. this._pendingData = []; //ANY
  20631. this._activeMeshes = new BABYLON.SmartArray(256);
  20632. this._processedMaterials = new BABYLON.SmartArray(256);
  20633. this._renderTargets = new BABYLON.SmartArray(256);
  20634. this._activeParticleSystems = new BABYLON.SmartArray(256);
  20635. this._activeSkeletons = new BABYLON.SmartArray(32);
  20636. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  20637. this._activeAnimatables = new Array();
  20638. this._transformMatrix = BABYLON.Matrix.Zero();
  20639. this._edgesRenderers = new BABYLON.SmartArray(16);
  20640. this._uniqueIdCounter = 0;
  20641. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  20642. this._engine.scenes.push(this);
  20643. this._externalData = new BABYLON.StringDictionary();
  20644. this._uid = null;
  20645. this._renderingManager = new BABYLON.RenderingManager(this);
  20646. this.postProcessManager = new BABYLON.PostProcessManager(this);
  20647. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20648. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20649. if (BABYLON.OutlineRenderer) {
  20650. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  20651. }
  20652. this.attachControl();
  20653. if (BABYLON.SoundTrack) {
  20654. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20655. }
  20656. //simplification queue
  20657. if (BABYLON.SimplificationQueue) {
  20658. this.simplificationQueue = new BABYLON.SimplificationQueue();
  20659. }
  20660. //collision coordinator initialization. For now legacy per default.
  20661. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  20662. }
  20663. Object.defineProperty(Scene, "FOGMODE_NONE", {
  20664. get: function () {
  20665. return Scene._FOGMODE_NONE;
  20666. },
  20667. enumerable: true,
  20668. configurable: true
  20669. });
  20670. Object.defineProperty(Scene, "FOGMODE_EXP", {
  20671. get: function () {
  20672. return Scene._FOGMODE_EXP;
  20673. },
  20674. enumerable: true,
  20675. configurable: true
  20676. });
  20677. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  20678. get: function () {
  20679. return Scene._FOGMODE_EXP2;
  20680. },
  20681. enumerable: true,
  20682. configurable: true
  20683. });
  20684. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  20685. get: function () {
  20686. return Scene._FOGMODE_LINEAR;
  20687. },
  20688. enumerable: true,
  20689. configurable: true
  20690. });
  20691. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  20692. get: function () {
  20693. return this._forcePointsCloud;
  20694. },
  20695. set: function (value) {
  20696. if (this._forcePointsCloud === value) {
  20697. return;
  20698. }
  20699. this._forcePointsCloud = value;
  20700. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20701. },
  20702. enumerable: true,
  20703. configurable: true
  20704. });
  20705. Object.defineProperty(Scene.prototype, "onDispose", {
  20706. set: function (callback) {
  20707. if (this._onDisposeObserver) {
  20708. this.onDisposeObservable.remove(this._onDisposeObserver);
  20709. }
  20710. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20711. },
  20712. enumerable: true,
  20713. configurable: true
  20714. });
  20715. Object.defineProperty(Scene.prototype, "beforeRender", {
  20716. set: function (callback) {
  20717. if (this._onBeforeRenderObserver) {
  20718. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20719. }
  20720. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20721. },
  20722. enumerable: true,
  20723. configurable: true
  20724. });
  20725. Object.defineProperty(Scene.prototype, "afterRender", {
  20726. set: function (callback) {
  20727. if (this._onAfterRenderObserver) {
  20728. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20729. }
  20730. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20731. },
  20732. enumerable: true,
  20733. configurable: true
  20734. });
  20735. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20736. set: function (callback) {
  20737. if (this._onBeforeCameraRenderObserver) {
  20738. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20739. }
  20740. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20741. },
  20742. enumerable: true,
  20743. configurable: true
  20744. });
  20745. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20746. set: function (callback) {
  20747. if (this._onAfterCameraRenderObserver) {
  20748. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20749. }
  20750. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20751. },
  20752. enumerable: true,
  20753. configurable: true
  20754. });
  20755. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20756. get: function () {
  20757. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20758. },
  20759. enumerable: true,
  20760. configurable: true
  20761. });
  20762. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20763. get: function () {
  20764. return this._fogEnabled;
  20765. },
  20766. set: function (value) {
  20767. if (this._fogEnabled === value) {
  20768. return;
  20769. }
  20770. this._fogEnabled = value;
  20771. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20772. },
  20773. enumerable: true,
  20774. configurable: true
  20775. });
  20776. Object.defineProperty(Scene.prototype, "fogMode", {
  20777. get: function () {
  20778. return this._fogMode;
  20779. },
  20780. set: function (value) {
  20781. if (this._fogMode === value) {
  20782. return;
  20783. }
  20784. this._fogMode = value;
  20785. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20791. get: function () {
  20792. return this._shadowsEnabled;
  20793. },
  20794. set: function (value) {
  20795. if (this._shadowsEnabled === value) {
  20796. return;
  20797. }
  20798. this._shadowsEnabled = value;
  20799. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20800. },
  20801. enumerable: true,
  20802. configurable: true
  20803. });
  20804. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20805. get: function () {
  20806. return this._lightsEnabled;
  20807. },
  20808. set: function (value) {
  20809. if (this._lightsEnabled === value) {
  20810. return;
  20811. }
  20812. this._lightsEnabled = value;
  20813. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20814. },
  20815. enumerable: true,
  20816. configurable: true
  20817. });
  20818. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20819. get: function () {
  20820. if (!this._defaultMaterial) {
  20821. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20822. }
  20823. return this._defaultMaterial;
  20824. },
  20825. enumerable: true,
  20826. configurable: true
  20827. });
  20828. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20829. get: function () {
  20830. return this._texturesEnabled;
  20831. },
  20832. set: function (value) {
  20833. if (this._texturesEnabled === value) {
  20834. return;
  20835. }
  20836. this._texturesEnabled = value;
  20837. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20838. },
  20839. enumerable: true,
  20840. configurable: true
  20841. });
  20842. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20843. get: function () {
  20844. return this._skeletonsEnabled;
  20845. },
  20846. set: function (value) {
  20847. if (this._skeletonsEnabled === value) {
  20848. return;
  20849. }
  20850. this._skeletonsEnabled = value;
  20851. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20852. },
  20853. enumerable: true,
  20854. configurable: true
  20855. });
  20856. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20857. get: function () {
  20858. return this._frustumPlanes;
  20859. },
  20860. enumerable: true,
  20861. configurable: true
  20862. });
  20863. Object.defineProperty(Scene.prototype, "debugLayer", {
  20864. // Properties
  20865. get: function () {
  20866. if (!this._debugLayer) {
  20867. this._debugLayer = new BABYLON.DebugLayer(this);
  20868. }
  20869. return this._debugLayer;
  20870. },
  20871. enumerable: true,
  20872. configurable: true
  20873. });
  20874. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20875. get: function () {
  20876. return this._workerCollisions;
  20877. },
  20878. set: function (enabled) {
  20879. enabled = (enabled && !!Worker);
  20880. this._workerCollisions = enabled;
  20881. if (this.collisionCoordinator) {
  20882. this.collisionCoordinator.destroy();
  20883. }
  20884. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20885. this.collisionCoordinator.init(this);
  20886. },
  20887. enumerable: true,
  20888. configurable: true
  20889. });
  20890. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20891. get: function () {
  20892. return this._selectionOctree;
  20893. },
  20894. enumerable: true,
  20895. configurable: true
  20896. });
  20897. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20898. /**
  20899. * The mesh that is currently under the pointer.
  20900. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20901. */
  20902. get: function () {
  20903. return this._pointerOverMesh;
  20904. },
  20905. enumerable: true,
  20906. configurable: true
  20907. });
  20908. Object.defineProperty(Scene.prototype, "pointerX", {
  20909. /**
  20910. * Current on-screen X position of the pointer
  20911. * @return {number} X position of the pointer
  20912. */
  20913. get: function () {
  20914. return this._pointerX;
  20915. },
  20916. enumerable: true,
  20917. configurable: true
  20918. });
  20919. Object.defineProperty(Scene.prototype, "pointerY", {
  20920. /**
  20921. * Current on-screen Y position of the pointer
  20922. * @return {number} Y position of the pointer
  20923. */
  20924. get: function () {
  20925. return this._pointerY;
  20926. },
  20927. enumerable: true,
  20928. configurable: true
  20929. });
  20930. Scene.prototype.getCachedMaterial = function () {
  20931. return this._cachedMaterial;
  20932. };
  20933. Scene.prototype.getCachedEffect = function () {
  20934. return this._cachedEffect;
  20935. };
  20936. Scene.prototype.getBoundingBoxRenderer = function () {
  20937. return this._boundingBoxRenderer;
  20938. };
  20939. Scene.prototype.getOutlineRenderer = function () {
  20940. return this._outlineRenderer;
  20941. };
  20942. Scene.prototype.getEngine = function () {
  20943. return this._engine;
  20944. };
  20945. Scene.prototype.getTotalVertices = function () {
  20946. return this._totalVertices.current;
  20947. };
  20948. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20949. get: function () {
  20950. return this._totalVertices;
  20951. },
  20952. enumerable: true,
  20953. configurable: true
  20954. });
  20955. Scene.prototype.getActiveIndices = function () {
  20956. return this._activeIndices.current;
  20957. };
  20958. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20959. get: function () {
  20960. return this._activeIndices;
  20961. },
  20962. enumerable: true,
  20963. configurable: true
  20964. });
  20965. Scene.prototype.getActiveParticles = function () {
  20966. return this._activeParticles.current;
  20967. };
  20968. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20969. get: function () {
  20970. return this._activeParticles;
  20971. },
  20972. enumerable: true,
  20973. configurable: true
  20974. });
  20975. Scene.prototype.getActiveBones = function () {
  20976. return this._activeBones.current;
  20977. };
  20978. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20979. get: function () {
  20980. return this._activeBones;
  20981. },
  20982. enumerable: true,
  20983. configurable: true
  20984. });
  20985. // Stats
  20986. Scene.prototype.getLastFrameDuration = function () {
  20987. return this._lastFrameDuration.current;
  20988. };
  20989. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20990. get: function () {
  20991. return this._lastFrameDuration;
  20992. },
  20993. enumerable: true,
  20994. configurable: true
  20995. });
  20996. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20997. return this._evaluateActiveMeshesDuration.current;
  20998. };
  20999. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21000. get: function () {
  21001. return this._evaluateActiveMeshesDuration;
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. Scene.prototype.getActiveMeshes = function () {
  21007. return this._activeMeshes;
  21008. };
  21009. Scene.prototype.getRenderTargetsDuration = function () {
  21010. return this._renderTargetsDuration.current;
  21011. };
  21012. Scene.prototype.getRenderDuration = function () {
  21013. return this._renderDuration.current;
  21014. };
  21015. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21016. get: function () {
  21017. return this._renderDuration;
  21018. },
  21019. enumerable: true,
  21020. configurable: true
  21021. });
  21022. Scene.prototype.getParticlesDuration = function () {
  21023. return this._particlesDuration.current;
  21024. };
  21025. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21026. get: function () {
  21027. return this._particlesDuration;
  21028. },
  21029. enumerable: true,
  21030. configurable: true
  21031. });
  21032. Scene.prototype.getSpritesDuration = function () {
  21033. return this._spritesDuration.current;
  21034. };
  21035. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21036. get: function () {
  21037. return this._spritesDuration;
  21038. },
  21039. enumerable: true,
  21040. configurable: true
  21041. });
  21042. Scene.prototype.getAnimationRatio = function () {
  21043. return this._animationRatio;
  21044. };
  21045. Scene.prototype.getRenderId = function () {
  21046. return this._renderId;
  21047. };
  21048. Scene.prototype.incrementRenderId = function () {
  21049. this._renderId++;
  21050. };
  21051. Scene.prototype._updatePointerPosition = function (evt) {
  21052. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21053. this._pointerX = evt.clientX - canvasRect.left;
  21054. this._pointerY = evt.clientY - canvasRect.top;
  21055. this._unTranslatedPointerX = this._pointerX;
  21056. this._unTranslatedPointerY = this._pointerY;
  21057. if (this.cameraToUseForPointers) {
  21058. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  21059. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  21060. }
  21061. };
  21062. // Pointers handling
  21063. /**
  21064. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21065. * @param attachUp defines if you want to attach events to pointerup
  21066. * @param attachDown defines if you want to attach events to pointerdown
  21067. * @param attachMove defines if you want to attach events to pointermove
  21068. */
  21069. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21070. var _this = this;
  21071. if (attachUp === void 0) { attachUp = true; }
  21072. if (attachDown === void 0) { attachDown = true; }
  21073. if (attachMove === void 0) { attachMove = true; }
  21074. this._initActionManager = function (act, clickInfo) {
  21075. if (!_this._meshPickProceed) {
  21076. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21077. _this._currentPickResult = pickResult;
  21078. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21079. _this._meshPickProceed = true;
  21080. }
  21081. return act;
  21082. };
  21083. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21084. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21085. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21086. btn !== _this._previousButtonPressed) {
  21087. _this._doubleClickOccured = false;
  21088. clickInfo.singleClick = true;
  21089. clickInfo.ignore = false;
  21090. cb(clickInfo, _this._currentPickResult);
  21091. }
  21092. };
  21093. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21094. var clickInfo = new ClickInfo();
  21095. _this._currentPickResult = null;
  21096. var act;
  21097. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  21098. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  21099. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  21100. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  21101. act = _this._initActionManager(act, clickInfo);
  21102. if (act)
  21103. checkPicking = act.hasPickTriggers;
  21104. }
  21105. if (checkPicking) {
  21106. var btn = evt.button;
  21107. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21108. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21109. if (!clickInfo.hasSwiped) {
  21110. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21111. if (!checkSingleClickImmediately) {
  21112. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  21113. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  21114. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21115. act = _this._initActionManager(act, clickInfo);
  21116. if (act)
  21117. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21118. }
  21119. }
  21120. if (checkSingleClickImmediately) {
  21121. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21122. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21123. btn !== _this._previousButtonPressed) {
  21124. clickInfo.singleClick = true;
  21125. cb(clickInfo, _this._currentPickResult);
  21126. }
  21127. }
  21128. else {
  21129. // wait that no double click has been raised during the double click delay
  21130. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21131. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21132. }
  21133. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  21134. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  21135. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21136. act = _this._initActionManager(act, clickInfo);
  21137. if (act)
  21138. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21139. }
  21140. if (checkDoubleClick) {
  21141. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21142. if (btn === _this._previousButtonPressed &&
  21143. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21144. !_this._doubleClickOccured) {
  21145. // pointer has not moved for 2 clicks, it's a double click
  21146. if (!clickInfo.hasSwiped &&
  21147. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21148. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21149. _this._previousStartingPointerTime = 0;
  21150. _this._doubleClickOccured = true;
  21151. clickInfo.doubleClick = true;
  21152. clickInfo.ignore = false;
  21153. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  21154. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  21155. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21156. cb(clickInfo, _this._currentPickResult);
  21157. }
  21158. else {
  21159. _this._doubleClickOccured = false;
  21160. _this._previousStartingPointerTime = _this._startingPointerTime;
  21161. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21162. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21163. _this._previousButtonPressed = btn;
  21164. _this._previousHasSwiped = clickInfo.hasSwiped;
  21165. if (Scene.ExclusiveDoubleClickMode) {
  21166. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  21167. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  21168. }
  21169. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21170. cb(clickInfo, _this._previousPickResult);
  21171. }
  21172. else {
  21173. cb(clickInfo, _this._currentPickResult);
  21174. }
  21175. }
  21176. }
  21177. else {
  21178. _this._doubleClickOccured = false;
  21179. _this._previousStartingPointerTime = _this._startingPointerTime;
  21180. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21181. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21182. _this._previousButtonPressed = btn;
  21183. _this._previousHasSwiped = clickInfo.hasSwiped;
  21184. }
  21185. }
  21186. }
  21187. }
  21188. clickInfo.ignore = true;
  21189. cb(clickInfo, _this._currentPickResult);
  21190. };
  21191. var spritePredicate = function (sprite) {
  21192. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21193. };
  21194. this._onPointerMove = function (evt) {
  21195. _this._updatePointerPosition(evt);
  21196. // PreObservable support
  21197. if (_this.onPrePointerObservable.hasObservers()) {
  21198. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  21199. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21200. _this.onPrePointerObservable.notifyObservers(pi, type);
  21201. if (pi.skipOnPointerObservable) {
  21202. return;
  21203. }
  21204. }
  21205. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21206. return;
  21207. }
  21208. var canvas = _this._engine.getRenderingCanvas();
  21209. if (!_this.pointerMovePredicate) {
  21210. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21211. }
  21212. // Meshes
  21213. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21214. if (pickResult.hit && pickResult.pickedMesh) {
  21215. _this.setPointerOverSprite(null);
  21216. _this.setPointerOverMesh(pickResult.pickedMesh);
  21217. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21218. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  21219. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  21220. }
  21221. else {
  21222. canvas.style.cursor = _this.hoverCursor;
  21223. }
  21224. }
  21225. else {
  21226. canvas.style.cursor = "";
  21227. }
  21228. }
  21229. else {
  21230. _this.setPointerOverMesh(null);
  21231. // Sprites
  21232. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  21233. if (pickResult.hit && pickResult.pickedSprite) {
  21234. _this.setPointerOverSprite(pickResult.pickedSprite);
  21235. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  21236. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  21237. }
  21238. else {
  21239. canvas.style.cursor = _this.hoverCursor;
  21240. }
  21241. }
  21242. else {
  21243. _this.setPointerOverSprite(null);
  21244. // Restore pointer
  21245. canvas.style.cursor = "";
  21246. }
  21247. }
  21248. if (_this.onPointerMove) {
  21249. _this.onPointerMove(evt, pickResult);
  21250. }
  21251. if (_this.onPointerObservable.hasObservers()) {
  21252. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  21253. var pi = new PointerInfo(type, evt, pickResult);
  21254. _this.onPointerObservable.notifyObservers(pi, type);
  21255. }
  21256. };
  21257. this._onPointerDown = function (evt) {
  21258. _this._isButtonPressed = true;
  21259. _this._pickedDownMesh = null;
  21260. _this._meshPickProceed = false;
  21261. _this._updatePointerPosition(evt);
  21262. // PreObservable support
  21263. if (_this.onPrePointerObservable.hasObservers()) {
  21264. var type = PointerEventTypes.POINTERDOWN;
  21265. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21266. _this.onPrePointerObservable.notifyObservers(pi, type);
  21267. if (pi.skipOnPointerObservable) {
  21268. return;
  21269. }
  21270. }
  21271. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21272. return;
  21273. }
  21274. _this._startingPointerPosition.x = _this._pointerX;
  21275. _this._startingPointerPosition.y = _this._pointerY;
  21276. _this._startingPointerTime = new Date().getTime();
  21277. if (!_this.pointerDownPredicate) {
  21278. _this.pointerDownPredicate = function (mesh) {
  21279. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  21280. };
  21281. }
  21282. // Meshes
  21283. _this._pickedDownMesh = null;
  21284. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21285. if (pickResult.hit && pickResult.pickedMesh) {
  21286. _this._pickedDownMesh = pickResult.pickedMesh;
  21287. var actionManager = pickResult.pickedMesh.actionManager;
  21288. if (actionManager) {
  21289. if (actionManager.hasPickTriggers) {
  21290. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21291. switch (evt.button) {
  21292. case 0:
  21293. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21294. break;
  21295. case 1:
  21296. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21297. break;
  21298. case 2:
  21299. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21300. break;
  21301. }
  21302. }
  21303. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21304. window.setTimeout((function () {
  21305. var _this = this;
  21306. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  21307. if (pickResult.hit && pickResult.pickedMesh) {
  21308. if (this._isButtonPressed &&
  21309. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  21310. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  21311. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  21312. this._startingPointerTime = 0;
  21313. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21314. }
  21315. }
  21316. }).bind(_this), Scene.LongPressDelay);
  21317. }
  21318. }
  21319. }
  21320. if (_this.onPointerDown) {
  21321. _this.onPointerDown(evt, pickResult);
  21322. }
  21323. if (_this.onPointerObservable.hasObservers()) {
  21324. var type = PointerEventTypes.POINTERDOWN;
  21325. var pi = new PointerInfo(type, evt, pickResult);
  21326. _this.onPointerObservable.notifyObservers(pi, type);
  21327. }
  21328. // Sprites
  21329. _this._pickedDownSprite = null;
  21330. if (_this.spriteManagers.length > 0) {
  21331. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  21332. if (pickResult.hit && pickResult.pickedSprite) {
  21333. if (pickResult.pickedSprite.actionManager) {
  21334. _this._pickedDownSprite = pickResult.pickedSprite;
  21335. switch (evt.button) {
  21336. case 0:
  21337. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21338. break;
  21339. case 1:
  21340. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21341. break;
  21342. case 2:
  21343. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21344. break;
  21345. }
  21346. if (pickResult.pickedSprite.actionManager) {
  21347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21348. }
  21349. }
  21350. }
  21351. }
  21352. };
  21353. this._onPointerUp = function (evt) {
  21354. _this._isButtonPressed = false;
  21355. _this._pickedUpMesh = null;
  21356. _this._meshPickProceed = false;
  21357. _this._updatePointerPosition(evt);
  21358. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  21359. // PreObservable support
  21360. if (this.onPrePointerObservable.hasObservers()) {
  21361. if (!clickInfo.ignore) {
  21362. if (!clickInfo.hasSwiped) {
  21363. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  21364. var type = PointerEventTypes.POINTERTAP;
  21365. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  21366. this.onPrePointerObservable.notifyObservers(pi, type);
  21367. if (pi.skipOnPointerObservable) {
  21368. return;
  21369. }
  21370. }
  21371. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  21372. var type = PointerEventTypes.POINTERDOUBLETAP;
  21373. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  21374. this.onPrePointerObservable.notifyObservers(pi, type);
  21375. if (pi.skipOnPointerObservable) {
  21376. return;
  21377. }
  21378. }
  21379. }
  21380. }
  21381. else {
  21382. var type = PointerEventTypes.POINTERUP;
  21383. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  21384. this.onPrePointerObservable.notifyObservers(pi, type);
  21385. if (pi.skipOnPointerObservable) {
  21386. return;
  21387. }
  21388. }
  21389. }
  21390. if (!this.cameraToUseForPointers && !this.activeCamera) {
  21391. return;
  21392. }
  21393. if (!this.pointerUpPredicate) {
  21394. this.pointerUpPredicate = function (mesh) {
  21395. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  21396. };
  21397. }
  21398. // Meshes
  21399. if (!this._meshPickProceed && (BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  21400. this._initActionManager(null, clickInfo);
  21401. }
  21402. if (!pickResult) {
  21403. pickResult = this._currentPickResult;
  21404. }
  21405. if (pickResult && pickResult.pickedMesh) {
  21406. this._pickedUpMesh = pickResult.pickedMesh;
  21407. if (this._pickedDownMesh === this._pickedUpMesh) {
  21408. if (this.onPointerPick) {
  21409. this.onPointerPick(evt, pickResult);
  21410. }
  21411. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21412. var type = PointerEventTypes.POINTERPICK;
  21413. var pi = new PointerInfo(type, evt, pickResult);
  21414. this.onPointerObservable.notifyObservers(pi, type);
  21415. }
  21416. }
  21417. if (pickResult.pickedMesh.actionManager) {
  21418. if (clickInfo.ignore) {
  21419. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21420. }
  21421. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21422. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21423. }
  21424. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21425. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21426. }
  21427. }
  21428. }
  21429. if (this._pickedDownMesh &&
  21430. this._pickedDownMesh.actionManager &&
  21431. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21432. this._pickedDownMesh !== this._pickedUpMesh) {
  21433. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21434. }
  21435. if (this.onPointerUp) {
  21436. this.onPointerUp(evt, pickResult);
  21437. }
  21438. if (this.onPointerObservable.hasObservers()) {
  21439. if (!clickInfo.ignore) {
  21440. if (!clickInfo.hasSwiped) {
  21441. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  21442. var type = PointerEventTypes.POINTERTAP;
  21443. var pi = new PointerInfo(type, evt, pickResult);
  21444. this.onPointerObservable.notifyObservers(pi, type);
  21445. }
  21446. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  21447. var type = PointerEventTypes.POINTERDOUBLETAP;
  21448. var pi = new PointerInfo(type, evt, pickResult);
  21449. this.onPointerObservable.notifyObservers(pi, type);
  21450. }
  21451. }
  21452. }
  21453. else {
  21454. var type = PointerEventTypes.POINTERUP;
  21455. var pi = new PointerInfo(type, evt, pickResult);
  21456. this.onPointerObservable.notifyObservers(pi, type);
  21457. }
  21458. }
  21459. // Sprites
  21460. if (this.spriteManagers.length > 0) {
  21461. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  21462. if (pickResult.hit && pickResult.pickedSprite) {
  21463. if (pickResult.pickedSprite.actionManager) {
  21464. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  21465. if (pickResult.pickedSprite.actionManager) {
  21466. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  21467. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  21468. }
  21469. }
  21470. }
  21471. }
  21472. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  21473. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  21474. }
  21475. }
  21476. this._previousPickResult = this._currentPickResult;
  21477. }).bind(_this));
  21478. };
  21479. this._onKeyDown = function (evt) {
  21480. if (_this.actionManager) {
  21481. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21482. }
  21483. };
  21484. this._onKeyUp = function (evt) {
  21485. if (_this.actionManager) {
  21486. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  21487. }
  21488. };
  21489. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21490. var canvas = this._engine.getRenderingCanvas();
  21491. if (attachMove) {
  21492. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21493. // Wheel
  21494. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21495. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21496. }
  21497. if (attachDown) {
  21498. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21499. }
  21500. if (attachUp) {
  21501. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21502. }
  21503. canvas.tabIndex = 1;
  21504. canvas.addEventListener("keydown", this._onKeyDown, false);
  21505. canvas.addEventListener("keyup", this._onKeyUp, false);
  21506. };
  21507. Scene.prototype.detachControl = function () {
  21508. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21509. var canvas = this._engine.getRenderingCanvas();
  21510. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21511. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21512. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21513. // Wheel
  21514. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21515. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21516. canvas.removeEventListener("keydown", this._onKeyDown);
  21517. canvas.removeEventListener("keyup", this._onKeyUp);
  21518. };
  21519. // Ready
  21520. Scene.prototype.isReady = function () {
  21521. if (this._pendingData.length > 0) {
  21522. return false;
  21523. }
  21524. var index;
  21525. // Geometries
  21526. for (index = 0; index < this._geometries.length; index++) {
  21527. var geometry = this._geometries[index];
  21528. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21529. return false;
  21530. }
  21531. }
  21532. // Meshes
  21533. for (index = 0; index < this.meshes.length; index++) {
  21534. var mesh = this.meshes[index];
  21535. if (!mesh.isEnabled()) {
  21536. continue;
  21537. }
  21538. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21539. continue;
  21540. }
  21541. if (!mesh.isReady()) {
  21542. return false;
  21543. }
  21544. var mat = mesh.material;
  21545. if (mat) {
  21546. if (!mat.isReady(mesh)) {
  21547. return false;
  21548. }
  21549. }
  21550. }
  21551. return true;
  21552. };
  21553. Scene.prototype.resetCachedMaterial = function () {
  21554. this._cachedMaterial = null;
  21555. this._cachedEffect = null;
  21556. };
  21557. Scene.prototype.registerBeforeRender = function (func) {
  21558. this.onBeforeRenderObservable.add(func);
  21559. };
  21560. Scene.prototype.unregisterBeforeRender = function (func) {
  21561. this.onBeforeRenderObservable.removeCallback(func);
  21562. };
  21563. Scene.prototype.registerAfterRender = function (func) {
  21564. this.onAfterRenderObservable.add(func);
  21565. };
  21566. Scene.prototype.unregisterAfterRender = function (func) {
  21567. this.onAfterRenderObservable.removeCallback(func);
  21568. };
  21569. Scene.prototype._addPendingData = function (data) {
  21570. this._pendingData.push(data);
  21571. };
  21572. Scene.prototype._removePendingData = function (data) {
  21573. var index = this._pendingData.indexOf(data);
  21574. if (index !== -1) {
  21575. this._pendingData.splice(index, 1);
  21576. }
  21577. };
  21578. Scene.prototype.getWaitingItemsCount = function () {
  21579. return this._pendingData.length;
  21580. };
  21581. /**
  21582. * Registers a function to be executed when the scene is ready.
  21583. * @param {Function} func - the function to be executed.
  21584. */
  21585. Scene.prototype.executeWhenReady = function (func) {
  21586. var _this = this;
  21587. this.onReadyObservable.add(func);
  21588. if (this._executeWhenReadyTimeoutId !== -1) {
  21589. return;
  21590. }
  21591. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21592. _this._checkIsReady();
  21593. }, 150);
  21594. };
  21595. Scene.prototype._checkIsReady = function () {
  21596. var _this = this;
  21597. if (this.isReady()) {
  21598. this.onReadyObservable.notifyObservers(this);
  21599. this.onReadyObservable.clear();
  21600. this._executeWhenReadyTimeoutId = -1;
  21601. return;
  21602. }
  21603. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21604. _this._checkIsReady();
  21605. }, 150);
  21606. };
  21607. // Animations
  21608. /**
  21609. * Will start the animation sequence of a given target
  21610. * @param target - the target
  21611. * @param {number} from - from which frame should animation start
  21612. * @param {number} to - till which frame should animation run.
  21613. * @param {boolean} [loop] - should the animation loop
  21614. * @param {number} [speedRatio] - the speed in which to run the animation
  21615. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21616. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21617. * @return {BABYLON.Animatable} the animatable object created for this animation
  21618. * @see BABYLON.Animatable
  21619. * @see http://doc.babylonjs.com/page.php?p=22081
  21620. */
  21621. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21622. if (speedRatio === void 0) { speedRatio = 1.0; }
  21623. this.stopAnimation(target);
  21624. if (!animatable) {
  21625. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21626. }
  21627. // Local animations
  21628. if (target.animations) {
  21629. animatable.appendAnimations(target, target.animations);
  21630. }
  21631. // Children animations
  21632. if (target.getAnimatables) {
  21633. var animatables = target.getAnimatables();
  21634. for (var index = 0; index < animatables.length; index++) {
  21635. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21636. }
  21637. }
  21638. animatable.reset();
  21639. return animatable;
  21640. };
  21641. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21642. if (speedRatio === undefined) {
  21643. speedRatio = 1.0;
  21644. }
  21645. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21646. return animatable;
  21647. };
  21648. Scene.prototype.getAnimatableByTarget = function (target) {
  21649. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21650. if (this._activeAnimatables[index].target === target) {
  21651. return this._activeAnimatables[index];
  21652. }
  21653. }
  21654. return null;
  21655. };
  21656. Object.defineProperty(Scene.prototype, "Animatables", {
  21657. get: function () {
  21658. return this._activeAnimatables;
  21659. },
  21660. enumerable: true,
  21661. configurable: true
  21662. });
  21663. /**
  21664. * Will stop the animation of the given target
  21665. * @param target - the target
  21666. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21667. * @see beginAnimation
  21668. */
  21669. Scene.prototype.stopAnimation = function (target, animationName) {
  21670. var animatable = this.getAnimatableByTarget(target);
  21671. if (animatable) {
  21672. animatable.stop(animationName);
  21673. }
  21674. };
  21675. Scene.prototype._animate = function () {
  21676. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21677. return;
  21678. }
  21679. // Getting time
  21680. var now = BABYLON.Tools.Now;
  21681. if (!this._animationTimeLast) {
  21682. if (this._pendingData.length > 0) {
  21683. return;
  21684. }
  21685. this._animationTimeLast = now;
  21686. }
  21687. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  21688. this._animationTime += deltaTime;
  21689. this._animationTimeLast = now;
  21690. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21691. this._activeAnimatables[index]._animate(this._animationTime);
  21692. }
  21693. };
  21694. // Matrix
  21695. Scene.prototype.getViewMatrix = function () {
  21696. return this._viewMatrix;
  21697. };
  21698. Scene.prototype.getProjectionMatrix = function () {
  21699. return this._projectionMatrix;
  21700. };
  21701. Scene.prototype.getTransformMatrix = function () {
  21702. return this._transformMatrix;
  21703. };
  21704. Scene.prototype.setTransformMatrix = function (view, projection) {
  21705. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21706. return;
  21707. }
  21708. this._viewUpdateFlag = view.updateFlag;
  21709. this._projectionUpdateFlag = projection.updateFlag;
  21710. this._viewMatrix = view;
  21711. this._projectionMatrix = projection;
  21712. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21713. // Update frustum
  21714. if (!this._frustumPlanes) {
  21715. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21716. }
  21717. else {
  21718. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21719. }
  21720. };
  21721. // Methods
  21722. Scene.prototype.getUniqueId = function () {
  21723. var result = this._uniqueIdCounter;
  21724. this._uniqueIdCounter++;
  21725. return result;
  21726. };
  21727. Scene.prototype.addMesh = function (newMesh) {
  21728. newMesh.uniqueId = this.getUniqueId();
  21729. var position = this.meshes.push(newMesh);
  21730. //notify the collision coordinator
  21731. this.collisionCoordinator.onMeshAdded(newMesh);
  21732. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21733. };
  21734. Scene.prototype.removeMesh = function (toRemove) {
  21735. var index = this.meshes.indexOf(toRemove);
  21736. if (index !== -1) {
  21737. // Remove from the scene if mesh found
  21738. this.meshes.splice(index, 1);
  21739. }
  21740. //notify the collision coordinator
  21741. this.collisionCoordinator.onMeshRemoved(toRemove);
  21742. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21743. return index;
  21744. };
  21745. Scene.prototype.removeSkeleton = function (toRemove) {
  21746. var index = this.skeletons.indexOf(toRemove);
  21747. if (index !== -1) {
  21748. // Remove from the scene if found
  21749. this.skeletons.splice(index, 1);
  21750. }
  21751. return index;
  21752. };
  21753. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21754. var index = this.morphTargetManagers.indexOf(toRemove);
  21755. if (index !== -1) {
  21756. // Remove from the scene if found
  21757. this.morphTargetManagers.splice(index, 1);
  21758. }
  21759. return index;
  21760. };
  21761. Scene.prototype.removeLight = function (toRemove) {
  21762. var index = this.lights.indexOf(toRemove);
  21763. if (index !== -1) {
  21764. // Remove from the scene if mesh found
  21765. this.lights.splice(index, 1);
  21766. }
  21767. this.onLightRemovedObservable.notifyObservers(toRemove);
  21768. return index;
  21769. };
  21770. Scene.prototype.removeCamera = function (toRemove) {
  21771. var index = this.cameras.indexOf(toRemove);
  21772. if (index !== -1) {
  21773. // Remove from the scene if mesh found
  21774. this.cameras.splice(index, 1);
  21775. }
  21776. // Remove from activeCameras
  21777. var index2 = this.activeCameras.indexOf(toRemove);
  21778. if (index2 !== -1) {
  21779. // Remove from the scene if mesh found
  21780. this.activeCameras.splice(index2, 1);
  21781. }
  21782. // Reset the activeCamera
  21783. if (this.activeCamera === toRemove) {
  21784. if (this.cameras.length > 0) {
  21785. this.activeCamera = this.cameras[0];
  21786. }
  21787. else {
  21788. this.activeCamera = null;
  21789. }
  21790. }
  21791. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21792. return index;
  21793. };
  21794. Scene.prototype.addLight = function (newLight) {
  21795. newLight.uniqueId = this.getUniqueId();
  21796. var position = this.lights.push(newLight);
  21797. this.onNewLightAddedObservable.notifyObservers(newLight);
  21798. };
  21799. Scene.prototype.addCamera = function (newCamera) {
  21800. newCamera.uniqueId = this.getUniqueId();
  21801. var position = this.cameras.push(newCamera);
  21802. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21803. };
  21804. /**
  21805. * Switch active camera
  21806. * @param {Camera} newCamera - new active camera
  21807. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21808. */
  21809. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21810. if (attachControl === void 0) { attachControl = true; }
  21811. var canvas = this._engine.getRenderingCanvas();
  21812. this.activeCamera.detachControl(canvas);
  21813. this.activeCamera = newCamera;
  21814. if (attachControl) {
  21815. newCamera.attachControl(canvas);
  21816. }
  21817. };
  21818. /**
  21819. * sets the active camera of the scene using its ID
  21820. * @param {string} id - the camera's ID
  21821. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21822. * @see activeCamera
  21823. */
  21824. Scene.prototype.setActiveCameraByID = function (id) {
  21825. var camera = this.getCameraByID(id);
  21826. if (camera) {
  21827. this.activeCamera = camera;
  21828. return camera;
  21829. }
  21830. return null;
  21831. };
  21832. /**
  21833. * sets the active camera of the scene using its name
  21834. * @param {string} name - the camera's name
  21835. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21836. * @see activeCamera
  21837. */
  21838. Scene.prototype.setActiveCameraByName = function (name) {
  21839. var camera = this.getCameraByName(name);
  21840. if (camera) {
  21841. this.activeCamera = camera;
  21842. return camera;
  21843. }
  21844. return null;
  21845. };
  21846. /**
  21847. * get a material using its id
  21848. * @param {string} the material's ID
  21849. * @return {BABYLON.Material|null} the material or null if none found.
  21850. */
  21851. Scene.prototype.getMaterialByID = function (id) {
  21852. for (var index = 0; index < this.materials.length; index++) {
  21853. if (this.materials[index].id === id) {
  21854. return this.materials[index];
  21855. }
  21856. }
  21857. return null;
  21858. };
  21859. /**
  21860. * get a material using its name
  21861. * @param {string} the material's name
  21862. * @return {BABYLON.Material|null} the material or null if none found.
  21863. */
  21864. Scene.prototype.getMaterialByName = function (name) {
  21865. for (var index = 0; index < this.materials.length; index++) {
  21866. if (this.materials[index].name === name) {
  21867. return this.materials[index];
  21868. }
  21869. }
  21870. return null;
  21871. };
  21872. Scene.prototype.getLensFlareSystemByName = function (name) {
  21873. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21874. if (this.lensFlareSystems[index].name === name) {
  21875. return this.lensFlareSystems[index];
  21876. }
  21877. }
  21878. return null;
  21879. };
  21880. Scene.prototype.getLensFlareSystemByID = function (id) {
  21881. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21882. if (this.lensFlareSystems[index].id === id) {
  21883. return this.lensFlareSystems[index];
  21884. }
  21885. }
  21886. return null;
  21887. };
  21888. Scene.prototype.getCameraByID = function (id) {
  21889. for (var index = 0; index < this.cameras.length; index++) {
  21890. if (this.cameras[index].id === id) {
  21891. return this.cameras[index];
  21892. }
  21893. }
  21894. return null;
  21895. };
  21896. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21897. for (var index = 0; index < this.cameras.length; index++) {
  21898. if (this.cameras[index].uniqueId === uniqueId) {
  21899. return this.cameras[index];
  21900. }
  21901. }
  21902. return null;
  21903. };
  21904. /**
  21905. * get a camera using its name
  21906. * @param {string} the camera's name
  21907. * @return {BABYLON.Camera|null} the camera or null if none found.
  21908. */
  21909. Scene.prototype.getCameraByName = function (name) {
  21910. for (var index = 0; index < this.cameras.length; index++) {
  21911. if (this.cameras[index].name === name) {
  21912. return this.cameras[index];
  21913. }
  21914. }
  21915. return null;
  21916. };
  21917. /**
  21918. * get a bone using its id
  21919. * @param {string} the bone's id
  21920. * @return {BABYLON.Bone|null} the bone or null if not found
  21921. */
  21922. Scene.prototype.getBoneByID = function (id) {
  21923. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21924. var skeleton = this.skeletons[skeletonIndex];
  21925. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21926. if (skeleton.bones[boneIndex].id === id) {
  21927. return skeleton.bones[boneIndex];
  21928. }
  21929. }
  21930. }
  21931. return null;
  21932. };
  21933. /**
  21934. * get a bone using its id
  21935. * @param {string} the bone's name
  21936. * @return {BABYLON.Bone|null} the bone or null if not found
  21937. */
  21938. Scene.prototype.getBoneByName = function (name) {
  21939. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21940. var skeleton = this.skeletons[skeletonIndex];
  21941. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21942. if (skeleton.bones[boneIndex].name === name) {
  21943. return skeleton.bones[boneIndex];
  21944. }
  21945. }
  21946. }
  21947. return null;
  21948. };
  21949. /**
  21950. * get a light node using its name
  21951. * @param {string} the light's name
  21952. * @return {BABYLON.Light|null} the light or null if none found.
  21953. */
  21954. Scene.prototype.getLightByName = function (name) {
  21955. for (var index = 0; index < this.lights.length; index++) {
  21956. if (this.lights[index].name === name) {
  21957. return this.lights[index];
  21958. }
  21959. }
  21960. return null;
  21961. };
  21962. /**
  21963. * get a light node using its ID
  21964. * @param {string} the light's id
  21965. * @return {BABYLON.Light|null} the light or null if none found.
  21966. */
  21967. Scene.prototype.getLightByID = function (id) {
  21968. for (var index = 0; index < this.lights.length; index++) {
  21969. if (this.lights[index].id === id) {
  21970. return this.lights[index];
  21971. }
  21972. }
  21973. return null;
  21974. };
  21975. /**
  21976. * get a light node using its scene-generated unique ID
  21977. * @param {number} the light's unique id
  21978. * @return {BABYLON.Light|null} the light or null if none found.
  21979. */
  21980. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21981. for (var index = 0; index < this.lights.length; index++) {
  21982. if (this.lights[index].uniqueId === uniqueId) {
  21983. return this.lights[index];
  21984. }
  21985. }
  21986. return null;
  21987. };
  21988. /**
  21989. * get a particle system by id
  21990. * @param id {number} the particle system id
  21991. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  21992. */
  21993. Scene.prototype.getParticleSystemByID = function (id) {
  21994. for (var index = 0; index < this.particleSystems.length; index++) {
  21995. if (this.particleSystems[index].id === id) {
  21996. return this.particleSystems[index];
  21997. }
  21998. }
  21999. return null;
  22000. };
  22001. /**
  22002. * get a geometry using its ID
  22003. * @param {string} the geometry's id
  22004. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22005. */
  22006. Scene.prototype.getGeometryByID = function (id) {
  22007. for (var index = 0; index < this._geometries.length; index++) {
  22008. if (this._geometries[index].id === id) {
  22009. return this._geometries[index];
  22010. }
  22011. }
  22012. return null;
  22013. };
  22014. /**
  22015. * add a new geometry to this scene.
  22016. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22017. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22018. * @return {boolean} was the geometry added or not
  22019. */
  22020. Scene.prototype.pushGeometry = function (geometry, force) {
  22021. if (!force && this.getGeometryByID(geometry.id)) {
  22022. return false;
  22023. }
  22024. this._geometries.push(geometry);
  22025. //notify the collision coordinator
  22026. this.collisionCoordinator.onGeometryAdded(geometry);
  22027. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22028. return true;
  22029. };
  22030. /**
  22031. * Removes an existing geometry
  22032. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22033. * @return {boolean} was the geometry removed or not
  22034. */
  22035. Scene.prototype.removeGeometry = function (geometry) {
  22036. var index = this._geometries.indexOf(geometry);
  22037. if (index > -1) {
  22038. this._geometries.splice(index, 1);
  22039. //notify the collision coordinator
  22040. this.collisionCoordinator.onGeometryDeleted(geometry);
  22041. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22042. return true;
  22043. }
  22044. return false;
  22045. };
  22046. Scene.prototype.getGeometries = function () {
  22047. return this._geometries;
  22048. };
  22049. /**
  22050. * Get the first added mesh found of a given ID
  22051. * @param {string} id - the id to search for
  22052. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22053. */
  22054. Scene.prototype.getMeshByID = function (id) {
  22055. for (var index = 0; index < this.meshes.length; index++) {
  22056. if (this.meshes[index].id === id) {
  22057. return this.meshes[index];
  22058. }
  22059. }
  22060. return null;
  22061. };
  22062. Scene.prototype.getMeshesByID = function (id) {
  22063. return this.meshes.filter(function (m) {
  22064. return m.id === id;
  22065. });
  22066. };
  22067. /**
  22068. * Get a mesh with its auto-generated unique id
  22069. * @param {number} uniqueId - the unique id to search for
  22070. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22071. */
  22072. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  22073. for (var index = 0; index < this.meshes.length; index++) {
  22074. if (this.meshes[index].uniqueId === uniqueId) {
  22075. return this.meshes[index];
  22076. }
  22077. }
  22078. return null;
  22079. };
  22080. /**
  22081. * Get a the last added mesh found of a given ID
  22082. * @param {string} id - the id to search for
  22083. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22084. */
  22085. Scene.prototype.getLastMeshByID = function (id) {
  22086. for (var index = this.meshes.length - 1; index >= 0; index--) {
  22087. if (this.meshes[index].id === id) {
  22088. return this.meshes[index];
  22089. }
  22090. }
  22091. return null;
  22092. };
  22093. /**
  22094. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  22095. * @param {string} id - the id to search for
  22096. * @return {BABYLON.Node|null} the node found or null if not found at all.
  22097. */
  22098. Scene.prototype.getLastEntryByID = function (id) {
  22099. var index;
  22100. for (index = this.meshes.length - 1; index >= 0; index--) {
  22101. if (this.meshes[index].id === id) {
  22102. return this.meshes[index];
  22103. }
  22104. }
  22105. for (index = this.cameras.length - 1; index >= 0; index--) {
  22106. if (this.cameras[index].id === id) {
  22107. return this.cameras[index];
  22108. }
  22109. }
  22110. for (index = this.lights.length - 1; index >= 0; index--) {
  22111. if (this.lights[index].id === id) {
  22112. return this.lights[index];
  22113. }
  22114. }
  22115. return null;
  22116. };
  22117. Scene.prototype.getNodeByID = function (id) {
  22118. var mesh = this.getMeshByID(id);
  22119. if (mesh) {
  22120. return mesh;
  22121. }
  22122. var light = this.getLightByID(id);
  22123. if (light) {
  22124. return light;
  22125. }
  22126. var camera = this.getCameraByID(id);
  22127. if (camera) {
  22128. return camera;
  22129. }
  22130. var bone = this.getBoneByID(id);
  22131. return bone;
  22132. };
  22133. Scene.prototype.getNodeByName = function (name) {
  22134. var mesh = this.getMeshByName(name);
  22135. if (mesh) {
  22136. return mesh;
  22137. }
  22138. var light = this.getLightByName(name);
  22139. if (light) {
  22140. return light;
  22141. }
  22142. var camera = this.getCameraByName(name);
  22143. if (camera) {
  22144. return camera;
  22145. }
  22146. var bone = this.getBoneByName(name);
  22147. return bone;
  22148. };
  22149. Scene.prototype.getMeshByName = function (name) {
  22150. for (var index = 0; index < this.meshes.length; index++) {
  22151. if (this.meshes[index].name === name) {
  22152. return this.meshes[index];
  22153. }
  22154. }
  22155. return null;
  22156. };
  22157. Scene.prototype.getSoundByName = function (name) {
  22158. var index;
  22159. if (BABYLON.AudioEngine) {
  22160. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  22161. if (this.mainSoundTrack.soundCollection[index].name === name) {
  22162. return this.mainSoundTrack.soundCollection[index];
  22163. }
  22164. }
  22165. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22166. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22167. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22168. return this.soundTracks[sdIndex].soundCollection[index];
  22169. }
  22170. }
  22171. }
  22172. }
  22173. return null;
  22174. };
  22175. Scene.prototype.getLastSkeletonByID = function (id) {
  22176. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22177. if (this.skeletons[index].id === id) {
  22178. return this.skeletons[index];
  22179. }
  22180. }
  22181. return null;
  22182. };
  22183. Scene.prototype.getSkeletonById = function (id) {
  22184. for (var index = 0; index < this.skeletons.length; index++) {
  22185. if (this.skeletons[index].id === id) {
  22186. return this.skeletons[index];
  22187. }
  22188. }
  22189. return null;
  22190. };
  22191. Scene.prototype.getSkeletonByName = function (name) {
  22192. for (var index = 0; index < this.skeletons.length; index++) {
  22193. if (this.skeletons[index].name === name) {
  22194. return this.skeletons[index];
  22195. }
  22196. }
  22197. return null;
  22198. };
  22199. Scene.prototype.getMorphTargetManagerById = function (id) {
  22200. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22201. if (this.morphTargetManagers[index].uniqueId === id) {
  22202. return this.morphTargetManagers[index];
  22203. }
  22204. }
  22205. return null;
  22206. };
  22207. Scene.prototype.isActiveMesh = function (mesh) {
  22208. return (this._activeMeshes.indexOf(mesh) !== -1);
  22209. };
  22210. /**
  22211. * Return a the first highlight layer of the scene with a given name.
  22212. * @param name The name of the highlight layer to look for.
  22213. * @return The highlight layer if found otherwise null.
  22214. */
  22215. Scene.prototype.getHighlightLayerByName = function (name) {
  22216. for (var index = 0; index < this.highlightLayers.length; index++) {
  22217. if (this.highlightLayers[index].name === name) {
  22218. return this.highlightLayers[index];
  22219. }
  22220. }
  22221. return null;
  22222. };
  22223. Object.defineProperty(Scene.prototype, "uid", {
  22224. /**
  22225. * Return a unique id as a string which can serve as an identifier for the scene
  22226. */
  22227. get: function () {
  22228. if (!this._uid) {
  22229. this._uid = BABYLON.Tools.RandomId();
  22230. }
  22231. return this._uid;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. /**
  22237. * Add an externaly attached data from its key.
  22238. * This method call will fail and return false, if such key already exists.
  22239. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22240. * @param key the unique key that identifies the data
  22241. * @param data the data object to associate to the key for this Engine instance
  22242. * @return true if no such key were already present and the data was added successfully, false otherwise
  22243. */
  22244. Scene.prototype.addExternalData = function (key, data) {
  22245. return this._externalData.add(key, data);
  22246. };
  22247. /**
  22248. * Get an externaly attached data from its key
  22249. * @param key the unique key that identifies the data
  22250. * @return the associated data, if present (can be null), or undefined if not present
  22251. */
  22252. Scene.prototype.getExternalData = function (key) {
  22253. return this._externalData.get(key);
  22254. };
  22255. /**
  22256. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22257. * @param key the unique key that identifies the data
  22258. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22259. * @return the associated data, can be null if the factory returned null.
  22260. */
  22261. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22262. return this._externalData.getOrAddWithFactory(key, factory);
  22263. };
  22264. /**
  22265. * Remove an externaly attached data from the Engine instance
  22266. * @param key the unique key that identifies the data
  22267. * @return true if the data was successfully removed, false if it doesn't exist
  22268. */
  22269. Scene.prototype.removeExternalData = function (key) {
  22270. return this._externalData.remove(key);
  22271. };
  22272. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22273. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22274. var material = subMesh.getMaterial();
  22275. if (mesh.showSubMeshesBoundingBox) {
  22276. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  22277. }
  22278. if (material) {
  22279. // Render targets
  22280. if (material.getRenderTargetTextures) {
  22281. if (this._processedMaterials.indexOf(material) === -1) {
  22282. this._processedMaterials.push(material);
  22283. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22284. }
  22285. }
  22286. // Dispatch
  22287. this._activeIndices.addCount(subMesh.indexCount, false);
  22288. this._renderingManager.dispatch(subMesh);
  22289. }
  22290. }
  22291. };
  22292. Scene.prototype._isInIntermediateRendering = function () {
  22293. return this._intermediateRendering;
  22294. };
  22295. Scene.prototype._evaluateActiveMeshes = function () {
  22296. this.activeCamera._activeMeshes.reset();
  22297. this._activeMeshes.reset();
  22298. this._renderingManager.reset();
  22299. this._processedMaterials.reset();
  22300. this._activeParticleSystems.reset();
  22301. this._activeSkeletons.reset();
  22302. this._softwareSkinnedMeshes.reset();
  22303. this._boundingBoxRenderer.reset();
  22304. this._edgesRenderers.reset();
  22305. // Meshes
  22306. var meshes;
  22307. var len;
  22308. if (this._selectionOctree) {
  22309. var selection = this._selectionOctree.select(this._frustumPlanes);
  22310. meshes = selection.data;
  22311. len = selection.length;
  22312. }
  22313. else {
  22314. len = this.meshes.length;
  22315. meshes = this.meshes;
  22316. }
  22317. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  22318. var mesh = meshes[meshIndex];
  22319. if (mesh.isBlocked) {
  22320. continue;
  22321. }
  22322. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22323. if (!mesh.isReady() || !mesh.isEnabled()) {
  22324. continue;
  22325. }
  22326. mesh.computeWorldMatrix();
  22327. // Intersections
  22328. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22329. this._meshesForIntersections.pushNoDuplicate(mesh);
  22330. }
  22331. // Switch to current LOD
  22332. var meshLOD = mesh.getLOD(this.activeCamera);
  22333. if (!meshLOD) {
  22334. continue;
  22335. }
  22336. mesh._preActivate();
  22337. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22338. this._activeMeshes.push(mesh);
  22339. this.activeCamera._activeMeshes.push(mesh);
  22340. mesh._activate(this._renderId);
  22341. this._activeMesh(mesh, meshLOD);
  22342. }
  22343. }
  22344. // Particle systems
  22345. this._particlesDuration.beginMonitoring();
  22346. var beforeParticlesDate = BABYLON.Tools.Now;
  22347. if (this.particlesEnabled) {
  22348. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  22349. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22350. var particleSystem = this.particleSystems[particleIndex];
  22351. if (!particleSystem.isStarted()) {
  22352. continue;
  22353. }
  22354. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  22355. this._activeParticleSystems.push(particleSystem);
  22356. particleSystem.animate();
  22357. this._renderingManager.dispatchParticles(particleSystem);
  22358. }
  22359. }
  22360. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  22361. }
  22362. this._particlesDuration.endMonitoring(false);
  22363. };
  22364. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22365. if (mesh.skeleton && this.skeletonsEnabled) {
  22366. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22367. mesh.skeleton.prepare();
  22368. }
  22369. if (!mesh.computeBonesUsingShaders) {
  22370. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22371. }
  22372. }
  22373. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22374. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  22375. }
  22376. if (sourceMesh._edgesRenderer) {
  22377. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  22378. }
  22379. if (mesh && mesh.subMeshes) {
  22380. // Submeshes Octrees
  22381. var len;
  22382. var subMeshes;
  22383. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  22384. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22385. len = intersections.length;
  22386. subMeshes = intersections.data;
  22387. }
  22388. else {
  22389. subMeshes = mesh.subMeshes;
  22390. len = subMeshes.length;
  22391. }
  22392. for (var subIndex = 0; subIndex < len; subIndex++) {
  22393. var subMesh = subMeshes[subIndex];
  22394. this._evaluateSubMesh(subMesh, mesh);
  22395. }
  22396. }
  22397. };
  22398. Scene.prototype.updateTransformMatrix = function (force) {
  22399. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22400. };
  22401. Scene.prototype._renderForCamera = function (camera) {
  22402. var engine = this._engine;
  22403. var startTime = BABYLON.Tools.Now;
  22404. this.activeCamera = camera;
  22405. if (!this.activeCamera)
  22406. throw new Error("Active camera not set");
  22407. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22408. // Viewport
  22409. engine.setViewport(this.activeCamera.viewport);
  22410. // Camera
  22411. this.resetCachedMaterial();
  22412. this._renderId++;
  22413. this.updateTransformMatrix();
  22414. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22415. // Meshes
  22416. this._evaluateActiveMeshesDuration.beginMonitoring();
  22417. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  22418. this._evaluateActiveMeshes();
  22419. this._evaluateActiveMeshesDuration.endMonitoring(false);
  22420. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  22421. // Software skinning
  22422. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22423. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22424. mesh.applySkeleton(mesh.skeleton);
  22425. }
  22426. // Render targets
  22427. this._renderTargetsDuration.beginMonitoring();
  22428. var needsRestoreFrameBuffer = false;
  22429. var beforeRenderTargetDate = BABYLON.Tools.Now;
  22430. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22431. this._intermediateRendering = true;
  22432. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22433. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22434. var renderTarget = this._renderTargets.data[renderIndex];
  22435. if (renderTarget._shouldRender()) {
  22436. this._renderId++;
  22437. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22438. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22439. }
  22440. }
  22441. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22442. this._intermediateRendering = false;
  22443. this._renderId++;
  22444. needsRestoreFrameBuffer = true; // Restore back buffer
  22445. }
  22446. // Render HighlightLayer Texture
  22447. var stencilState = this._engine.getStencilBuffer();
  22448. var renderhighlights = false;
  22449. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22450. this._intermediateRendering = true;
  22451. for (var i = 0; i < this.highlightLayers.length; i++) {
  22452. var highlightLayer = this.highlightLayers[i];
  22453. if (highlightLayer.shouldRender() &&
  22454. (!highlightLayer.camera ||
  22455. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22456. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22457. renderhighlights = true;
  22458. var renderTarget = highlightLayer._mainTexture;
  22459. if (renderTarget._shouldRender()) {
  22460. this._renderId++;
  22461. renderTarget.render(false, false);
  22462. needsRestoreFrameBuffer = true;
  22463. }
  22464. }
  22465. }
  22466. this._intermediateRendering = false;
  22467. this._renderId++;
  22468. }
  22469. if (needsRestoreFrameBuffer) {
  22470. engine.restoreDefaultFramebuffer();
  22471. }
  22472. this._renderTargetsDuration.endMonitoring(false);
  22473. // Prepare Frame
  22474. this.postProcessManager._prepareFrame();
  22475. this._renderDuration.beginMonitoring();
  22476. // Backgrounds
  22477. var layerIndex;
  22478. var layer;
  22479. if (this.layers.length) {
  22480. engine.setDepthBuffer(false);
  22481. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22482. layer = this.layers[layerIndex];
  22483. if (layer.isBackground) {
  22484. layer.render();
  22485. }
  22486. }
  22487. engine.setDepthBuffer(true);
  22488. }
  22489. // Render
  22490. BABYLON.Tools.StartPerformanceCounter("Main render");
  22491. // Activate HighlightLayer stencil
  22492. if (renderhighlights) {
  22493. this._engine.setStencilBuffer(true);
  22494. }
  22495. this._renderingManager.render(null, null, true, true);
  22496. // Restore HighlightLayer stencil
  22497. if (renderhighlights) {
  22498. this._engine.setStencilBuffer(stencilState);
  22499. }
  22500. BABYLON.Tools.EndPerformanceCounter("Main render");
  22501. // Bounding boxes
  22502. this._boundingBoxRenderer.render();
  22503. // Edges
  22504. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22505. this._edgesRenderers.data[edgesRendererIndex].render();
  22506. }
  22507. // Lens flares
  22508. if (this.lensFlaresEnabled) {
  22509. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22510. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22511. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22512. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22513. lensFlareSystem.render();
  22514. }
  22515. }
  22516. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22517. }
  22518. // Foregrounds
  22519. if (this.layers.length) {
  22520. engine.setDepthBuffer(false);
  22521. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22522. layer = this.layers[layerIndex];
  22523. if (!layer.isBackground) {
  22524. layer.render();
  22525. }
  22526. }
  22527. engine.setDepthBuffer(true);
  22528. }
  22529. // Highlight Layer
  22530. if (renderhighlights) {
  22531. engine.setDepthBuffer(false);
  22532. for (var i = 0; i < this.highlightLayers.length; i++) {
  22533. if (this.highlightLayers[i].shouldRender()) {
  22534. this.highlightLayers[i].render();
  22535. }
  22536. }
  22537. engine.setDepthBuffer(true);
  22538. }
  22539. this._renderDuration.endMonitoring(false);
  22540. // Finalize frame
  22541. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22542. // Update camera
  22543. this.activeCamera._updateFromScene();
  22544. // Reset some special arrays
  22545. this._renderTargets.reset();
  22546. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22547. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22548. };
  22549. Scene.prototype._processSubCameras = function (camera) {
  22550. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22551. this._renderForCamera(camera);
  22552. return;
  22553. }
  22554. // rig cameras
  22555. for (var index = 0; index < camera._rigCameras.length; index++) {
  22556. this._renderForCamera(camera._rigCameras[index]);
  22557. }
  22558. this.activeCamera = camera;
  22559. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22560. // Update camera
  22561. this.activeCamera._updateFromScene();
  22562. };
  22563. Scene.prototype._checkIntersections = function () {
  22564. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22565. var sourceMesh = this._meshesForIntersections.data[index];
  22566. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22567. var action = sourceMesh.actionManager.actions[actionIndex];
  22568. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22569. var parameters = action.getTriggerParameter();
  22570. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22571. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22572. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22573. if (areIntersecting && currentIntersectionInProgress === -1) {
  22574. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22575. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  22576. sourceMesh._intersectionsInProgress.push(otherMesh);
  22577. }
  22578. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22579. sourceMesh._intersectionsInProgress.push(otherMesh);
  22580. }
  22581. }
  22582. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22583. //They intersected, and now they don't.
  22584. //is this trigger an exit trigger? execute an event.
  22585. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22586. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  22587. }
  22588. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22589. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22590. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22591. }
  22592. }
  22593. }
  22594. }
  22595. }
  22596. };
  22597. Scene.prototype.render = function () {
  22598. if (this.isDisposed) {
  22599. return;
  22600. }
  22601. this._lastFrameDuration.beginMonitoring();
  22602. this._particlesDuration.fetchNewFrame();
  22603. this._spritesDuration.fetchNewFrame();
  22604. this._activeParticles.fetchNewFrame();
  22605. this._renderDuration.fetchNewFrame();
  22606. this._renderTargetsDuration.fetchNewFrame();
  22607. this._evaluateActiveMeshesDuration.fetchNewFrame();
  22608. this._totalVertices.fetchNewFrame();
  22609. this._activeIndices.fetchNewFrame();
  22610. this._activeBones.fetchNewFrame();
  22611. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  22612. this._meshesForIntersections.reset();
  22613. this.resetCachedMaterial();
  22614. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  22615. // Actions
  22616. if (this.actionManager) {
  22617. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  22618. }
  22619. //Simplification Queue
  22620. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22621. this.simplificationQueue.executeNext();
  22622. }
  22623. // Animations
  22624. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22625. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22626. this._animate();
  22627. // Physics
  22628. if (this._physicsEngine) {
  22629. BABYLON.Tools.StartPerformanceCounter("Physics");
  22630. this._physicsEngine._step(deltaTime / 1000.0);
  22631. BABYLON.Tools.EndPerformanceCounter("Physics");
  22632. }
  22633. // Before render
  22634. this.onBeforeRenderObservable.notifyObservers(this);
  22635. // Customs render targets
  22636. this._renderTargetsDuration.beginMonitoring();
  22637. var beforeRenderTargetDate = BABYLON.Tools.Now;
  22638. var engine = this.getEngine();
  22639. var currentActiveCamera = this.activeCamera;
  22640. if (this.renderTargetsEnabled) {
  22641. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22642. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22643. var renderTarget = this.customRenderTargets[customIndex];
  22644. if (renderTarget._shouldRender()) {
  22645. this._renderId++;
  22646. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22647. if (!this.activeCamera)
  22648. throw new Error("Active camera not set");
  22649. // Viewport
  22650. engine.setViewport(this.activeCamera.viewport);
  22651. // Camera
  22652. this.updateTransformMatrix();
  22653. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22654. }
  22655. }
  22656. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22657. this._renderId++;
  22658. }
  22659. if (this.customRenderTargets.length > 0) {
  22660. engine.restoreDefaultFramebuffer();
  22661. }
  22662. this._renderTargetsDuration.endMonitoring();
  22663. this.activeCamera = currentActiveCamera;
  22664. // Procedural textures
  22665. if (this.proceduralTexturesEnabled) {
  22666. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22667. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22668. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22669. if (proceduralTexture._shouldRender()) {
  22670. proceduralTexture.render();
  22671. }
  22672. }
  22673. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22674. }
  22675. // Clear
  22676. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  22677. // Shadows
  22678. if (this.shadowsEnabled) {
  22679. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22680. var light = this.lights[lightIndex];
  22681. var shadowGenerator = light.getShadowGenerator();
  22682. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  22683. this._renderTargets.push(shadowGenerator.getShadowMap());
  22684. }
  22685. }
  22686. }
  22687. // Depth renderer
  22688. if (this._depthRenderer) {
  22689. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22690. }
  22691. // RenderPipeline
  22692. this.postProcessRenderPipelineManager.update();
  22693. // Multi-cameras?
  22694. if (this.activeCameras.length > 0) {
  22695. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22696. if (cameraIndex > 0) {
  22697. this._engine.clear(null, false, true, true);
  22698. }
  22699. this._processSubCameras(this.activeCameras[cameraIndex]);
  22700. }
  22701. }
  22702. else {
  22703. if (!this.activeCamera) {
  22704. throw new Error("No camera defined");
  22705. }
  22706. this._processSubCameras(this.activeCamera);
  22707. }
  22708. // Intersection checks
  22709. this._checkIntersections();
  22710. // Update the audio listener attached to the camera
  22711. if (BABYLON.AudioEngine) {
  22712. this._updateAudioParameters();
  22713. }
  22714. // After render
  22715. if (this.afterRender) {
  22716. this.afterRender();
  22717. }
  22718. this.onAfterRenderObservable.notifyObservers(this);
  22719. // Cleaning
  22720. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22721. this._toBeDisposed.data[index].dispose();
  22722. this._toBeDisposed[index] = null;
  22723. }
  22724. this._toBeDisposed.reset();
  22725. if (this.dumpNextRenderTargets) {
  22726. this.dumpNextRenderTargets = false;
  22727. }
  22728. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  22729. this._lastFrameDuration.endMonitoring();
  22730. this._totalMeshesCounter.addCount(this.meshes.length, true);
  22731. this._totalLightsCounter.addCount(this.lights.length, true);
  22732. this._totalMaterialsCounter.addCount(this.materials.length, true);
  22733. this._totalTexturesCounter.addCount(this.textures.length, true);
  22734. this._activeBones.addCount(0, true);
  22735. this._activeIndices.addCount(0, true);
  22736. this._activeParticles.addCount(0, true);
  22737. };
  22738. Scene.prototype._updateAudioParameters = function () {
  22739. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22740. return;
  22741. }
  22742. var listeningCamera;
  22743. var audioEngine = BABYLON.Engine.audioEngine;
  22744. if (this.activeCameras.length > 0) {
  22745. listeningCamera = this.activeCameras[0];
  22746. }
  22747. else {
  22748. listeningCamera = this.activeCamera;
  22749. }
  22750. if (listeningCamera && audioEngine.canUseWebAudio) {
  22751. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22752. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22753. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22754. cameraDirection.normalize();
  22755. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22756. var i;
  22757. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22758. var sound = this.mainSoundTrack.soundCollection[i];
  22759. if (sound.useCustomAttenuation) {
  22760. sound.updateDistanceFromListener();
  22761. }
  22762. }
  22763. for (i = 0; i < this.soundTracks.length; i++) {
  22764. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22765. sound = this.soundTracks[i].soundCollection[j];
  22766. if (sound.useCustomAttenuation) {
  22767. sound.updateDistanceFromListener();
  22768. }
  22769. }
  22770. }
  22771. }
  22772. };
  22773. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22774. // Audio
  22775. get: function () {
  22776. return this._audioEnabled;
  22777. },
  22778. set: function (value) {
  22779. this._audioEnabled = value;
  22780. if (BABYLON.AudioEngine) {
  22781. if (this._audioEnabled) {
  22782. this._enableAudio();
  22783. }
  22784. else {
  22785. this._disableAudio();
  22786. }
  22787. }
  22788. },
  22789. enumerable: true,
  22790. configurable: true
  22791. });
  22792. Scene.prototype._disableAudio = function () {
  22793. var i;
  22794. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22795. this.mainSoundTrack.soundCollection[i].pause();
  22796. }
  22797. for (i = 0; i < this.soundTracks.length; i++) {
  22798. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22799. this.soundTracks[i].soundCollection[j].pause();
  22800. }
  22801. }
  22802. };
  22803. Scene.prototype._enableAudio = function () {
  22804. var i;
  22805. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22806. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22807. this.mainSoundTrack.soundCollection[i].play();
  22808. }
  22809. }
  22810. for (i = 0; i < this.soundTracks.length; i++) {
  22811. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22812. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22813. this.soundTracks[i].soundCollection[j].play();
  22814. }
  22815. }
  22816. }
  22817. };
  22818. Object.defineProperty(Scene.prototype, "headphone", {
  22819. get: function () {
  22820. return this._headphone;
  22821. },
  22822. set: function (value) {
  22823. this._headphone = value;
  22824. if (BABYLON.AudioEngine) {
  22825. if (this._headphone) {
  22826. this._switchAudioModeForHeadphones();
  22827. }
  22828. else {
  22829. this._switchAudioModeForNormalSpeakers();
  22830. }
  22831. }
  22832. },
  22833. enumerable: true,
  22834. configurable: true
  22835. });
  22836. Scene.prototype._switchAudioModeForHeadphones = function () {
  22837. this.mainSoundTrack.switchPanningModelToHRTF();
  22838. for (var i = 0; i < this.soundTracks.length; i++) {
  22839. this.soundTracks[i].switchPanningModelToHRTF();
  22840. }
  22841. };
  22842. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22843. this.mainSoundTrack.switchPanningModelToEqualPower();
  22844. for (var i = 0; i < this.soundTracks.length; i++) {
  22845. this.soundTracks[i].switchPanningModelToEqualPower();
  22846. }
  22847. };
  22848. Scene.prototype.enableDepthRenderer = function () {
  22849. if (this._depthRenderer) {
  22850. return this._depthRenderer;
  22851. }
  22852. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22853. return this._depthRenderer;
  22854. };
  22855. Scene.prototype.disableDepthRenderer = function () {
  22856. if (!this._depthRenderer) {
  22857. return;
  22858. }
  22859. this._depthRenderer.dispose();
  22860. this._depthRenderer = null;
  22861. };
  22862. Scene.prototype.freezeMaterials = function () {
  22863. for (var i = 0; i < this.materials.length; i++) {
  22864. this.materials[i].freeze();
  22865. }
  22866. };
  22867. Scene.prototype.unfreezeMaterials = function () {
  22868. for (var i = 0; i < this.materials.length; i++) {
  22869. this.materials[i].unfreeze();
  22870. }
  22871. };
  22872. Scene.prototype.dispose = function () {
  22873. this.beforeRender = null;
  22874. this.afterRender = null;
  22875. this.skeletons = [];
  22876. this.morphTargetManagers = [];
  22877. this._boundingBoxRenderer.dispose();
  22878. if (this._depthRenderer) {
  22879. this._depthRenderer.dispose();
  22880. }
  22881. // Smart arrays
  22882. if (this.activeCamera) {
  22883. this.activeCamera._activeMeshes.dispose();
  22884. this.activeCamera = null;
  22885. }
  22886. this._activeMeshes.dispose();
  22887. this._renderingManager.dispose();
  22888. this._processedMaterials.dispose();
  22889. this._activeParticleSystems.dispose();
  22890. this._activeSkeletons.dispose();
  22891. this._softwareSkinnedMeshes.dispose();
  22892. this._boundingBoxRenderer.dispose();
  22893. this._edgesRenderers.dispose();
  22894. this._meshesForIntersections.dispose();
  22895. this._toBeDisposed.dispose();
  22896. // Debug layer
  22897. if (this._debugLayer) {
  22898. this._debugLayer.hide();
  22899. }
  22900. // Events
  22901. this.onDisposeObservable.notifyObservers(this);
  22902. this.onDisposeObservable.clear();
  22903. this.onBeforeRenderObservable.clear();
  22904. this.onAfterRenderObservable.clear();
  22905. this.detachControl();
  22906. // Release sounds & sounds tracks
  22907. if (BABYLON.AudioEngine) {
  22908. this.disposeSounds();
  22909. }
  22910. // Detach cameras
  22911. var canvas = this._engine.getRenderingCanvas();
  22912. var index;
  22913. for (index = 0; index < this.cameras.length; index++) {
  22914. this.cameras[index].detachControl(canvas);
  22915. }
  22916. // Release lights
  22917. while (this.lights.length) {
  22918. this.lights[0].dispose();
  22919. }
  22920. // Release meshes
  22921. while (this.meshes.length) {
  22922. this.meshes[0].dispose(true);
  22923. }
  22924. // Release cameras
  22925. while (this.cameras.length) {
  22926. this.cameras[0].dispose();
  22927. }
  22928. // Release materials
  22929. while (this.materials.length) {
  22930. this.materials[0].dispose();
  22931. }
  22932. // Release particles
  22933. while (this.particleSystems.length) {
  22934. this.particleSystems[0].dispose();
  22935. }
  22936. // Release sprites
  22937. while (this.spriteManagers.length) {
  22938. this.spriteManagers[0].dispose();
  22939. }
  22940. // Release layers
  22941. while (this.layers.length) {
  22942. this.layers[0].dispose();
  22943. }
  22944. while (this.highlightLayers.length) {
  22945. this.highlightLayers[0].dispose();
  22946. }
  22947. // Release textures
  22948. while (this.textures.length) {
  22949. this.textures[0].dispose();
  22950. }
  22951. // Post-processes
  22952. this.postProcessManager.dispose();
  22953. // Physics
  22954. if (this._physicsEngine) {
  22955. this.disablePhysicsEngine();
  22956. }
  22957. // Remove from engine
  22958. index = this._engine.scenes.indexOf(this);
  22959. if (index > -1) {
  22960. this._engine.scenes.splice(index, 1);
  22961. }
  22962. this._engine.wipeCaches();
  22963. this._engine = null;
  22964. };
  22965. Object.defineProperty(Scene.prototype, "isDisposed", {
  22966. get: function () {
  22967. return !this._engine;
  22968. },
  22969. enumerable: true,
  22970. configurable: true
  22971. });
  22972. // Release sounds & sounds tracks
  22973. Scene.prototype.disposeSounds = function () {
  22974. this.mainSoundTrack.dispose();
  22975. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22976. this.soundTracks[scIndex].dispose();
  22977. }
  22978. };
  22979. // Octrees
  22980. Scene.prototype.getWorldExtends = function () {
  22981. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22982. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22983. for (var index = 0; index < this.meshes.length; index++) {
  22984. var mesh = this.meshes[index];
  22985. mesh.computeWorldMatrix(true);
  22986. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  22987. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  22988. BABYLON.Tools.CheckExtends(minBox, min, max);
  22989. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22990. }
  22991. return {
  22992. min: min,
  22993. max: max
  22994. };
  22995. };
  22996. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22997. if (maxCapacity === void 0) { maxCapacity = 64; }
  22998. if (maxDepth === void 0) { maxDepth = 2; }
  22999. if (!this._selectionOctree) {
  23000. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23001. }
  23002. var worldExtends = this.getWorldExtends();
  23003. // Update octree
  23004. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23005. return this._selectionOctree;
  23006. };
  23007. // Picking
  23008. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23009. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23010. var engine = this._engine;
  23011. if (!camera) {
  23012. if (!this.activeCamera)
  23013. throw new Error("Active camera not set");
  23014. camera = this.activeCamera;
  23015. }
  23016. var cameraViewport = camera.viewport;
  23017. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23018. // Moving coordinates to local viewport world
  23019. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23020. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23021. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23022. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  23023. };
  23024. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23025. var engine = this._engine;
  23026. if (!camera) {
  23027. if (!this.activeCamera)
  23028. throw new Error("Active camera not set");
  23029. camera = this.activeCamera;
  23030. }
  23031. var cameraViewport = camera.viewport;
  23032. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23033. var identity = BABYLON.Matrix.Identity();
  23034. // Moving coordinates to local viewport world
  23035. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23036. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23037. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23038. };
  23039. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23040. var pickingInfo = null;
  23041. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23042. var mesh = this.meshes[meshIndex];
  23043. if (predicate) {
  23044. if (!predicate(mesh)) {
  23045. continue;
  23046. }
  23047. }
  23048. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23049. continue;
  23050. }
  23051. var world = mesh.getWorldMatrix();
  23052. var ray = rayFunction(world);
  23053. var result = mesh.intersects(ray, fastCheck);
  23054. if (!result || !result.hit)
  23055. continue;
  23056. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23057. continue;
  23058. pickingInfo = result;
  23059. if (fastCheck) {
  23060. break;
  23061. }
  23062. }
  23063. return pickingInfo || new BABYLON.PickingInfo();
  23064. };
  23065. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23066. var pickingInfos = new Array();
  23067. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23068. var mesh = this.meshes[meshIndex];
  23069. if (predicate) {
  23070. if (!predicate(mesh)) {
  23071. continue;
  23072. }
  23073. }
  23074. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23075. continue;
  23076. }
  23077. var world = mesh.getWorldMatrix();
  23078. var ray = rayFunction(world);
  23079. var result = mesh.intersects(ray, false);
  23080. if (!result || !result.hit)
  23081. continue;
  23082. pickingInfos.push(result);
  23083. }
  23084. return pickingInfos;
  23085. };
  23086. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23087. var pickingInfo = null;
  23088. camera = camera || this.activeCamera;
  23089. if (this.spriteManagers.length > 0) {
  23090. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23091. var spriteManager = this.spriteManagers[spriteIndex];
  23092. if (!spriteManager.isPickable) {
  23093. continue;
  23094. }
  23095. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23096. if (!result || !result.hit)
  23097. continue;
  23098. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23099. continue;
  23100. pickingInfo = result;
  23101. if (fastCheck) {
  23102. break;
  23103. }
  23104. }
  23105. }
  23106. return pickingInfo || new BABYLON.PickingInfo();
  23107. };
  23108. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  23109. /// <param name="x">X position on screen</param>
  23110. /// <param name="y">Y position on screen</param>
  23111. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  23112. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  23113. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  23114. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23115. var _this = this;
  23116. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  23117. };
  23118. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  23119. /// <param name="x">X position on screen</param>
  23120. /// <param name="y">Y position on screen</param>
  23121. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  23122. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  23123. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  23124. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23125. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  23126. };
  23127. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23128. var _this = this;
  23129. return this._internalPick(function (world) {
  23130. if (!_this._pickWithRayInverseMatrix) {
  23131. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23132. }
  23133. world.invertToRef(_this._pickWithRayInverseMatrix);
  23134. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  23135. }, predicate, fastCheck);
  23136. };
  23137. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  23138. /// <param name="x">X position on screen</param>
  23139. /// <param name="y">Y position on screen</param>
  23140. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  23141. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  23142. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23143. var _this = this;
  23144. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  23145. };
  23146. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  23147. /// <param name="ray">Ray to use</param>
  23148. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  23149. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23150. var _this = this;
  23151. return this._internalMultiPick(function (world) {
  23152. if (!_this._pickWithRayInverseMatrix) {
  23153. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23154. }
  23155. world.invertToRef(_this._pickWithRayInverseMatrix);
  23156. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  23157. }, predicate);
  23158. };
  23159. Scene.prototype.setPointerOverMesh = function (mesh) {
  23160. if (this._pointerOverMesh === mesh) {
  23161. return;
  23162. }
  23163. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23164. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23165. }
  23166. this._pointerOverMesh = mesh;
  23167. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23168. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23169. }
  23170. };
  23171. Scene.prototype.getPointerOverMesh = function () {
  23172. return this._pointerOverMesh;
  23173. };
  23174. Scene.prototype.setPointerOverSprite = function (sprite) {
  23175. if (this._pointerOverSprite === sprite) {
  23176. return;
  23177. }
  23178. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23179. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23180. }
  23181. this._pointerOverSprite = sprite;
  23182. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23183. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23184. }
  23185. };
  23186. Scene.prototype.getPointerOverSprite = function () {
  23187. return this._pointerOverSprite;
  23188. };
  23189. // Physics
  23190. Scene.prototype.getPhysicsEngine = function () {
  23191. return this._physicsEngine;
  23192. };
  23193. /**
  23194. * Enables physics to the current scene
  23195. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23196. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23197. * @return {boolean} was the physics engine initialized
  23198. */
  23199. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23200. if (this._physicsEngine) {
  23201. return true;
  23202. }
  23203. try {
  23204. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23205. return true;
  23206. }
  23207. catch (e) {
  23208. BABYLON.Tools.Error(e.message);
  23209. return false;
  23210. }
  23211. };
  23212. Scene.prototype.disablePhysicsEngine = function () {
  23213. if (!this._physicsEngine) {
  23214. return;
  23215. }
  23216. this._physicsEngine.dispose();
  23217. this._physicsEngine = undefined;
  23218. };
  23219. Scene.prototype.isPhysicsEnabled = function () {
  23220. return this._physicsEngine !== undefined;
  23221. };
  23222. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23223. var mesh = compound.parts[0].mesh;
  23224. mesh.physicsImpostor.dispose();
  23225. mesh.physicsImpostor = null;
  23226. };
  23227. // Misc.
  23228. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  23229. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23230. // Light
  23231. if (this.lights.length === 0) {
  23232. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23233. }
  23234. // Camera
  23235. if (!this.activeCamera) {
  23236. // Compute position
  23237. var worldExtends = this.getWorldExtends();
  23238. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  23239. var camera;
  23240. if (createArcRotateCamera) {
  23241. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  23242. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  23243. camera.lowerRadiusLimit = 0.5;
  23244. camera.setTarget(worldCenter);
  23245. }
  23246. else {
  23247. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  23248. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  23249. camera.setTarget(worldCenter);
  23250. }
  23251. camera.minZ = 0.1;
  23252. var maxDist = worldExtends.max.subtract(worldExtends.min).length();
  23253. camera.wheelPrecision = 100.0 / maxDist;
  23254. this.activeCamera = camera;
  23255. }
  23256. };
  23257. // Tags
  23258. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23259. if (tagsQuery === undefined) {
  23260. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23261. return list;
  23262. }
  23263. var listByTags = [];
  23264. forEach = forEach || (function (item) { return; });
  23265. for (var i in list) {
  23266. var item = list[i];
  23267. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23268. listByTags.push(item);
  23269. forEach(item);
  23270. }
  23271. }
  23272. return listByTags;
  23273. };
  23274. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23275. return this._getByTags(this.meshes, tagsQuery, forEach);
  23276. };
  23277. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23278. return this._getByTags(this.cameras, tagsQuery, forEach);
  23279. };
  23280. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23281. return this._getByTags(this.lights, tagsQuery, forEach);
  23282. };
  23283. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23284. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23285. };
  23286. /**
  23287. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23288. * This allowed control for front to back rendering or reversly depending of the special needs.
  23289. *
  23290. * @param renderingGroupId The rendering group id corresponding to its index
  23291. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23292. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23293. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23294. */
  23295. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23296. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23297. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23298. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23299. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23300. };
  23301. /**
  23302. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23303. *
  23304. * @param renderingGroupId The rendering group id corresponding to its index
  23305. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23306. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23307. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23308. */
  23309. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23310. if (depth === void 0) { depth = true; }
  23311. if (stencil === void 0) { stencil = true; }
  23312. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23313. };
  23314. /**
  23315. * Will flag all materials as dirty to trigger new shader compilation
  23316. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23317. */
  23318. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23319. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23320. var material = _a[_i];
  23321. if (predicate && !predicate(material)) {
  23322. continue;
  23323. }
  23324. material.markAsDirty(flag);
  23325. }
  23326. };
  23327. return Scene;
  23328. }());
  23329. // Statics
  23330. Scene._FOGMODE_NONE = 0;
  23331. Scene._FOGMODE_EXP = 1;
  23332. Scene._FOGMODE_EXP2 = 2;
  23333. Scene._FOGMODE_LINEAR = 3;
  23334. Scene.MinDeltaTime = 1.0;
  23335. Scene.MaxDeltaTime = 1000.0;
  23336. Scene.DragMovementThreshold = 10; // in pixels
  23337. Scene.LongPressDelay = 500; // in milliseconds
  23338. Scene.DoubleClickDelay = 300; // in milliseconds
  23339. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  23340. BABYLON.Scene = Scene;
  23341. })(BABYLON || (BABYLON = {}));
  23342. //# sourceMappingURL=babylon.scene.js.map
  23343. var BABYLON;
  23344. (function (BABYLON) {
  23345. var Buffer = (function () {
  23346. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23347. if (engine instanceof BABYLON.Mesh) {
  23348. this._engine = engine.getScene().getEngine();
  23349. }
  23350. else {
  23351. this._engine = engine;
  23352. }
  23353. this._updatable = updatable;
  23354. this._data = data;
  23355. this._strideSize = stride;
  23356. if (!postponeInternalCreation) {
  23357. this.create();
  23358. }
  23359. this._instanced = instanced;
  23360. }
  23361. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23362. // a lot of these parameters are ignored as they are overriden by the buffer
  23363. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23364. };
  23365. // Properties
  23366. Buffer.prototype.isUpdatable = function () {
  23367. return this._updatable;
  23368. };
  23369. Buffer.prototype.getData = function () {
  23370. return this._data;
  23371. };
  23372. Buffer.prototype.getBuffer = function () {
  23373. return this._buffer;
  23374. };
  23375. Buffer.prototype.getStrideSize = function () {
  23376. return this._strideSize;
  23377. };
  23378. Buffer.prototype.getIsInstanced = function () {
  23379. return this._instanced;
  23380. };
  23381. // Methods
  23382. Buffer.prototype.create = function (data) {
  23383. if (!data && this._buffer) {
  23384. return; // nothing to do
  23385. }
  23386. data = data || this._data;
  23387. if (!this._buffer) {
  23388. if (this._updatable) {
  23389. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23390. this._data = data;
  23391. }
  23392. else {
  23393. this._buffer = this._engine.createVertexBuffer(data);
  23394. }
  23395. }
  23396. else if (this._updatable) {
  23397. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23398. this._data = data;
  23399. }
  23400. };
  23401. Buffer.prototype.update = function (data) {
  23402. this.create(data);
  23403. };
  23404. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23405. if (!this._buffer) {
  23406. return;
  23407. }
  23408. if (this._updatable) {
  23409. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23410. this._data = null;
  23411. }
  23412. };
  23413. Buffer.prototype.dispose = function () {
  23414. if (!this._buffer) {
  23415. return;
  23416. }
  23417. if (this._engine._releaseBuffer(this._buffer)) {
  23418. this._buffer = null;
  23419. }
  23420. };
  23421. return Buffer;
  23422. }());
  23423. BABYLON.Buffer = Buffer;
  23424. })(BABYLON || (BABYLON = {}));
  23425. //# sourceMappingURL=babylon.buffer.js.map
  23426. var BABYLON;
  23427. (function (BABYLON) {
  23428. var VertexBuffer = (function () {
  23429. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23430. if (!stride) {
  23431. // Deduce stride from kind
  23432. switch (kind) {
  23433. case VertexBuffer.PositionKind:
  23434. stride = 3;
  23435. break;
  23436. case VertexBuffer.NormalKind:
  23437. stride = 3;
  23438. break;
  23439. case VertexBuffer.UVKind:
  23440. case VertexBuffer.UV2Kind:
  23441. case VertexBuffer.UV3Kind:
  23442. case VertexBuffer.UV4Kind:
  23443. case VertexBuffer.UV5Kind:
  23444. case VertexBuffer.UV6Kind:
  23445. stride = 2;
  23446. break;
  23447. case VertexBuffer.TangentKind:
  23448. case VertexBuffer.ColorKind:
  23449. stride = 4;
  23450. break;
  23451. case VertexBuffer.MatricesIndicesKind:
  23452. case VertexBuffer.MatricesIndicesExtraKind:
  23453. stride = 4;
  23454. break;
  23455. case VertexBuffer.MatricesWeightsKind:
  23456. case VertexBuffer.MatricesWeightsExtraKind:
  23457. stride = 4;
  23458. break;
  23459. }
  23460. }
  23461. if (data instanceof BABYLON.Buffer) {
  23462. if (!stride) {
  23463. stride = data.getStrideSize();
  23464. }
  23465. this._buffer = data;
  23466. this._ownsBuffer = false;
  23467. }
  23468. else {
  23469. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23470. this._ownsBuffer = true;
  23471. }
  23472. this._stride = stride;
  23473. this._offset = offset ? offset : 0;
  23474. this._size = size ? size : stride;
  23475. this._kind = kind;
  23476. }
  23477. /**
  23478. * Returns the kind of the VertexBuffer (string).
  23479. */
  23480. VertexBuffer.prototype.getKind = function () {
  23481. return this._kind;
  23482. };
  23483. // Properties
  23484. /**
  23485. * Boolean : is the VertexBuffer updatable ?
  23486. */
  23487. VertexBuffer.prototype.isUpdatable = function () {
  23488. return this._buffer.isUpdatable();
  23489. };
  23490. /**
  23491. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23492. */
  23493. VertexBuffer.prototype.getData = function () {
  23494. return this._buffer.getData();
  23495. };
  23496. /**
  23497. * Returns the WebGLBuffer associated to the VertexBuffer.
  23498. */
  23499. VertexBuffer.prototype.getBuffer = function () {
  23500. return this._buffer.getBuffer();
  23501. };
  23502. /**
  23503. * Returns the stride of the VertexBuffer (integer).
  23504. */
  23505. VertexBuffer.prototype.getStrideSize = function () {
  23506. return this._stride;
  23507. };
  23508. /**
  23509. * Returns the offset (integer).
  23510. */
  23511. VertexBuffer.prototype.getOffset = function () {
  23512. return this._offset;
  23513. };
  23514. /**
  23515. * Returns the VertexBuffer total size (integer).
  23516. */
  23517. VertexBuffer.prototype.getSize = function () {
  23518. return this._size;
  23519. };
  23520. /**
  23521. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23522. */
  23523. VertexBuffer.prototype.getIsInstanced = function () {
  23524. return this._buffer.getIsInstanced();
  23525. };
  23526. // Methods
  23527. /**
  23528. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23529. * Returns the created WebGLBuffer.
  23530. */
  23531. VertexBuffer.prototype.create = function (data) {
  23532. return this._buffer.create(data);
  23533. };
  23534. /**
  23535. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23536. * Returns the updated WebGLBuffer.
  23537. */
  23538. VertexBuffer.prototype.update = function (data) {
  23539. return this._buffer.update(data);
  23540. };
  23541. /**
  23542. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23543. * Returns the directly updated WebGLBuffer.
  23544. */
  23545. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23546. return this._buffer.updateDirectly(data, offset);
  23547. };
  23548. /**
  23549. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23550. */
  23551. VertexBuffer.prototype.dispose = function () {
  23552. if (this._ownsBuffer) {
  23553. this._buffer.dispose();
  23554. }
  23555. };
  23556. Object.defineProperty(VertexBuffer, "PositionKind", {
  23557. get: function () {
  23558. return VertexBuffer._PositionKind;
  23559. },
  23560. enumerable: true,
  23561. configurable: true
  23562. });
  23563. Object.defineProperty(VertexBuffer, "NormalKind", {
  23564. get: function () {
  23565. return VertexBuffer._NormalKind;
  23566. },
  23567. enumerable: true,
  23568. configurable: true
  23569. });
  23570. Object.defineProperty(VertexBuffer, "TangentKind", {
  23571. get: function () {
  23572. return VertexBuffer._TangentKind;
  23573. },
  23574. enumerable: true,
  23575. configurable: true
  23576. });
  23577. Object.defineProperty(VertexBuffer, "UVKind", {
  23578. get: function () {
  23579. return VertexBuffer._UVKind;
  23580. },
  23581. enumerable: true,
  23582. configurable: true
  23583. });
  23584. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23585. get: function () {
  23586. return VertexBuffer._UV2Kind;
  23587. },
  23588. enumerable: true,
  23589. configurable: true
  23590. });
  23591. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23592. get: function () {
  23593. return VertexBuffer._UV3Kind;
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23599. get: function () {
  23600. return VertexBuffer._UV4Kind;
  23601. },
  23602. enumerable: true,
  23603. configurable: true
  23604. });
  23605. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23606. get: function () {
  23607. return VertexBuffer._UV5Kind;
  23608. },
  23609. enumerable: true,
  23610. configurable: true
  23611. });
  23612. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23613. get: function () {
  23614. return VertexBuffer._UV6Kind;
  23615. },
  23616. enumerable: true,
  23617. configurable: true
  23618. });
  23619. Object.defineProperty(VertexBuffer, "ColorKind", {
  23620. get: function () {
  23621. return VertexBuffer._ColorKind;
  23622. },
  23623. enumerable: true,
  23624. configurable: true
  23625. });
  23626. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23627. get: function () {
  23628. return VertexBuffer._MatricesIndicesKind;
  23629. },
  23630. enumerable: true,
  23631. configurable: true
  23632. });
  23633. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23634. get: function () {
  23635. return VertexBuffer._MatricesWeightsKind;
  23636. },
  23637. enumerable: true,
  23638. configurable: true
  23639. });
  23640. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23641. get: function () {
  23642. return VertexBuffer._MatricesIndicesExtraKind;
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23648. get: function () {
  23649. return VertexBuffer._MatricesWeightsExtraKind;
  23650. },
  23651. enumerable: true,
  23652. configurable: true
  23653. });
  23654. return VertexBuffer;
  23655. }());
  23656. // Enums
  23657. VertexBuffer._PositionKind = "position";
  23658. VertexBuffer._NormalKind = "normal";
  23659. VertexBuffer._TangentKind = "tangent";
  23660. VertexBuffer._UVKind = "uv";
  23661. VertexBuffer._UV2Kind = "uv2";
  23662. VertexBuffer._UV3Kind = "uv3";
  23663. VertexBuffer._UV4Kind = "uv4";
  23664. VertexBuffer._UV5Kind = "uv5";
  23665. VertexBuffer._UV6Kind = "uv6";
  23666. VertexBuffer._ColorKind = "color";
  23667. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23668. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23669. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23670. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23671. BABYLON.VertexBuffer = VertexBuffer;
  23672. })(BABYLON || (BABYLON = {}));
  23673. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23674. var BABYLON;
  23675. (function (BABYLON) {
  23676. /**
  23677. * Creates an instance based on a source mesh.
  23678. */
  23679. var InstancedMesh = (function (_super) {
  23680. __extends(InstancedMesh, _super);
  23681. function InstancedMesh(name, source) {
  23682. var _this = _super.call(this, name, source.getScene()) || this;
  23683. source.instances.push(_this);
  23684. _this._sourceMesh = source;
  23685. _this.position.copyFrom(source.position);
  23686. _this.rotation.copyFrom(source.rotation);
  23687. _this.scaling.copyFrom(source.scaling);
  23688. if (source.rotationQuaternion) {
  23689. _this.rotationQuaternion = source.rotationQuaternion.clone();
  23690. }
  23691. _this.infiniteDistance = source.infiniteDistance;
  23692. _this.setPivotMatrix(source.getPivotMatrix());
  23693. _this.refreshBoundingInfo();
  23694. _this._syncSubMeshes();
  23695. return _this;
  23696. }
  23697. /**
  23698. * Returns the string "InstancedMesh".
  23699. */
  23700. InstancedMesh.prototype.getClassName = function () {
  23701. return "InstancedMesh";
  23702. };
  23703. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  23704. // Methods
  23705. get: function () {
  23706. return this._sourceMesh.receiveShadows;
  23707. },
  23708. enumerable: true,
  23709. configurable: true
  23710. });
  23711. Object.defineProperty(InstancedMesh.prototype, "material", {
  23712. get: function () {
  23713. return this._sourceMesh.material;
  23714. },
  23715. enumerable: true,
  23716. configurable: true
  23717. });
  23718. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  23719. get: function () {
  23720. return this._sourceMesh.visibility;
  23721. },
  23722. enumerable: true,
  23723. configurable: true
  23724. });
  23725. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  23726. get: function () {
  23727. return this._sourceMesh.skeleton;
  23728. },
  23729. enumerable: true,
  23730. configurable: true
  23731. });
  23732. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  23733. get: function () {
  23734. return this._sourceMesh.renderingGroupId;
  23735. },
  23736. enumerable: true,
  23737. configurable: true
  23738. });
  23739. /**
  23740. * Returns the total number of vertices (integer).
  23741. */
  23742. InstancedMesh.prototype.getTotalVertices = function () {
  23743. return this._sourceMesh.getTotalVertices();
  23744. };
  23745. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  23746. get: function () {
  23747. return this._sourceMesh;
  23748. },
  23749. enumerable: true,
  23750. configurable: true
  23751. });
  23752. /**
  23753. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  23754. */
  23755. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23756. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  23757. };
  23758. /**
  23759. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23760. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23761. * The `data` are either a numeric array either a Float32Array.
  23762. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23763. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  23764. * Note that a new underlying VertexBuffer object is created each call.
  23765. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23766. *
  23767. * Possible `kind` values :
  23768. * - BABYLON.VertexBuffer.PositionKind
  23769. * - BABYLON.VertexBuffer.UVKind
  23770. * - BABYLON.VertexBuffer.UV2Kind
  23771. * - BABYLON.VertexBuffer.UV3Kind
  23772. * - BABYLON.VertexBuffer.UV4Kind
  23773. * - BABYLON.VertexBuffer.UV5Kind
  23774. * - BABYLON.VertexBuffer.UV6Kind
  23775. * - BABYLON.VertexBuffer.ColorKind
  23776. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23777. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23778. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23779. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23780. *
  23781. * Returns the Mesh.
  23782. */
  23783. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23784. if (this.sourceMesh) {
  23785. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  23786. }
  23787. return this.sourceMesh;
  23788. };
  23789. /**
  23790. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23791. * If the mesh has no geometry, it is simply returned as it is.
  23792. * The `data` are either a numeric array either a Float32Array.
  23793. * No new underlying VertexBuffer object is created.
  23794. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23795. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23796. *
  23797. * Possible `kind` values :
  23798. * - BABYLON.VertexBuffer.PositionKind
  23799. * - BABYLON.VertexBuffer.UVKind
  23800. * - BABYLON.VertexBuffer.UV2Kind
  23801. * - BABYLON.VertexBuffer.UV3Kind
  23802. * - BABYLON.VertexBuffer.UV4Kind
  23803. * - BABYLON.VertexBuffer.UV5Kind
  23804. * - BABYLON.VertexBuffer.UV6Kind
  23805. * - BABYLON.VertexBuffer.ColorKind
  23806. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23807. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23808. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23809. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23810. *
  23811. * Returns the Mesh.
  23812. */
  23813. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23814. if (this.sourceMesh) {
  23815. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  23816. }
  23817. return this.sourceMesh;
  23818. };
  23819. /**
  23820. * Sets the mesh indices.
  23821. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23822. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23823. * This method creates a new index buffer each call.
  23824. * Returns the Mesh.
  23825. */
  23826. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  23827. if (this.sourceMesh) {
  23828. this.sourceMesh.setIndices(indices, totalVertices);
  23829. }
  23830. return this.sourceMesh;
  23831. };
  23832. /**
  23833. * Boolean : True if the mesh owns the requested kind of data.
  23834. */
  23835. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  23836. return this._sourceMesh.isVerticesDataPresent(kind);
  23837. };
  23838. /**
  23839. * Returns an array of indices (IndicesArray).
  23840. */
  23841. InstancedMesh.prototype.getIndices = function () {
  23842. return this._sourceMesh.getIndices();
  23843. };
  23844. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  23845. get: function () {
  23846. return this._sourceMesh._positions;
  23847. },
  23848. enumerable: true,
  23849. configurable: true
  23850. });
  23851. /**
  23852. * Sets a new updated BoundingInfo to the mesh.
  23853. * Returns the mesh.
  23854. */
  23855. InstancedMesh.prototype.refreshBoundingInfo = function () {
  23856. var meshBB = this._sourceMesh.getBoundingInfo();
  23857. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  23858. this._updateBoundingInfo();
  23859. return this;
  23860. };
  23861. InstancedMesh.prototype._preActivate = function () {
  23862. if (this._currentLOD) {
  23863. this._currentLOD._preActivate();
  23864. }
  23865. return this;
  23866. };
  23867. InstancedMesh.prototype._activate = function (renderId) {
  23868. if (this._currentLOD) {
  23869. this._currentLOD._registerInstanceForRenderId(this, renderId);
  23870. }
  23871. return this;
  23872. };
  23873. /**
  23874. * Returns the current associated LOD AbstractMesh.
  23875. */
  23876. InstancedMesh.prototype.getLOD = function (camera) {
  23877. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  23878. if (this._currentLOD === this.sourceMesh) {
  23879. return this;
  23880. }
  23881. return this._currentLOD;
  23882. };
  23883. InstancedMesh.prototype._syncSubMeshes = function () {
  23884. this.releaseSubMeshes();
  23885. if (this._sourceMesh.subMeshes) {
  23886. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  23887. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  23888. }
  23889. }
  23890. return this;
  23891. };
  23892. InstancedMesh.prototype._generatePointsArray = function () {
  23893. return this._sourceMesh._generatePointsArray();
  23894. };
  23895. /**
  23896. * Creates a new InstancedMesh from the current mesh.
  23897. * - name (string) : the cloned mesh name
  23898. * - newParent (optional Node) : the optional Node to parent the clone to.
  23899. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  23900. *
  23901. * Returns the clone.
  23902. */
  23903. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  23904. var result = this._sourceMesh.createInstance(name);
  23905. // Deep copy
  23906. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  23907. // Bounding info
  23908. this.refreshBoundingInfo();
  23909. // Parent
  23910. if (newParent) {
  23911. result.parent = newParent;
  23912. }
  23913. if (!doNotCloneChildren) {
  23914. // Children
  23915. for (var index = 0; index < this.getScene().meshes.length; index++) {
  23916. var mesh = this.getScene().meshes[index];
  23917. if (mesh.parent === this) {
  23918. mesh.clone(mesh.name, result);
  23919. }
  23920. }
  23921. }
  23922. result.computeWorldMatrix(true);
  23923. return result;
  23924. };
  23925. /**
  23926. * Disposes the InstancedMesh.
  23927. * Returns nothing.
  23928. */
  23929. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  23930. // Remove from mesh
  23931. var index = this._sourceMesh.instances.indexOf(this);
  23932. this._sourceMesh.instances.splice(index, 1);
  23933. _super.prototype.dispose.call(this, doNotRecurse);
  23934. };
  23935. return InstancedMesh;
  23936. }(BABYLON.AbstractMesh));
  23937. BABYLON.InstancedMesh = InstancedMesh;
  23938. })(BABYLON || (BABYLON = {}));
  23939. //# sourceMappingURL=babylon.instancedMesh.js.map
  23940. var BABYLON;
  23941. (function (BABYLON) {
  23942. var _InstancesBatch = (function () {
  23943. function _InstancesBatch() {
  23944. this.mustReturn = false;
  23945. this.visibleInstances = new Array();
  23946. this.renderSelf = new Array();
  23947. }
  23948. return _InstancesBatch;
  23949. }());
  23950. BABYLON._InstancesBatch = _InstancesBatch;
  23951. var Mesh = (function (_super) {
  23952. __extends(Mesh, _super);
  23953. /**
  23954. * @constructor
  23955. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23956. * @param {Scene} scene The scene to add this mesh to.
  23957. * @param {Node} parent The parent of this mesh, if it has one
  23958. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23959. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23960. * When false, achieved by calling a clone(), also passing False.
  23961. * This will make creation of children, recursive.
  23962. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23963. */
  23964. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23965. if (parent === void 0) { parent = null; }
  23966. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23967. var _this = _super.call(this, name, scene) || this;
  23968. // Events
  23969. /**
  23970. * An event triggered before rendering the mesh
  23971. * @type {BABYLON.Observable}
  23972. */
  23973. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23974. /**
  23975. * An event triggered after rendering the mesh
  23976. * @type {BABYLON.Observable}
  23977. */
  23978. _this.onAfterRenderObservable = new BABYLON.Observable();
  23979. /**
  23980. * An event triggered before drawing the mesh
  23981. * @type {BABYLON.Observable}
  23982. */
  23983. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23984. // Members
  23985. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23986. _this.instances = new Array();
  23987. _this._LODLevels = new Array();
  23988. _this._visibleInstances = {};
  23989. _this._renderIdForInstances = new Array();
  23990. _this._batchCache = new _InstancesBatch();
  23991. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23992. _this._sideOrientation = Mesh._DEFAULTSIDE;
  23993. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23994. // Will be used to save a source mesh reference, If any
  23995. _this._source = null;
  23996. if (source) {
  23997. // Source mesh
  23998. _this._source = source;
  23999. // Geometry
  24000. if (source._geometry) {
  24001. source._geometry.applyToMesh(_this);
  24002. }
  24003. // Deep copy
  24004. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  24005. // Parent
  24006. _this.parent = source.parent;
  24007. // Pivot
  24008. _this.setPivotMatrix(source.getPivotMatrix());
  24009. _this.id = name + "." + source.id;
  24010. // Material
  24011. _this.material = source.material;
  24012. var index;
  24013. if (!doNotCloneChildren) {
  24014. // Children
  24015. for (index = 0; index < scene.meshes.length; index++) {
  24016. var mesh = scene.meshes[index];
  24017. if (mesh.parent === source) {
  24018. // doNotCloneChildren is always going to be False
  24019. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  24020. }
  24021. }
  24022. }
  24023. // Physics clone
  24024. var physicsEngine = _this.getScene().getPhysicsEngine();
  24025. if (clonePhysicsImpostor && physicsEngine) {
  24026. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24027. if (impostor) {
  24028. _this.physicsImpostor = impostor.clone(_this);
  24029. }
  24030. }
  24031. // Particles
  24032. for (index = 0; index < scene.particleSystems.length; index++) {
  24033. var system = scene.particleSystems[index];
  24034. if (system.emitter === source) {
  24035. system.clone(system.name, _this);
  24036. }
  24037. }
  24038. _this.computeWorldMatrix(true);
  24039. }
  24040. // Parent
  24041. if (parent !== null) {
  24042. _this.parent = parent;
  24043. }
  24044. return _this;
  24045. }
  24046. Object.defineProperty(Mesh, "FRONTSIDE", {
  24047. /**
  24048. * Mesh side orientation : usually the external or front surface
  24049. */
  24050. get: function () {
  24051. return Mesh._FRONTSIDE;
  24052. },
  24053. enumerable: true,
  24054. configurable: true
  24055. });
  24056. Object.defineProperty(Mesh, "BACKSIDE", {
  24057. /**
  24058. * Mesh side orientation : usually the internal or back surface
  24059. */
  24060. get: function () {
  24061. return Mesh._BACKSIDE;
  24062. },
  24063. enumerable: true,
  24064. configurable: true
  24065. });
  24066. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24067. /**
  24068. * Mesh side orientation : both internal and external or front and back surfaces
  24069. */
  24070. get: function () {
  24071. return Mesh._DOUBLESIDE;
  24072. },
  24073. enumerable: true,
  24074. configurable: true
  24075. });
  24076. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24077. /**
  24078. * Mesh side orientation : by default, `FRONTSIDE`
  24079. */
  24080. get: function () {
  24081. return Mesh._DEFAULTSIDE;
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. Object.defineProperty(Mesh, "NO_CAP", {
  24087. /**
  24088. * Mesh cap setting : no cap
  24089. */
  24090. get: function () {
  24091. return Mesh._NO_CAP;
  24092. },
  24093. enumerable: true,
  24094. configurable: true
  24095. });
  24096. Object.defineProperty(Mesh, "CAP_START", {
  24097. /**
  24098. * Mesh cap setting : one cap at the beginning of the mesh
  24099. */
  24100. get: function () {
  24101. return Mesh._CAP_START;
  24102. },
  24103. enumerable: true,
  24104. configurable: true
  24105. });
  24106. Object.defineProperty(Mesh, "CAP_END", {
  24107. /**
  24108. * Mesh cap setting : one cap at the end of the mesh
  24109. */
  24110. get: function () {
  24111. return Mesh._CAP_END;
  24112. },
  24113. enumerable: true,
  24114. configurable: true
  24115. });
  24116. Object.defineProperty(Mesh, "CAP_ALL", {
  24117. /**
  24118. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24119. */
  24120. get: function () {
  24121. return Mesh._CAP_ALL;
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24127. set: function (callback) {
  24128. if (this._onBeforeDrawObserver) {
  24129. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24130. }
  24131. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24137. get: function () {
  24138. return this._morphTargetManager;
  24139. },
  24140. set: function (value) {
  24141. if (this._morphTargetManager === value) {
  24142. return;
  24143. }
  24144. this._morphTargetManager = value;
  24145. this._syncGeometryWithMorphTargetManager();
  24146. },
  24147. enumerable: true,
  24148. configurable: true
  24149. });
  24150. Object.defineProperty(Mesh.prototype, "source", {
  24151. get: function () {
  24152. return this._source;
  24153. },
  24154. enumerable: true,
  24155. configurable: true
  24156. });
  24157. // Methods
  24158. /**
  24159. * Returns the string "Mesh".
  24160. */
  24161. Mesh.prototype.getClassName = function () {
  24162. return "Mesh";
  24163. };
  24164. /**
  24165. * Returns a string.
  24166. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24167. */
  24168. Mesh.prototype.toString = function (fullDetails) {
  24169. var ret = _super.prototype.toString.call(this, fullDetails);
  24170. ret += ", n vertices: " + this.getTotalVertices();
  24171. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24172. if (this.animations) {
  24173. for (var i = 0; i < this.animations.length; i++) {
  24174. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24175. }
  24176. }
  24177. if (fullDetails) {
  24178. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  24179. }
  24180. return ret;
  24181. };
  24182. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24183. /**
  24184. * True if the mesh has some Levels Of Details (LOD).
  24185. * Returns a boolean.
  24186. */
  24187. get: function () {
  24188. return this._LODLevels.length > 0;
  24189. },
  24190. enumerable: true,
  24191. configurable: true
  24192. });
  24193. Mesh.prototype._sortLODLevels = function () {
  24194. this._LODLevels.sort(function (a, b) {
  24195. if (a.distance < b.distance) {
  24196. return 1;
  24197. }
  24198. if (a.distance > b.distance) {
  24199. return -1;
  24200. }
  24201. return 0;
  24202. });
  24203. };
  24204. /**
  24205. * Add a mesh as LOD level triggered at the given distance.
  24206. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24207. * @param {number} distance The distance from the center of the object to show this level
  24208. * @param {Mesh} mesh The mesh to be added as LOD level
  24209. * @return {Mesh} This mesh (for chaining)
  24210. */
  24211. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24212. if (mesh && mesh._masterMesh) {
  24213. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24214. return this;
  24215. }
  24216. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  24217. this._LODLevels.push(level);
  24218. if (mesh) {
  24219. mesh._masterMesh = this;
  24220. }
  24221. this._sortLODLevels();
  24222. return this;
  24223. };
  24224. /**
  24225. * Returns the LOD level mesh at the passed distance or null if not found.
  24226. * It is related to the method `addLODLevel(distance, mesh)`.
  24227. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24228. * Returns an object Mesh or `null`.
  24229. */
  24230. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24231. for (var index = 0; index < this._LODLevels.length; index++) {
  24232. var level = this._LODLevels[index];
  24233. if (level.distance === distance) {
  24234. return level.mesh;
  24235. }
  24236. }
  24237. return null;
  24238. };
  24239. /**
  24240. * Remove a mesh from the LOD array
  24241. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24242. * @param {Mesh} mesh The mesh to be removed.
  24243. * @return {Mesh} This mesh (for chaining)
  24244. */
  24245. Mesh.prototype.removeLODLevel = function (mesh) {
  24246. for (var index = 0; index < this._LODLevels.length; index++) {
  24247. if (this._LODLevels[index].mesh === mesh) {
  24248. this._LODLevels.splice(index, 1);
  24249. if (mesh) {
  24250. mesh._masterMesh = null;
  24251. }
  24252. }
  24253. }
  24254. this._sortLODLevels();
  24255. return this;
  24256. };
  24257. /**
  24258. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  24259. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24260. */
  24261. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  24262. if (!this._LODLevels || this._LODLevels.length === 0) {
  24263. return this;
  24264. }
  24265. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  24266. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  24267. if (this.onLODLevelSelection) {
  24268. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  24269. }
  24270. return this;
  24271. }
  24272. for (var index = 0; index < this._LODLevels.length; index++) {
  24273. var level = this._LODLevels[index];
  24274. if (level.distance < distanceToCamera) {
  24275. if (level.mesh) {
  24276. level.mesh._preActivate();
  24277. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  24278. }
  24279. if (this.onLODLevelSelection) {
  24280. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  24281. }
  24282. return level.mesh;
  24283. }
  24284. }
  24285. if (this.onLODLevelSelection) {
  24286. this.onLODLevelSelection(distanceToCamera, this, this);
  24287. }
  24288. return this;
  24289. };
  24290. Object.defineProperty(Mesh.prototype, "geometry", {
  24291. /**
  24292. * Returns the mesh internal Geometry object.
  24293. */
  24294. get: function () {
  24295. return this._geometry;
  24296. },
  24297. enumerable: true,
  24298. configurable: true
  24299. });
  24300. /**
  24301. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  24302. */
  24303. Mesh.prototype.getTotalVertices = function () {
  24304. if (!this._geometry) {
  24305. return 0;
  24306. }
  24307. return this._geometry.getTotalVertices();
  24308. };
  24309. /**
  24310. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  24311. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  24312. * Returns null if the mesh has no geometry or no vertex buffer.
  24313. * Possible `kind` values :
  24314. * - BABYLON.VertexBuffer.PositionKind
  24315. * - BABYLON.VertexBuffer.UVKind
  24316. * - BABYLON.VertexBuffer.UV2Kind
  24317. * - BABYLON.VertexBuffer.UV3Kind
  24318. * - BABYLON.VertexBuffer.UV4Kind
  24319. * - BABYLON.VertexBuffer.UV5Kind
  24320. * - BABYLON.VertexBuffer.UV6Kind
  24321. * - BABYLON.VertexBuffer.ColorKind
  24322. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24323. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24324. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24325. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24326. */
  24327. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  24328. if (!this._geometry) {
  24329. return null;
  24330. }
  24331. return this._geometry.getVerticesData(kind, copyWhenShared);
  24332. };
  24333. /**
  24334. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24335. * Returns `undefined` if the mesh has no geometry.
  24336. * Possible `kind` values :
  24337. * - BABYLON.VertexBuffer.PositionKind
  24338. * - BABYLON.VertexBuffer.UVKind
  24339. * - BABYLON.VertexBuffer.UV2Kind
  24340. * - BABYLON.VertexBuffer.UV3Kind
  24341. * - BABYLON.VertexBuffer.UV4Kind
  24342. * - BABYLON.VertexBuffer.UV5Kind
  24343. * - BABYLON.VertexBuffer.UV6Kind
  24344. * - BABYLON.VertexBuffer.ColorKind
  24345. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24346. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24347. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24348. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24349. */
  24350. Mesh.prototype.getVertexBuffer = function (kind) {
  24351. if (!this._geometry) {
  24352. return undefined;
  24353. }
  24354. return this._geometry.getVertexBuffer(kind);
  24355. };
  24356. /**
  24357. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24358. * Possible `kind` values :
  24359. * - BABYLON.VertexBuffer.PositionKind
  24360. * - BABYLON.VertexBuffer.UVKind
  24361. * - BABYLON.VertexBuffer.UV2Kind
  24362. * - BABYLON.VertexBuffer.UV3Kind
  24363. * - BABYLON.VertexBuffer.UV4Kind
  24364. * - BABYLON.VertexBuffer.UV5Kind
  24365. * - BABYLON.VertexBuffer.UV6Kind
  24366. * - BABYLON.VertexBuffer.ColorKind
  24367. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24368. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24369. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24370. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24371. */
  24372. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24373. if (!this._geometry) {
  24374. if (this._delayInfo) {
  24375. return this._delayInfo.indexOf(kind) !== -1;
  24376. }
  24377. return false;
  24378. }
  24379. return this._geometry.isVerticesDataPresent(kind);
  24380. };
  24381. /**
  24382. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24383. * Possible `kind` values :
  24384. * - BABYLON.VertexBuffer.PositionKind
  24385. * - BABYLON.VertexBuffer.UVKind
  24386. * - BABYLON.VertexBuffer.UV2Kind
  24387. * - BABYLON.VertexBuffer.UV3Kind
  24388. * - BABYLON.VertexBuffer.UV4Kind
  24389. * - BABYLON.VertexBuffer.UV5Kind
  24390. * - BABYLON.VertexBuffer.UV6Kind
  24391. * - BABYLON.VertexBuffer.ColorKind
  24392. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24393. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24394. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24395. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24396. */
  24397. Mesh.prototype.getVerticesDataKinds = function () {
  24398. if (!this._geometry) {
  24399. var result = [];
  24400. if (this._delayInfo) {
  24401. this._delayInfo.forEach(function (kind, index, array) {
  24402. result.push(kind);
  24403. });
  24404. }
  24405. return result;
  24406. }
  24407. return this._geometry.getVerticesDataKinds();
  24408. };
  24409. /**
  24410. * Returns a positive integer : the total number of indices in this mesh geometry.
  24411. * Returns zero if the mesh has no geometry.
  24412. */
  24413. Mesh.prototype.getTotalIndices = function () {
  24414. if (!this._geometry) {
  24415. return 0;
  24416. }
  24417. return this._geometry.getTotalIndices();
  24418. };
  24419. /**
  24420. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  24421. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  24422. * Returns an empty array if the mesh has no geometry.
  24423. */
  24424. Mesh.prototype.getIndices = function (copyWhenShared) {
  24425. if (!this._geometry) {
  24426. return [];
  24427. }
  24428. return this._geometry.getIndices(copyWhenShared);
  24429. };
  24430. Object.defineProperty(Mesh.prototype, "isBlocked", {
  24431. get: function () {
  24432. return this._masterMesh !== null && this._masterMesh !== undefined;
  24433. },
  24434. enumerable: true,
  24435. configurable: true
  24436. });
  24437. /**
  24438. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  24439. */
  24440. Mesh.prototype.isReady = function () {
  24441. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24442. return false;
  24443. }
  24444. return _super.prototype.isReady.call(this);
  24445. };
  24446. /**
  24447. * Boolean : true if the mesh has been disposed.
  24448. */
  24449. Mesh.prototype.isDisposed = function () {
  24450. return this._isDisposed;
  24451. };
  24452. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  24453. get: function () {
  24454. return this._sideOrientation;
  24455. },
  24456. /**
  24457. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  24458. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  24459. */
  24460. set: function (sideO) {
  24461. this._sideOrientation = sideO;
  24462. },
  24463. enumerable: true,
  24464. configurable: true
  24465. });
  24466. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  24467. /**
  24468. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  24469. * This property is pertinent only for updatable parametric shapes.
  24470. */
  24471. get: function () {
  24472. return this._areNormalsFrozen;
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. /**
  24478. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24479. * It has no effect at all on other shapes.
  24480. * It prevents the mesh normals from being recomputed on next `positions` array update.
  24481. * Returns the Mesh.
  24482. */
  24483. Mesh.prototype.freezeNormals = function () {
  24484. this._areNormalsFrozen = true;
  24485. return this;
  24486. };
  24487. /**
  24488. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24489. * It has no effect at all on other shapes.
  24490. * It reactivates the mesh normals computation if it was previously frozen.
  24491. * Returns the Mesh.
  24492. */
  24493. Mesh.prototype.unfreezeNormals = function () {
  24494. this._areNormalsFrozen = false;
  24495. return this;
  24496. };
  24497. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  24498. /**
  24499. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  24500. */
  24501. set: function (count) {
  24502. this._overridenInstanceCount = count;
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. // Methods
  24508. Mesh.prototype._preActivate = function () {
  24509. var sceneRenderId = this.getScene().getRenderId();
  24510. if (this._preActivateId === sceneRenderId) {
  24511. return this;
  24512. }
  24513. this._preActivateId = sceneRenderId;
  24514. this._visibleInstances = null;
  24515. return this;
  24516. };
  24517. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  24518. if (this._visibleInstances) {
  24519. this._visibleInstances.intermediateDefaultRenderId = renderId;
  24520. }
  24521. return this;
  24522. };
  24523. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  24524. if (!this._visibleInstances) {
  24525. this._visibleInstances = {};
  24526. this._visibleInstances.defaultRenderId = renderId;
  24527. this._visibleInstances.selfDefaultRenderId = this._renderId;
  24528. }
  24529. if (!this._visibleInstances[renderId]) {
  24530. this._visibleInstances[renderId] = new Array();
  24531. }
  24532. this._visibleInstances[renderId].push(instance);
  24533. return this;
  24534. };
  24535. /**
  24536. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  24537. * This means the mesh underlying bounding box and sphere are recomputed.
  24538. * Returns the Mesh.
  24539. */
  24540. Mesh.prototype.refreshBoundingInfo = function () {
  24541. if (this._boundingInfo.isLocked) {
  24542. return;
  24543. }
  24544. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24545. if (data) {
  24546. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  24547. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24548. }
  24549. if (this.subMeshes) {
  24550. for (var index = 0; index < this.subMeshes.length; index++) {
  24551. this.subMeshes[index].refreshBoundingInfo();
  24552. }
  24553. }
  24554. this._updateBoundingInfo();
  24555. return this;
  24556. };
  24557. Mesh.prototype._createGlobalSubMesh = function () {
  24558. var totalVertices = this.getTotalVertices();
  24559. if (!totalVertices || !this.getIndices()) {
  24560. return null;
  24561. }
  24562. this.releaseSubMeshes();
  24563. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  24564. };
  24565. Mesh.prototype.subdivide = function (count) {
  24566. if (count < 1) {
  24567. return;
  24568. }
  24569. var totalIndices = this.getTotalIndices();
  24570. var subdivisionSize = (totalIndices / count) | 0;
  24571. var offset = 0;
  24572. // Ensure that subdivisionSize is a multiple of 3
  24573. while (subdivisionSize % 3 !== 0) {
  24574. subdivisionSize++;
  24575. }
  24576. this.releaseSubMeshes();
  24577. for (var index = 0; index < count; index++) {
  24578. if (offset >= totalIndices) {
  24579. break;
  24580. }
  24581. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  24582. offset += subdivisionSize;
  24583. }
  24584. this.synchronizeInstances();
  24585. };
  24586. /**
  24587. * Sets the vertex data of the mesh geometry for the requested `kind`.
  24588. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  24589. * The `data` are either a numeric array either a Float32Array.
  24590. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  24591. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  24592. * Note that a new underlying VertexBuffer object is created each call.
  24593. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  24594. *
  24595. * Possible `kind` values :
  24596. * - BABYLON.VertexBuffer.PositionKind
  24597. * - BABYLON.VertexBuffer.UVKind
  24598. * - BABYLON.VertexBuffer.UV2Kind
  24599. * - BABYLON.VertexBuffer.UV3Kind
  24600. * - BABYLON.VertexBuffer.UV4Kind
  24601. * - BABYLON.VertexBuffer.UV5Kind
  24602. * - BABYLON.VertexBuffer.UV6Kind
  24603. * - BABYLON.VertexBuffer.ColorKind
  24604. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24605. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24606. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24607. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24608. *
  24609. * Returns the Mesh.
  24610. */
  24611. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24612. if (!this._geometry) {
  24613. var vertexData = new BABYLON.VertexData();
  24614. vertexData.set(data, kind);
  24615. var scene = this.getScene();
  24616. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24617. }
  24618. else {
  24619. this._geometry.setVerticesData(kind, data, updatable, stride);
  24620. }
  24621. return this;
  24622. };
  24623. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  24624. if (updatable === void 0) { updatable = true; }
  24625. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  24626. return;
  24627. }
  24628. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  24629. };
  24630. /**
  24631. * Sets the mesh VertexBuffer.
  24632. * Returns the Mesh.
  24633. */
  24634. Mesh.prototype.setVerticesBuffer = function (buffer) {
  24635. if (!this._geometry) {
  24636. var scene = this.getScene();
  24637. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  24638. }
  24639. this._geometry.setVerticesBuffer(buffer);
  24640. return this;
  24641. };
  24642. /**
  24643. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24644. * If the mesh has no geometry, it is simply returned as it is.
  24645. * The `data` are either a numeric array either a Float32Array.
  24646. * No new underlying VertexBuffer object is created.
  24647. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  24648. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24649. *
  24650. * Possible `kind` values :
  24651. * - BABYLON.VertexBuffer.PositionKind
  24652. * - BABYLON.VertexBuffer.UVKind
  24653. * - BABYLON.VertexBuffer.UV2Kind
  24654. * - BABYLON.VertexBuffer.UV3Kind
  24655. * - BABYLON.VertexBuffer.UV4Kind
  24656. * - BABYLON.VertexBuffer.UV5Kind
  24657. * - BABYLON.VertexBuffer.UV6Kind
  24658. * - BABYLON.VertexBuffer.ColorKind
  24659. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24660. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24661. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24662. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24663. *
  24664. * Returns the Mesh.
  24665. */
  24666. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24667. if (!this._geometry) {
  24668. return;
  24669. }
  24670. if (!makeItUnique) {
  24671. this._geometry.updateVerticesData(kind, data, updateExtends);
  24672. }
  24673. else {
  24674. this.makeGeometryUnique();
  24675. this.updateVerticesData(kind, data, updateExtends, false);
  24676. }
  24677. return this;
  24678. };
  24679. /**
  24680. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24681. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24682. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24683. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24684. * Returns the Mesh.
  24685. */
  24686. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24687. if (computeNormals === void 0) { computeNormals = true; }
  24688. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24689. positionFunction(positions);
  24690. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24691. if (computeNormals) {
  24692. var indices = this.getIndices();
  24693. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24694. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24695. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24696. }
  24697. return this;
  24698. };
  24699. /**
  24700. * Creates a un-shared specific occurence of the geometry for the mesh.
  24701. * Returns the Mesh.
  24702. */
  24703. Mesh.prototype.makeGeometryUnique = function () {
  24704. if (!this._geometry) {
  24705. return;
  24706. }
  24707. var oldGeometry = this._geometry;
  24708. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24709. oldGeometry.releaseForMesh(this, true);
  24710. geometry.applyToMesh(this);
  24711. return this;
  24712. };
  24713. /**
  24714. * Sets the mesh indices.
  24715. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24716. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24717. * This method creates a new index buffer each call.
  24718. * Returns the Mesh.
  24719. */
  24720. Mesh.prototype.setIndices = function (indices, totalVertices) {
  24721. if (!this._geometry) {
  24722. var vertexData = new BABYLON.VertexData();
  24723. vertexData.indices = indices;
  24724. var scene = this.getScene();
  24725. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  24726. }
  24727. else {
  24728. this._geometry.setIndices(indices, totalVertices);
  24729. }
  24730. return this;
  24731. };
  24732. /**
  24733. * Invert the geometry to move from a right handed system to a left handed one.
  24734. * Returns the Mesh.
  24735. */
  24736. Mesh.prototype.toLeftHanded = function () {
  24737. if (!this._geometry) {
  24738. return;
  24739. }
  24740. this._geometry.toLeftHanded();
  24741. return this;
  24742. };
  24743. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24744. var engine = this.getScene().getEngine();
  24745. // Wireframe
  24746. var indexToBind;
  24747. if (this._unIndexed) {
  24748. indexToBind = null;
  24749. }
  24750. else {
  24751. switch (fillMode) {
  24752. case BABYLON.Material.PointFillMode:
  24753. indexToBind = null;
  24754. break;
  24755. case BABYLON.Material.WireFrameFillMode:
  24756. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24757. break;
  24758. default:
  24759. case BABYLON.Material.TriangleFillMode:
  24760. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24761. break;
  24762. }
  24763. }
  24764. // VBOs
  24765. this._geometry._bind(effect, indexToBind);
  24766. return this;
  24767. };
  24768. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24769. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24770. return this;
  24771. }
  24772. this.onBeforeDrawObservable.notifyObservers(this);
  24773. var engine = this.getScene().getEngine();
  24774. // Draw order
  24775. switch (fillMode) {
  24776. case BABYLON.Material.PointFillMode:
  24777. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24778. break;
  24779. case BABYLON.Material.WireFrameFillMode:
  24780. if (this._unIndexed) {
  24781. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24782. }
  24783. else {
  24784. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  24785. }
  24786. break;
  24787. default:
  24788. if (this._unIndexed) {
  24789. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24790. }
  24791. else {
  24792. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24793. }
  24794. }
  24795. return this;
  24796. };
  24797. /**
  24798. * Registers for this mesh a javascript function called just before the rendering process.
  24799. * This function is passed the current mesh.
  24800. * Return the Mesh.
  24801. */
  24802. Mesh.prototype.registerBeforeRender = function (func) {
  24803. this.onBeforeRenderObservable.add(func);
  24804. return this;
  24805. };
  24806. /**
  24807. * Disposes a previously registered javascript function called before the rendering.
  24808. * This function is passed the current mesh.
  24809. * Returns the Mesh.
  24810. */
  24811. Mesh.prototype.unregisterBeforeRender = function (func) {
  24812. this.onBeforeRenderObservable.removeCallback(func);
  24813. return this;
  24814. };
  24815. /**
  24816. * Registers for this mesh a javascript function called just after the rendering is complete.
  24817. * This function is passed the current mesh.
  24818. * Returns the Mesh.
  24819. */
  24820. Mesh.prototype.registerAfterRender = function (func) {
  24821. this.onAfterRenderObservable.add(func);
  24822. return this;
  24823. };
  24824. /**
  24825. * Disposes a previously registered javascript function called after the rendering.
  24826. * This function is passed the current mesh.
  24827. * Return the Mesh.
  24828. */
  24829. Mesh.prototype.unregisterAfterRender = function (func) {
  24830. this.onAfterRenderObservable.removeCallback(func);
  24831. return this;
  24832. };
  24833. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24834. var scene = this.getScene();
  24835. this._batchCache.mustReturn = false;
  24836. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24837. this._batchCache.visibleInstances[subMeshId] = null;
  24838. if (this._visibleInstances) {
  24839. var currentRenderId = scene.getRenderId();
  24840. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24841. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24842. var selfRenderId = this._renderId;
  24843. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24844. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24845. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24846. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24847. }
  24848. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  24849. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24850. this._batchCache.mustReturn = true;
  24851. return this._batchCache;
  24852. }
  24853. if (currentRenderId !== selfRenderId) {
  24854. this._batchCache.renderSelf[subMeshId] = false;
  24855. }
  24856. }
  24857. this._renderIdForInstances[subMeshId] = currentRenderId;
  24858. }
  24859. return this._batchCache;
  24860. };
  24861. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24862. var visibleInstances = batch.visibleInstances[subMesh._id];
  24863. var matricesCount = visibleInstances.length + 1;
  24864. var bufferSize = matricesCount * 16 * 4;
  24865. var currentInstancesBufferSize = this._instancesBufferSize;
  24866. var instancesBuffer = this._instancesBuffer;
  24867. while (this._instancesBufferSize < bufferSize) {
  24868. this._instancesBufferSize *= 2;
  24869. }
  24870. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24871. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24872. }
  24873. var offset = 0;
  24874. var instancesCount = 0;
  24875. var world = this.getWorldMatrix();
  24876. if (batch.renderSelf[subMesh._id]) {
  24877. world.copyToArray(this._instancesData, offset);
  24878. offset += 16;
  24879. instancesCount++;
  24880. }
  24881. if (visibleInstances) {
  24882. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24883. var instance = visibleInstances[instanceIndex];
  24884. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24885. offset += 16;
  24886. instancesCount++;
  24887. }
  24888. }
  24889. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24890. if (instancesBuffer) {
  24891. instancesBuffer.dispose();
  24892. }
  24893. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24894. this._instancesBuffer = instancesBuffer;
  24895. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24896. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24897. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24898. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24899. }
  24900. else {
  24901. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24902. }
  24903. this.geometry._bind(effect);
  24904. this._draw(subMesh, fillMode, instancesCount);
  24905. engine.unbindInstanceAttributes();
  24906. return this;
  24907. };
  24908. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24909. var scene = this.getScene();
  24910. var engine = scene.getEngine();
  24911. if (hardwareInstancedRendering) {
  24912. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24913. }
  24914. else {
  24915. if (batch.renderSelf[subMesh._id]) {
  24916. // Draw
  24917. if (onBeforeDraw) {
  24918. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24919. }
  24920. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24921. }
  24922. if (batch.visibleInstances[subMesh._id]) {
  24923. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24924. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24925. // World
  24926. var world = instance.getWorldMatrix();
  24927. if (onBeforeDraw) {
  24928. onBeforeDraw(true, world, effectiveMaterial);
  24929. }
  24930. // Draw
  24931. this._draw(subMesh, fillMode);
  24932. }
  24933. }
  24934. }
  24935. return this;
  24936. };
  24937. /**
  24938. * Triggers the draw call for the mesh.
  24939. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24940. * Returns the Mesh.
  24941. */
  24942. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24943. var scene = this.getScene();
  24944. // Managing instances
  24945. var batch = this._getInstancesRenderList(subMesh._id);
  24946. if (batch.mustReturn) {
  24947. return this;
  24948. }
  24949. // Checking geometry state
  24950. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24951. return this;
  24952. }
  24953. var callbackIndex;
  24954. this.onBeforeRenderObservable.notifyObservers(this);
  24955. var engine = scene.getEngine();
  24956. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24957. // Material
  24958. var effectiveMaterial = subMesh.getMaterial();
  24959. if (!effectiveMaterial) {
  24960. return this;
  24961. }
  24962. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24963. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24964. return this;
  24965. }
  24966. }
  24967. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24968. return this;
  24969. }
  24970. // Outline - step 1
  24971. var savedDepthWrite = engine.getDepthWrite();
  24972. if (this.renderOutline) {
  24973. engine.setDepthWrite(false);
  24974. scene.getOutlineRenderer().render(subMesh, batch);
  24975. engine.setDepthWrite(savedDepthWrite);
  24976. }
  24977. var effect;
  24978. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24979. effect = subMesh.effect;
  24980. }
  24981. else {
  24982. effect = effectiveMaterial.getEffect();
  24983. }
  24984. effectiveMaterial._preBind(effect);
  24985. // Bind
  24986. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  24987. this._bind(subMesh, effect, fillMode);
  24988. var world = this.getWorldMatrix();
  24989. if (effectiveMaterial.storeEffectOnSubMeshes) {
  24990. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24991. }
  24992. else {
  24993. effectiveMaterial.bind(world, this);
  24994. }
  24995. // Alpha mode
  24996. if (enableAlphaMode) {
  24997. engine.setAlphaMode(effectiveMaterial.alphaMode);
  24998. }
  24999. // Draw
  25000. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  25001. // Unbind
  25002. effectiveMaterial.unbind();
  25003. // Outline - step 2
  25004. if (this.renderOutline && savedDepthWrite) {
  25005. engine.setDepthWrite(true);
  25006. engine.setColorWrite(false);
  25007. scene.getOutlineRenderer().render(subMesh, batch);
  25008. engine.setColorWrite(true);
  25009. }
  25010. // Overlay
  25011. if (this.renderOverlay) {
  25012. var currentMode = engine.getAlphaMode();
  25013. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25014. scene.getOutlineRenderer().render(subMesh, batch, true);
  25015. engine.setAlphaMode(currentMode);
  25016. }
  25017. this.onAfterRenderObservable.notifyObservers(this);
  25018. return this;
  25019. };
  25020. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25021. if (isInstance) {
  25022. effectiveMaterial.bindOnlyWorldMatrix(world);
  25023. }
  25024. return this;
  25025. };
  25026. /**
  25027. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25028. */
  25029. Mesh.prototype.getEmittedParticleSystems = function () {
  25030. var results = new Array();
  25031. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25032. var particleSystem = this.getScene().particleSystems[index];
  25033. if (particleSystem.emitter === this) {
  25034. results.push(particleSystem);
  25035. }
  25036. }
  25037. return results;
  25038. };
  25039. /**
  25040. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  25041. */
  25042. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  25043. var results = new Array();
  25044. var descendants = this.getDescendants();
  25045. descendants.push(this);
  25046. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25047. var particleSystem = this.getScene().particleSystems[index];
  25048. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  25049. results.push(particleSystem);
  25050. }
  25051. }
  25052. return results;
  25053. };
  25054. Mesh.prototype._checkDelayState = function () {
  25055. var scene = this.getScene();
  25056. if (this._geometry) {
  25057. this._geometry.load(scene);
  25058. }
  25059. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25061. this._queueLoad(this, scene);
  25062. }
  25063. return this;
  25064. };
  25065. Mesh.prototype._queueLoad = function (mesh, scene) {
  25066. var _this = this;
  25067. scene._addPendingData(mesh);
  25068. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  25069. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25070. if (data instanceof ArrayBuffer) {
  25071. _this._delayLoadingFunction(data, _this);
  25072. }
  25073. else {
  25074. _this._delayLoadingFunction(JSON.parse(data), _this);
  25075. }
  25076. _this.instances.forEach(function (instance) {
  25077. instance._syncSubMeshes();
  25078. });
  25079. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25080. scene._removePendingData(_this);
  25081. }, function () { }, scene.database, getBinaryData);
  25082. return this;
  25083. };
  25084. /**
  25085. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  25086. */
  25087. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  25088. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25089. return false;
  25090. }
  25091. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  25092. return false;
  25093. }
  25094. this._checkDelayState();
  25095. return true;
  25096. };
  25097. /**
  25098. * Sets the mesh material by the material or multiMaterial `id` property.
  25099. * The material `id` is a string identifying the material or the multiMaterial.
  25100. * This method returns the Mesh.
  25101. */
  25102. Mesh.prototype.setMaterialByID = function (id) {
  25103. var materials = this.getScene().materials;
  25104. var index;
  25105. for (index = 0; index < materials.length; index++) {
  25106. if (materials[index].id === id) {
  25107. this.material = materials[index];
  25108. return this;
  25109. }
  25110. }
  25111. // Multi
  25112. var multiMaterials = this.getScene().multiMaterials;
  25113. for (index = 0; index < multiMaterials.length; index++) {
  25114. if (multiMaterials[index].id === id) {
  25115. this.material = multiMaterials[index];
  25116. return this;
  25117. }
  25118. }
  25119. return this;
  25120. };
  25121. /**
  25122. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  25123. */
  25124. Mesh.prototype.getAnimatables = function () {
  25125. var results = [];
  25126. if (this.material) {
  25127. results.push(this.material);
  25128. }
  25129. if (this.skeleton) {
  25130. results.push(this.skeleton);
  25131. }
  25132. return results;
  25133. };
  25134. /**
  25135. * Modifies the mesh geometry according to the passed transformation matrix.
  25136. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  25137. * The mesh normals are modified accordingly the same transformation.
  25138. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25139. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25140. * Returns the Mesh.
  25141. */
  25142. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  25143. // Position
  25144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25145. return this;
  25146. }
  25147. var submeshes = this.subMeshes.splice(0);
  25148. this._resetPointsArrayCache();
  25149. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25150. var temp = [];
  25151. var index;
  25152. for (index = 0; index < data.length; index += 3) {
  25153. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  25154. }
  25155. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  25156. // Normals
  25157. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25158. return this;
  25159. }
  25160. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25161. temp = [];
  25162. for (index = 0; index < data.length; index += 3) {
  25163. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  25164. }
  25165. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  25166. // flip faces?
  25167. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  25168. this.flipFaces();
  25169. }
  25170. // Restore submeshes
  25171. this.releaseSubMeshes();
  25172. this.subMeshes = submeshes;
  25173. return this;
  25174. };
  25175. /**
  25176. * Modifies the mesh geometry according to its own current World Matrix.
  25177. * The mesh World Matrix is then reset.
  25178. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  25179. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25180. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25181. * Returns the Mesh.
  25182. */
  25183. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  25184. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  25185. this.scaling.copyFromFloats(1, 1, 1);
  25186. this.position.copyFromFloats(0, 0, 0);
  25187. this.rotation.copyFromFloats(0, 0, 0);
  25188. //only if quaternion is already set
  25189. if (this.rotationQuaternion) {
  25190. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25191. }
  25192. this._worldMatrix = BABYLON.Matrix.Identity();
  25193. return this;
  25194. };
  25195. // Cache
  25196. Mesh.prototype._resetPointsArrayCache = function () {
  25197. this._positions = null;
  25198. return this;
  25199. };
  25200. Mesh.prototype._generatePointsArray = function () {
  25201. if (this._positions)
  25202. return true;
  25203. this._positions = [];
  25204. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25205. if (!data) {
  25206. return false;
  25207. }
  25208. for (var index = 0; index < data.length; index += 3) {
  25209. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  25210. }
  25211. return true;
  25212. };
  25213. /**
  25214. * Returns a new Mesh object generated from the current mesh properties.
  25215. * This method must not get confused with createInstance().
  25216. * The parameter `name` is a string, the name given to the new mesh.
  25217. * The optional parameter `newParent` can be any Node object (default `null`).
  25218. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25219. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  25220. */
  25221. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25222. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25223. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25224. };
  25225. /**
  25226. * Disposes the mesh.
  25227. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  25228. */
  25229. Mesh.prototype.dispose = function (doNotRecurse) {
  25230. var _this = this;
  25231. this.morphTargetManager = undefined;
  25232. if (this._geometry) {
  25233. this._geometry.releaseForMesh(this, true);
  25234. }
  25235. // Sources
  25236. var meshes = this.getScene().meshes;
  25237. meshes.forEach(function (mesh) {
  25238. if (mesh._source && mesh._source === _this) {
  25239. mesh._source = null;
  25240. }
  25241. });
  25242. this._source = null;
  25243. // Instances
  25244. if (this._instancesBuffer) {
  25245. this._instancesBuffer.dispose();
  25246. this._instancesBuffer = null;
  25247. }
  25248. while (this.instances.length) {
  25249. this.instances[0].dispose();
  25250. }
  25251. // Highlight layers.
  25252. var highlightLayers = this.getScene().highlightLayers;
  25253. for (var i = 0; i < highlightLayers.length; i++) {
  25254. var highlightLayer = highlightLayers[i];
  25255. if (highlightLayer) {
  25256. highlightLayer.removeMesh(this);
  25257. highlightLayer.removeExcludedMesh(this);
  25258. }
  25259. }
  25260. _super.prototype.dispose.call(this, doNotRecurse);
  25261. };
  25262. /**
  25263. * Modifies the mesh geometry according to a displacement map.
  25264. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  25265. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25266. * This method returns nothing.
  25267. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25268. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25269. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  25270. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25271. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25272. *
  25273. * Returns the Mesh.
  25274. */
  25275. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25276. var _this = this;
  25277. var scene = this.getScene();
  25278. var onload = function (img) {
  25279. // Getting height map data
  25280. var canvas = document.createElement("canvas");
  25281. var context = canvas.getContext("2d");
  25282. var heightMapWidth = img.width;
  25283. var heightMapHeight = img.height;
  25284. canvas.width = heightMapWidth;
  25285. canvas.height = heightMapHeight;
  25286. context.drawImage(img, 0, 0);
  25287. // Create VertexData from map data
  25288. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25289. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  25290. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  25291. //execute success callback, if set
  25292. if (onSuccess) {
  25293. onSuccess(_this);
  25294. }
  25295. };
  25296. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25297. return this;
  25298. };
  25299. /**
  25300. * Modifies the mesh geometry according to a displacementMap buffer.
  25301. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  25302. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25303. * This method returns nothing.
  25304. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  25305. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  25306. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25307. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25308. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25309. *
  25310. * Returns the Mesh.
  25311. */
  25312. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  25313. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  25314. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  25315. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25316. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  25317. return this;
  25318. }
  25319. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25320. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25321. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25322. var position = BABYLON.Vector3.Zero();
  25323. var normal = BABYLON.Vector3.Zero();
  25324. var uv = BABYLON.Vector2.Zero();
  25325. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  25326. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  25327. for (var index = 0; index < positions.length; index += 3) {
  25328. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  25329. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  25330. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  25331. // Compute height
  25332. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  25333. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  25334. var pos = (u + v * heightMapWidth) * 4;
  25335. var r = buffer[pos] / 255.0;
  25336. var g = buffer[pos + 1] / 255.0;
  25337. var b = buffer[pos + 2] / 255.0;
  25338. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25339. normal.normalize();
  25340. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  25341. position = position.add(normal);
  25342. position.toArray(positions, index);
  25343. }
  25344. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  25345. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  25346. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25347. return this;
  25348. };
  25349. /**
  25350. * Modify the mesh to get a flat shading rendering.
  25351. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  25352. * This method returns the Mesh.
  25353. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  25354. */
  25355. Mesh.prototype.convertToFlatShadedMesh = function () {
  25356. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  25357. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25358. var kinds = this.getVerticesDataKinds();
  25359. var vbs = [];
  25360. var data = [];
  25361. var newdata = [];
  25362. var updatableNormals = false;
  25363. var kindIndex;
  25364. var kind;
  25365. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25366. kind = kinds[kindIndex];
  25367. var vertexBuffer = this.getVertexBuffer(kind);
  25368. if (kind === BABYLON.VertexBuffer.NormalKind) {
  25369. updatableNormals = vertexBuffer.isUpdatable();
  25370. kinds.splice(kindIndex, 1);
  25371. kindIndex--;
  25372. continue;
  25373. }
  25374. vbs[kind] = vertexBuffer;
  25375. data[kind] = vbs[kind].getData();
  25376. newdata[kind] = [];
  25377. }
  25378. // Save previous submeshes
  25379. var previousSubmeshes = this.subMeshes.slice(0);
  25380. var indices = this.getIndices();
  25381. var totalIndices = this.getTotalIndices();
  25382. // Generating unique vertices per face
  25383. var index;
  25384. for (index = 0; index < totalIndices; index++) {
  25385. var vertexIndex = indices[index];
  25386. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25387. kind = kinds[kindIndex];
  25388. var stride = vbs[kind].getStrideSize();
  25389. for (var offset = 0; offset < stride; offset++) {
  25390. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  25391. }
  25392. }
  25393. }
  25394. // Updating faces & normal
  25395. var normals = [];
  25396. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  25397. for (index = 0; index < totalIndices; index += 3) {
  25398. indices[index] = index;
  25399. indices[index + 1] = index + 1;
  25400. indices[index + 2] = index + 2;
  25401. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  25402. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  25403. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  25404. var p1p2 = p1.subtract(p2);
  25405. var p3p2 = p3.subtract(p2);
  25406. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  25407. // Store same normals for every vertex
  25408. for (var localIndex = 0; localIndex < 3; localIndex++) {
  25409. normals.push(normal.x);
  25410. normals.push(normal.y);
  25411. normals.push(normal.z);
  25412. }
  25413. }
  25414. this.setIndices(indices);
  25415. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  25416. // Updating vertex buffers
  25417. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25418. kind = kinds[kindIndex];
  25419. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  25420. }
  25421. // Updating submeshes
  25422. this.releaseSubMeshes();
  25423. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  25424. var previousOne = previousSubmeshes[submeshIndex];
  25425. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  25426. }
  25427. this.synchronizeInstances();
  25428. return this;
  25429. };
  25430. /**
  25431. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  25432. * In other words, more vertices, no more indices and a single bigger VBO.
  25433. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  25434. * Returns the Mesh.
  25435. */
  25436. Mesh.prototype.convertToUnIndexedMesh = function () {
  25437. /// <summary>Remove indices by unfolding faces into buffers</summary>
  25438. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25439. var kinds = this.getVerticesDataKinds();
  25440. var vbs = [];
  25441. var data = [];
  25442. var newdata = [];
  25443. var updatableNormals = false;
  25444. var kindIndex;
  25445. var kind;
  25446. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25447. kind = kinds[kindIndex];
  25448. var vertexBuffer = this.getVertexBuffer(kind);
  25449. vbs[kind] = vertexBuffer;
  25450. data[kind] = vbs[kind].getData();
  25451. newdata[kind] = [];
  25452. }
  25453. // Save previous submeshes
  25454. var previousSubmeshes = this.subMeshes.slice(0);
  25455. var indices = this.getIndices();
  25456. var totalIndices = this.getTotalIndices();
  25457. // Generating unique vertices per face
  25458. var index;
  25459. for (index = 0; index < totalIndices; index++) {
  25460. var vertexIndex = indices[index];
  25461. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25462. kind = kinds[kindIndex];
  25463. var stride = vbs[kind].getStrideSize();
  25464. for (var offset = 0; offset < stride; offset++) {
  25465. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  25466. }
  25467. }
  25468. }
  25469. // Updating indices
  25470. for (index = 0; index < totalIndices; index += 3) {
  25471. indices[index] = index;
  25472. indices[index + 1] = index + 1;
  25473. indices[index + 2] = index + 2;
  25474. }
  25475. this.setIndices(indices);
  25476. // Updating vertex buffers
  25477. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25478. kind = kinds[kindIndex];
  25479. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  25480. }
  25481. // Updating submeshes
  25482. this.releaseSubMeshes();
  25483. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  25484. var previousOne = previousSubmeshes[submeshIndex];
  25485. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  25486. }
  25487. this._unIndexed = true;
  25488. this.synchronizeInstances();
  25489. return this;
  25490. };
  25491. /**
  25492. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  25493. * This method returns the Mesh.
  25494. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  25495. */
  25496. Mesh.prototype.flipFaces = function (flipNormals) {
  25497. if (flipNormals === void 0) { flipNormals = false; }
  25498. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  25499. var i;
  25500. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25501. for (i = 0; i < vertex_data.normals.length; i++) {
  25502. vertex_data.normals[i] *= -1;
  25503. }
  25504. }
  25505. var temp;
  25506. for (i = 0; i < vertex_data.indices.length; i += 3) {
  25507. // reassign indices
  25508. temp = vertex_data.indices[i + 1];
  25509. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  25510. vertex_data.indices[i + 2] = temp;
  25511. }
  25512. vertex_data.applyToMesh(this);
  25513. return this;
  25514. };
  25515. // Instances
  25516. /**
  25517. * Creates a new InstancedMesh object from the mesh model.
  25518. * An instance shares the same properties and the same material than its model.
  25519. * Only these properties of each instance can then be set individually :
  25520. * - position
  25521. * - rotation
  25522. * - rotationQuaternion
  25523. * - setPivotMatrix
  25524. * - scaling
  25525. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  25526. * Warning : this method is not supported for Line mesh and LineSystem
  25527. */
  25528. Mesh.prototype.createInstance = function (name) {
  25529. return new BABYLON.InstancedMesh(name, this);
  25530. };
  25531. /**
  25532. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  25533. * After this call, all the mesh instances have the same submeshes than the current mesh.
  25534. * This method returns the Mesh.
  25535. */
  25536. Mesh.prototype.synchronizeInstances = function () {
  25537. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  25538. var instance = this.instances[instanceIndex];
  25539. instance._syncSubMeshes();
  25540. }
  25541. return this;
  25542. };
  25543. /**
  25544. * Simplify the mesh according to the given array of settings.
  25545. * Function will return immediately and will simplify async. It returns the Mesh.
  25546. * @param settings a collection of simplification settings.
  25547. * @param parallelProcessing should all levels calculate parallel or one after the other.
  25548. * @param type the type of simplification to run.
  25549. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  25550. */
  25551. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  25552. if (parallelProcessing === void 0) { parallelProcessing = true; }
  25553. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  25554. this.getScene().simplificationQueue.addTask({
  25555. settings: settings,
  25556. parallelProcessing: parallelProcessing,
  25557. mesh: this,
  25558. simplificationType: simplificationType,
  25559. successCallback: successCallback
  25560. });
  25561. return this;
  25562. };
  25563. /**
  25564. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  25565. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  25566. * This should be used together with the simplification to avoid disappearing triangles.
  25567. * Returns the Mesh.
  25568. * @param successCallback an optional success callback to be called after the optimization finished.
  25569. */
  25570. Mesh.prototype.optimizeIndices = function (successCallback) {
  25571. var _this = this;
  25572. var indices = this.getIndices();
  25573. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25574. var vectorPositions = [];
  25575. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  25576. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25577. }
  25578. var dupes = [];
  25579. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25580. var realPos = vectorPositions.length - 1 - iteration;
  25581. var testedPosition = vectorPositions[realPos];
  25582. for (var j = 0; j < realPos; ++j) {
  25583. var againstPosition = vectorPositions[j];
  25584. if (testedPosition.equals(againstPosition)) {
  25585. dupes[realPos] = j;
  25586. break;
  25587. }
  25588. }
  25589. }, function () {
  25590. for (var i = 0; i < indices.length; ++i) {
  25591. indices[i] = dupes[indices[i]] || indices[i];
  25592. }
  25593. //indices are now reordered
  25594. var originalSubMeshes = _this.subMeshes.slice(0);
  25595. _this.setIndices(indices);
  25596. _this.subMeshes = originalSubMeshes;
  25597. if (successCallback) {
  25598. successCallback(_this);
  25599. }
  25600. });
  25601. return this;
  25602. };
  25603. Mesh.prototype.serialize = function (serializationObject) {
  25604. serializationObject.name = this.name;
  25605. serializationObject.id = this.id;
  25606. serializationObject.type = this.getClassName();
  25607. if (BABYLON.Tags.HasTags(this)) {
  25608. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25609. }
  25610. serializationObject.position = this.position.asArray();
  25611. if (this.rotationQuaternion) {
  25612. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25613. }
  25614. else if (this.rotation) {
  25615. serializationObject.rotation = this.rotation.asArray();
  25616. }
  25617. serializationObject.scaling = this.scaling.asArray();
  25618. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25619. serializationObject.isEnabled = this.isEnabled();
  25620. serializationObject.isVisible = this.isVisible;
  25621. serializationObject.infiniteDistance = this.infiniteDistance;
  25622. serializationObject.pickable = this.isPickable;
  25623. serializationObject.receiveShadows = this.receiveShadows;
  25624. serializationObject.billboardMode = this.billboardMode;
  25625. serializationObject.visibility = this.visibility;
  25626. serializationObject.checkCollisions = this.checkCollisions;
  25627. serializationObject.isBlocker = this.isBlocker;
  25628. // Parent
  25629. if (this.parent) {
  25630. serializationObject.parentId = this.parent.id;
  25631. }
  25632. // Geometry
  25633. var geometry = this._geometry;
  25634. if (geometry) {
  25635. var geometryId = geometry.id;
  25636. serializationObject.geometryId = geometryId;
  25637. // SubMeshes
  25638. serializationObject.subMeshes = [];
  25639. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25640. var subMesh = this.subMeshes[subIndex];
  25641. serializationObject.subMeshes.push({
  25642. materialIndex: subMesh.materialIndex,
  25643. verticesStart: subMesh.verticesStart,
  25644. verticesCount: subMesh.verticesCount,
  25645. indexStart: subMesh.indexStart,
  25646. indexCount: subMesh.indexCount
  25647. });
  25648. }
  25649. }
  25650. // Material
  25651. if (this.material) {
  25652. serializationObject.materialId = this.material.id;
  25653. }
  25654. else {
  25655. this.material = null;
  25656. }
  25657. // Morph targets
  25658. if (this.morphTargetManager) {
  25659. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25660. }
  25661. // Skeleton
  25662. if (this.skeleton) {
  25663. serializationObject.skeletonId = this.skeleton.id;
  25664. }
  25665. // Physics
  25666. //TODO implement correct serialization for physics impostors.
  25667. if (this.getPhysicsImpostor()) {
  25668. var impostor = this.getPhysicsImpostor();
  25669. serializationObject.physicsMass = impostor.getParam("mass");
  25670. serializationObject.physicsFriction = impostor.getParam("friction");
  25671. serializationObject.physicsRestitution = impostor.getParam("mass");
  25672. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  25673. }
  25674. // Metadata
  25675. if (this.metadata) {
  25676. serializationObject.metadata = this.metadata;
  25677. }
  25678. // Instances
  25679. serializationObject.instances = [];
  25680. for (var index = 0; index < this.instances.length; index++) {
  25681. var instance = this.instances[index];
  25682. var serializationInstance = {
  25683. name: instance.name,
  25684. position: instance.position.asArray(),
  25685. scaling: instance.scaling.asArray()
  25686. };
  25687. if (instance.rotationQuaternion) {
  25688. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25689. }
  25690. else if (instance.rotation) {
  25691. serializationInstance.rotation = instance.rotation.asArray();
  25692. }
  25693. serializationObject.instances.push(serializationInstance);
  25694. // Animations
  25695. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25696. serializationInstance.ranges = instance.serializeAnimationRanges();
  25697. }
  25698. //
  25699. // Animations
  25700. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25701. serializationObject.ranges = this.serializeAnimationRanges();
  25702. // Layer mask
  25703. serializationObject.layerMask = this.layerMask;
  25704. // Alpha
  25705. serializationObject.alphaIndex = this.alphaIndex;
  25706. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25707. // Overlay
  25708. serializationObject.overlayAlpha = this.overlayAlpha;
  25709. serializationObject.overlayColor = this.overlayColor.asArray();
  25710. serializationObject.renderOverlay = this.renderOverlay;
  25711. // Fog
  25712. serializationObject.applyFog = this.applyFog;
  25713. // Action Manager
  25714. if (this.actionManager) {
  25715. serializationObject.actions = this.actionManager.serialize(this.name);
  25716. }
  25717. };
  25718. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25719. if (!this.geometry) {
  25720. return;
  25721. }
  25722. this._markSubMeshesAsAttributesDirty();
  25723. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  25724. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25725. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25726. this.morphTargetManager = undefined;
  25727. return;
  25728. }
  25729. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  25730. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  25731. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  25732. if (morphTarget.hasNormals) {
  25733. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  25734. }
  25735. }
  25736. }
  25737. else {
  25738. var index = 0;
  25739. // Positions
  25740. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25741. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25742. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25743. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25744. }
  25745. index++;
  25746. }
  25747. }
  25748. };
  25749. // Statics
  25750. /**
  25751. * Returns a new Mesh object what is a deep copy of the passed mesh.
  25752. * The parameter `parsedMesh` is the mesh to be copied.
  25753. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25754. */
  25755. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25756. var mesh;
  25757. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25758. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25759. }
  25760. else {
  25761. mesh = new Mesh(parsedMesh.name, scene);
  25762. }
  25763. mesh.id = parsedMesh.id;
  25764. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25765. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25766. if (parsedMesh.metadata !== undefined) {
  25767. mesh.metadata = parsedMesh.metadata;
  25768. }
  25769. if (parsedMesh.rotationQuaternion) {
  25770. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25771. }
  25772. else if (parsedMesh.rotation) {
  25773. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25774. }
  25775. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25776. if (parsedMesh.localMatrix) {
  25777. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25778. }
  25779. else if (parsedMesh.pivotMatrix) {
  25780. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25781. }
  25782. mesh.setEnabled(parsedMesh.isEnabled);
  25783. mesh.isVisible = parsedMesh.isVisible;
  25784. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25785. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25786. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25787. if (parsedMesh.applyFog !== undefined) {
  25788. mesh.applyFog = parsedMesh.applyFog;
  25789. }
  25790. if (parsedMesh.pickable !== undefined) {
  25791. mesh.isPickable = parsedMesh.pickable;
  25792. }
  25793. if (parsedMesh.alphaIndex !== undefined) {
  25794. mesh.alphaIndex = parsedMesh.alphaIndex;
  25795. }
  25796. mesh.receiveShadows = parsedMesh.receiveShadows;
  25797. mesh.billboardMode = parsedMesh.billboardMode;
  25798. if (parsedMesh.visibility !== undefined) {
  25799. mesh.visibility = parsedMesh.visibility;
  25800. }
  25801. mesh.checkCollisions = parsedMesh.checkCollisions;
  25802. if (parsedMesh.isBlocker !== undefined) {
  25803. mesh.isBlocker = parsedMesh.isBlocker;
  25804. }
  25805. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25806. // freezeWorldMatrix
  25807. if (parsedMesh.freezeWorldMatrix) {
  25808. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25809. }
  25810. // Parent
  25811. if (parsedMesh.parentId) {
  25812. mesh._waitingParentId = parsedMesh.parentId;
  25813. }
  25814. // Actions
  25815. if (parsedMesh.actions !== undefined) {
  25816. mesh._waitingActions = parsedMesh.actions;
  25817. }
  25818. // Overlay
  25819. if (parsedMesh.overlayAlpha !== undefined) {
  25820. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25821. }
  25822. if (parsedMesh.overlayColor !== undefined) {
  25823. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25824. }
  25825. if (parsedMesh.renderOverlay !== undefined) {
  25826. mesh.renderOverlay = parsedMesh.renderOverlay;
  25827. }
  25828. // Geometry
  25829. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25830. if (parsedMesh.delayLoadingFile) {
  25831. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25832. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25833. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25834. if (parsedMesh._binaryInfo) {
  25835. mesh._binaryInfo = parsedMesh._binaryInfo;
  25836. }
  25837. mesh._delayInfo = [];
  25838. if (parsedMesh.hasUVs) {
  25839. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25840. }
  25841. if (parsedMesh.hasUVs2) {
  25842. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25843. }
  25844. if (parsedMesh.hasUVs3) {
  25845. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25846. }
  25847. if (parsedMesh.hasUVs4) {
  25848. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25849. }
  25850. if (parsedMesh.hasUVs5) {
  25851. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25852. }
  25853. if (parsedMesh.hasUVs6) {
  25854. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25855. }
  25856. if (parsedMesh.hasColors) {
  25857. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25858. }
  25859. if (parsedMesh.hasMatricesIndices) {
  25860. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25861. }
  25862. if (parsedMesh.hasMatricesWeights) {
  25863. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25864. }
  25865. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25866. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25867. mesh._checkDelayState();
  25868. }
  25869. }
  25870. else {
  25871. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25872. }
  25873. // Material
  25874. if (parsedMesh.materialId) {
  25875. mesh.setMaterialByID(parsedMesh.materialId);
  25876. }
  25877. else {
  25878. mesh.material = null;
  25879. }
  25880. // Morph targets
  25881. if (parsedMesh.morphTargetManagerId > -1) {
  25882. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25883. }
  25884. // Skeleton
  25885. if (parsedMesh.skeletonId > -1) {
  25886. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25887. if (parsedMesh.numBoneInfluencers) {
  25888. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25889. }
  25890. }
  25891. // Animations
  25892. if (parsedMesh.animations) {
  25893. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25894. var parsedAnimation = parsedMesh.animations[animationIndex];
  25895. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25896. }
  25897. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25898. }
  25899. if (parsedMesh.autoAnimate) {
  25900. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25901. }
  25902. // Layer Mask
  25903. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25904. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25905. }
  25906. else {
  25907. mesh.layerMask = 0x0FFFFFFF;
  25908. }
  25909. // Physics
  25910. if (parsedMesh.physicsImpostor) {
  25911. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25912. mass: parsedMesh.physicsMass,
  25913. friction: parsedMesh.physicsFriction,
  25914. restitution: parsedMesh.physicsRestitution
  25915. }, scene);
  25916. }
  25917. // Instances
  25918. if (parsedMesh.instances) {
  25919. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25920. var parsedInstance = parsedMesh.instances[index];
  25921. var instance = mesh.createInstance(parsedInstance.name);
  25922. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25923. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25924. if (parsedInstance.parentId) {
  25925. instance._waitingParentId = parsedInstance.parentId;
  25926. }
  25927. if (parsedInstance.rotationQuaternion) {
  25928. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25929. }
  25930. else if (parsedInstance.rotation) {
  25931. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25932. }
  25933. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25934. instance.checkCollisions = mesh.checkCollisions;
  25935. if (parsedMesh.animations) {
  25936. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25937. parsedAnimation = parsedMesh.animations[animationIndex];
  25938. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25939. }
  25940. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25941. }
  25942. }
  25943. }
  25944. return mesh;
  25945. };
  25946. /**
  25947. * Creates a ribbon mesh.
  25948. * Please consider using the same method from the MeshBuilder class instead.
  25949. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  25950. *
  25951. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25952. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25953. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25954. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25955. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  25956. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  25957. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  25958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25961. */
  25962. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25963. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25964. pathArray: pathArray,
  25965. closeArray: closeArray,
  25966. closePath: closePath,
  25967. offset: offset,
  25968. updatable: updatable,
  25969. sideOrientation: sideOrientation,
  25970. instance: instance
  25971. }, scene);
  25972. };
  25973. /**
  25974. * Creates a plane polygonal mesh. By default, this is a disc.
  25975. * Please consider using the same method from the MeshBuilder class instead.
  25976. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25977. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  25978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25981. */
  25982. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25983. var options = {
  25984. radius: radius,
  25985. tessellation: tessellation,
  25986. sideOrientation: sideOrientation,
  25987. updatable: updatable
  25988. };
  25989. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25990. };
  25991. /**
  25992. * Creates a box mesh.
  25993. * Please consider using the same method from the MeshBuilder class instead.
  25994. * The parameter `size` sets the size (float) of each box side (default 1).
  25995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25996. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25998. */
  25999. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  26000. var options = {
  26001. size: size,
  26002. sideOrientation: sideOrientation,
  26003. updatable: updatable
  26004. };
  26005. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  26006. };
  26007. /**
  26008. * Creates a sphere mesh.
  26009. * Please consider using the same method from the MeshBuilder class instead.
  26010. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26011. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26015. */
  26016. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  26017. var options = {
  26018. segments: segments,
  26019. diameterX: diameter,
  26020. diameterY: diameter,
  26021. diameterZ: diameter,
  26022. sideOrientation: sideOrientation,
  26023. updatable: updatable
  26024. };
  26025. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  26026. };
  26027. /**
  26028. * Creates a cylinder or a cone mesh.
  26029. * Please consider using the same method from the MeshBuilder class instead.
  26030. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26031. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26032. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  26033. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26034. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26035. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26036. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26037. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26038. */
  26039. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  26040. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  26041. if (scene !== undefined) {
  26042. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  26043. updatable = scene;
  26044. }
  26045. scene = subdivisions;
  26046. subdivisions = 1;
  26047. }
  26048. var options = {
  26049. height: height,
  26050. diameterTop: diameterTop,
  26051. diameterBottom: diameterBottom,
  26052. tessellation: tessellation,
  26053. subdivisions: subdivisions,
  26054. sideOrientation: sideOrientation,
  26055. updatable: updatable
  26056. };
  26057. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  26058. };
  26059. // Torus (Code from SharpDX.org)
  26060. /**
  26061. * Creates a torus mesh.
  26062. * Please consider using the same method from the MeshBuilder class instead.
  26063. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26064. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26065. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26066. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26067. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26069. */
  26070. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  26071. var options = {
  26072. diameter: diameter,
  26073. thickness: thickness,
  26074. tessellation: tessellation,
  26075. sideOrientation: sideOrientation,
  26076. updatable: updatable
  26077. };
  26078. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  26079. };
  26080. /**
  26081. * Creates a torus knot mesh.
  26082. * Please consider using the same method from the MeshBuilder class instead.
  26083. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26084. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26085. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26086. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26090. */
  26091. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  26092. var options = {
  26093. radius: radius,
  26094. tube: tube,
  26095. radialSegments: radialSegments,
  26096. tubularSegments: tubularSegments,
  26097. p: p,
  26098. q: q,
  26099. sideOrientation: sideOrientation,
  26100. updatable: updatable
  26101. };
  26102. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  26103. };
  26104. /**
  26105. * Creates a line mesh.
  26106. * Please consider using the same method from the MeshBuilder class instead.
  26107. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  26108. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26109. * The parameter `points` is an array successive Vector3.
  26110. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  26111. * When updating an instance, remember that only point positions can change, not the number of points.
  26112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26113. */
  26114. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  26115. var options = {
  26116. points: points,
  26117. updatable: updatable,
  26118. instance: instance
  26119. };
  26120. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  26121. };
  26122. /**
  26123. * Creates a dashed line mesh.
  26124. * Please consider using the same method from the MeshBuilder class instead.
  26125. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  26126. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26127. * The parameter `points` is an array successive Vector3.
  26128. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26129. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26130. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26131. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  26132. * When updating an instance, remember that only point positions can change, not the number of points.
  26133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26134. */
  26135. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  26136. var options = {
  26137. points: points,
  26138. dashSize: dashSize,
  26139. gapSize: gapSize,
  26140. dashNb: dashNb,
  26141. updatable: updatable,
  26142. instance: instance
  26143. };
  26144. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26145. };
  26146. /**
  26147. * Creates an extruded shape mesh.
  26148. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  26149. * Please consider using the same method from the MeshBuilder class instead.
  26150. *
  26151. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26152. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  26153. * extruded along the Z axis.
  26154. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26155. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  26156. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26157. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  26158. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  26159. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26161. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26163. */
  26164. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26165. var options = {
  26166. shape: shape,
  26167. path: path,
  26168. scale: scale,
  26169. rotation: rotation,
  26170. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26171. sideOrientation: sideOrientation,
  26172. instance: instance,
  26173. updatable: updatable
  26174. };
  26175. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26176. };
  26177. /**
  26178. * Creates an custom extruded shape mesh.
  26179. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  26180. * Please consider using the same method from the MeshBuilder class instead.
  26181. *
  26182. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26183. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  26184. * extruded along the Z axis.
  26185. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26186. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  26187. * and the distance of this point from the begining of the path :
  26188. * ```javascript
  26189. * var rotationFunction = function(i, distance) {
  26190. * // do things
  26191. * return rotationValue; }
  26192. * ```
  26193. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26194. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  26195. * and the distance of this point from the begining of the path :
  26196. * ```javascript
  26197. * var scaleFunction = function(i, distance) {
  26198. * // do things
  26199. * return scaleValue;}
  26200. * ```
  26201. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26202. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26203. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26204. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  26205. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  26206. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26210. */
  26211. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26212. var options = {
  26213. shape: shape,
  26214. path: path,
  26215. scaleFunction: scaleFunction,
  26216. rotationFunction: rotationFunction,
  26217. ribbonCloseArray: ribbonCloseArray,
  26218. ribbonClosePath: ribbonClosePath,
  26219. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26220. sideOrientation: sideOrientation,
  26221. instance: instance,
  26222. updatable: updatable
  26223. };
  26224. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  26225. };
  26226. /**
  26227. * Creates lathe mesh.
  26228. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26229. * Please consider using the same method from the MeshBuilder class instead.
  26230. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  26231. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26232. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26233. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26235. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26237. */
  26238. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  26239. var options = {
  26240. shape: shape,
  26241. radius: radius,
  26242. tessellation: tessellation,
  26243. sideOrientation: sideOrientation,
  26244. updatable: updatable
  26245. };
  26246. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  26247. };
  26248. /**
  26249. * Creates a plane mesh.
  26250. * Please consider using the same method from the MeshBuilder class instead.
  26251. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26255. */
  26256. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  26257. var options = {
  26258. size: size,
  26259. width: size,
  26260. height: size,
  26261. sideOrientation: sideOrientation,
  26262. updatable: updatable
  26263. };
  26264. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  26265. };
  26266. /**
  26267. * Creates a ground mesh.
  26268. * Please consider using the same method from the MeshBuilder class instead.
  26269. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26270. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26272. */
  26273. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  26274. var options = {
  26275. width: width,
  26276. height: height,
  26277. subdivisions: subdivisions,
  26278. updatable: updatable
  26279. };
  26280. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  26281. };
  26282. /**
  26283. * Creates a tiled ground mesh.
  26284. * Please consider using the same method from the MeshBuilder class instead.
  26285. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26286. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26287. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26288. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26289. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26290. * numbers of subdivisions on the ground width and height of each tile.
  26291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26292. */
  26293. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  26294. var options = {
  26295. xmin: xmin,
  26296. zmin: zmin,
  26297. xmax: xmax,
  26298. zmax: zmax,
  26299. subdivisions: subdivisions,
  26300. precision: precision,
  26301. updatable: updatable
  26302. };
  26303. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  26304. };
  26305. /**
  26306. * Creates a ground mesh from a height map.
  26307. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26308. * Please consider using the same method from the MeshBuilder class instead.
  26309. * The parameter `url` sets the URL of the height map image resource.
  26310. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26311. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26312. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26313. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26314. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  26315. * This function is passed the newly built mesh :
  26316. * ```javascript
  26317. * function(mesh) { // do things
  26318. * return; }
  26319. * ```
  26320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26321. */
  26322. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  26323. var options = {
  26324. width: width,
  26325. height: height,
  26326. subdivisions: subdivisions,
  26327. minHeight: minHeight,
  26328. maxHeight: maxHeight,
  26329. updatable: updatable,
  26330. onReady: onReady
  26331. };
  26332. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  26333. };
  26334. /**
  26335. * Creates a tube mesh.
  26336. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  26337. * Please consider using the same method from the MeshBuilder class instead.
  26338. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26339. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26340. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26341. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26342. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  26343. * It must return a radius value (positive float) :
  26344. * ```javascript
  26345. * var radiusFunction = function(i, distance) {
  26346. * // do things
  26347. * return radius; }
  26348. * ```
  26349. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  26350. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  26351. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26352. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26354. */
  26355. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  26356. var options = {
  26357. path: path,
  26358. radius: radius,
  26359. tessellation: tessellation,
  26360. radiusFunction: radiusFunction,
  26361. arc: 1,
  26362. cap: cap,
  26363. updatable: updatable,
  26364. sideOrientation: sideOrientation,
  26365. instance: instance
  26366. };
  26367. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  26368. };
  26369. /**
  26370. * Creates a polyhedron mesh.
  26371. * Please consider using the same method from the MeshBuilder class instead.
  26372. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  26373. * to choose the wanted type.
  26374. * The parameter `size` (positive float, default 1) sets the polygon size.
  26375. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26376. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  26377. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  26378. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  26379. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  26380. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  26381. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26382. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26384. */
  26385. Mesh.CreatePolyhedron = function (name, options, scene) {
  26386. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  26387. };
  26388. /**
  26389. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  26390. * Please consider using the same method from the MeshBuilder class instead.
  26391. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  26392. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  26393. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  26394. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  26395. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26396. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26398. */
  26399. Mesh.CreateIcoSphere = function (name, options, scene) {
  26400. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  26401. };
  26402. /**
  26403. * Creates a decal mesh.
  26404. * Please consider using the same method from the MeshBuilder class instead.
  26405. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  26406. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26407. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26408. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26409. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26410. */
  26411. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  26412. var options = {
  26413. position: position,
  26414. normal: normal,
  26415. size: size,
  26416. angle: angle
  26417. };
  26418. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  26419. };
  26420. // Skeletons
  26421. /**
  26422. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26423. */
  26424. Mesh.prototype.setPositionsForCPUSkinning = function () {
  26425. var source;
  26426. if (!this._sourcePositions) {
  26427. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26428. this._sourcePositions = new Float32Array(source);
  26429. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  26430. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  26431. }
  26432. }
  26433. return this._sourcePositions;
  26434. };
  26435. /**
  26436. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26437. */
  26438. Mesh.prototype.setNormalsForCPUSkinning = function () {
  26439. var source;
  26440. if (!this._sourceNormals) {
  26441. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26442. this._sourceNormals = new Float32Array(source);
  26443. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  26444. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  26445. }
  26446. }
  26447. return this._sourceNormals;
  26448. };
  26449. /**
  26450. * Updates the vertex buffer by applying transformation from the bones.
  26451. * Returns the Mesh.
  26452. *
  26453. * @param {skeleton} skeleton to apply
  26454. */
  26455. Mesh.prototype.applySkeleton = function (skeleton) {
  26456. if (!this.geometry) {
  26457. return this;
  26458. }
  26459. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  26460. return this;
  26461. }
  26462. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  26463. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26464. return this;
  26465. }
  26466. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26467. return this;
  26468. }
  26469. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26470. return this;
  26471. }
  26472. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26473. return this;
  26474. }
  26475. if (!this._sourcePositions) {
  26476. var submeshes = this.subMeshes.slice();
  26477. this.setPositionsForCPUSkinning();
  26478. this.subMeshes = submeshes;
  26479. }
  26480. if (!this._sourceNormals) {
  26481. this.setNormalsForCPUSkinning();
  26482. }
  26483. // positionsData checks for not being Float32Array will only pass at most once
  26484. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26485. if (!(positionsData instanceof Float32Array)) {
  26486. positionsData = new Float32Array(positionsData);
  26487. }
  26488. // normalsData checks for not being Float32Array will only pass at most once
  26489. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26490. if (!(normalsData instanceof Float32Array)) {
  26491. normalsData = new Float32Array(normalsData);
  26492. }
  26493. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26494. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26495. var needExtras = this.numBoneInfluencers > 4;
  26496. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26497. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26498. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26499. var tempVector3 = BABYLON.Vector3.Zero();
  26500. var finalMatrix = new BABYLON.Matrix();
  26501. var tempMatrix = new BABYLON.Matrix();
  26502. var matWeightIdx = 0;
  26503. var inf;
  26504. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26505. var weight;
  26506. for (inf = 0; inf < 4; inf++) {
  26507. weight = matricesWeightsData[matWeightIdx + inf];
  26508. if (weight > 0) {
  26509. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26510. finalMatrix.addToSelf(tempMatrix);
  26511. }
  26512. else
  26513. break;
  26514. }
  26515. if (needExtras) {
  26516. for (inf = 0; inf < 4; inf++) {
  26517. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26518. if (weight > 0) {
  26519. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26520. finalMatrix.addToSelf(tempMatrix);
  26521. }
  26522. else
  26523. break;
  26524. }
  26525. }
  26526. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26527. tempVector3.toArray(positionsData, index);
  26528. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26529. tempVector3.toArray(normalsData, index);
  26530. finalMatrix.reset();
  26531. }
  26532. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26533. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26534. return this;
  26535. };
  26536. // Tools
  26537. /**
  26538. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26539. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26540. */
  26541. Mesh.MinMax = function (meshes) {
  26542. var minVector = null;
  26543. var maxVector = null;
  26544. meshes.forEach(function (mesh, index, array) {
  26545. var boundingBox = mesh.getBoundingInfo().boundingBox;
  26546. if (!minVector) {
  26547. minVector = boundingBox.minimumWorld;
  26548. maxVector = boundingBox.maximumWorld;
  26549. }
  26550. else {
  26551. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26552. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26553. }
  26554. });
  26555. return {
  26556. min: minVector,
  26557. max: maxVector
  26558. };
  26559. };
  26560. /**
  26561. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26562. */
  26563. Mesh.Center = function (meshesOrMinMaxVector) {
  26564. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26565. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26566. };
  26567. /**
  26568. * Merge the array of meshes into a single mesh for performance reasons.
  26569. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26570. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26571. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26572. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26573. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26574. */
  26575. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26576. if (disposeSource === void 0) { disposeSource = true; }
  26577. var index;
  26578. if (!allow32BitsIndices) {
  26579. var totalVertices = 0;
  26580. // Counting vertices
  26581. for (index = 0; index < meshes.length; index++) {
  26582. if (meshes[index]) {
  26583. totalVertices += meshes[index].getTotalVertices();
  26584. if (totalVertices > 65536) {
  26585. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26586. return null;
  26587. }
  26588. }
  26589. }
  26590. }
  26591. // Merge
  26592. var vertexData;
  26593. var otherVertexData;
  26594. var indiceArray = new Array();
  26595. var source;
  26596. for (index = 0; index < meshes.length; index++) {
  26597. if (meshes[index]) {
  26598. meshes[index].computeWorldMatrix(true);
  26599. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26600. otherVertexData.transform(meshes[index].getWorldMatrix());
  26601. if (vertexData) {
  26602. vertexData.merge(otherVertexData);
  26603. }
  26604. else {
  26605. vertexData = otherVertexData;
  26606. source = meshes[index];
  26607. }
  26608. if (subdivideWithSubMeshes) {
  26609. indiceArray.push(meshes[index].getTotalIndices());
  26610. }
  26611. }
  26612. }
  26613. if (!meshSubclass) {
  26614. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26615. }
  26616. vertexData.applyToMesh(meshSubclass);
  26617. // Setting properties
  26618. meshSubclass.material = source.material;
  26619. meshSubclass.checkCollisions = source.checkCollisions;
  26620. // Cleaning
  26621. if (disposeSource) {
  26622. for (index = 0; index < meshes.length; index++) {
  26623. if (meshes[index]) {
  26624. meshes[index].dispose();
  26625. }
  26626. }
  26627. }
  26628. // Subdivide
  26629. if (subdivideWithSubMeshes) {
  26630. //-- Suppresions du submesh global
  26631. meshSubclass.releaseSubMeshes();
  26632. index = 0;
  26633. var offset = 0;
  26634. //-- aplique la subdivision en fonction du tableau d'indices
  26635. while (index < indiceArray.length) {
  26636. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26637. offset += indiceArray[index];
  26638. index++;
  26639. }
  26640. }
  26641. return meshSubclass;
  26642. };
  26643. return Mesh;
  26644. }(BABYLON.AbstractMesh));
  26645. // Consts
  26646. Mesh._FRONTSIDE = 0;
  26647. Mesh._BACKSIDE = 1;
  26648. Mesh._DOUBLESIDE = 2;
  26649. Mesh._DEFAULTSIDE = 0;
  26650. Mesh._NO_CAP = 0;
  26651. Mesh._CAP_START = 1;
  26652. Mesh._CAP_END = 2;
  26653. Mesh._CAP_ALL = 3;
  26654. BABYLON.Mesh = Mesh;
  26655. })(BABYLON || (BABYLON = {}));
  26656. //# sourceMappingURL=babylon.mesh.js.map
  26657. var BABYLON;
  26658. (function (BABYLON) {
  26659. var SubMesh = (function () {
  26660. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26661. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26662. this.materialIndex = materialIndex;
  26663. this.verticesStart = verticesStart;
  26664. this.verticesCount = verticesCount;
  26665. this.indexStart = indexStart;
  26666. this.indexCount = indexCount;
  26667. this._renderId = 0;
  26668. this._mesh = mesh;
  26669. this._renderingMesh = renderingMesh || mesh;
  26670. mesh.subMeshes.push(this);
  26671. this._trianglePlanes = [];
  26672. this._id = mesh.subMeshes.length - 1;
  26673. if (createBoundingBox) {
  26674. this.refreshBoundingInfo();
  26675. mesh.computeWorldMatrix(true);
  26676. }
  26677. }
  26678. Object.defineProperty(SubMesh.prototype, "effect", {
  26679. get: function () {
  26680. return this._materialEffect;
  26681. },
  26682. enumerable: true,
  26683. configurable: true
  26684. });
  26685. SubMesh.prototype.setEffect = function (effect, defines) {
  26686. if (this._materialEffect === effect) {
  26687. return;
  26688. }
  26689. this._materialDefines = defines;
  26690. this._materialEffect = effect;
  26691. };
  26692. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26693. get: function () {
  26694. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26695. },
  26696. enumerable: true,
  26697. configurable: true
  26698. });
  26699. /**
  26700. * Returns the submesh BoudingInfo object.
  26701. */
  26702. SubMesh.prototype.getBoundingInfo = function () {
  26703. if (this.IsGlobal) {
  26704. return this._mesh.getBoundingInfo();
  26705. }
  26706. return this._boundingInfo;
  26707. };
  26708. /**
  26709. * Sets the submesh BoundingInfo.
  26710. * Return the SubMesh.
  26711. */
  26712. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26713. this._boundingInfo = boundingInfo;
  26714. return this;
  26715. };
  26716. /**
  26717. * Returns the mesh of the current submesh.
  26718. */
  26719. SubMesh.prototype.getMesh = function () {
  26720. return this._mesh;
  26721. };
  26722. /**
  26723. * Returns the rendering mesh of the submesh.
  26724. */
  26725. SubMesh.prototype.getRenderingMesh = function () {
  26726. return this._renderingMesh;
  26727. };
  26728. /**
  26729. * Returns the submesh material.
  26730. */
  26731. SubMesh.prototype.getMaterial = function () {
  26732. var rootMaterial = this._renderingMesh.material;
  26733. if (rootMaterial && rootMaterial.getSubMaterial) {
  26734. var multiMaterial = rootMaterial;
  26735. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26736. if (this._currentMaterial !== effectiveMaterial) {
  26737. this._currentMaterial = effectiveMaterial;
  26738. if (this._materialDefines) {
  26739. this._materialDefines.markAllAsDirty();
  26740. }
  26741. }
  26742. return effectiveMaterial;
  26743. }
  26744. if (!rootMaterial) {
  26745. return this._mesh.getScene().defaultMaterial;
  26746. }
  26747. return rootMaterial;
  26748. };
  26749. // Methods
  26750. /**
  26751. * Sets a new updated BoundingInfo object to the submesh.
  26752. * Returns the SubMesh.
  26753. */
  26754. SubMesh.prototype.refreshBoundingInfo = function () {
  26755. this._lastColliderWorldVertices = null;
  26756. if (this.IsGlobal) {
  26757. return;
  26758. }
  26759. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26760. if (!data) {
  26761. this._boundingInfo = this._mesh._boundingInfo;
  26762. return;
  26763. }
  26764. var indices = this._renderingMesh.getIndices();
  26765. var extend;
  26766. //is this the only submesh?
  26767. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26768. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26769. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  26770. }
  26771. else {
  26772. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26773. }
  26774. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26775. return this;
  26776. };
  26777. SubMesh.prototype._checkCollision = function (collider) {
  26778. return this.getBoundingInfo()._checkCollision(collider);
  26779. };
  26780. /**
  26781. * Updates the submesh BoundingInfo.
  26782. * Returns the Submesh.
  26783. */
  26784. SubMesh.prototype.updateBoundingInfo = function (world) {
  26785. if (!this.getBoundingInfo()) {
  26786. this.refreshBoundingInfo();
  26787. }
  26788. this.getBoundingInfo().update(world);
  26789. return this;
  26790. };
  26791. /**
  26792. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26793. * Boolean returned.
  26794. */
  26795. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26796. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  26797. };
  26798. /**
  26799. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26800. * Boolean returned.
  26801. */
  26802. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26803. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  26804. };
  26805. /**
  26806. * Renders the submesh.
  26807. * Returns it.
  26808. */
  26809. SubMesh.prototype.render = function (enableAlphaMode) {
  26810. this._renderingMesh.render(this, enableAlphaMode);
  26811. return this;
  26812. };
  26813. /**
  26814. * Returns a new Index Buffer.
  26815. * Type returned : WebGLBuffer.
  26816. */
  26817. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26818. if (!this._linesIndexBuffer) {
  26819. var linesIndices = [];
  26820. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26821. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26822. }
  26823. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26824. this.linesIndexCount = linesIndices.length;
  26825. }
  26826. return this._linesIndexBuffer;
  26827. };
  26828. /**
  26829. * True is the passed Ray intersects the submesh bounding box.
  26830. * Boolean returned.
  26831. */
  26832. SubMesh.prototype.canIntersects = function (ray) {
  26833. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  26834. };
  26835. /**
  26836. * Returns an object IntersectionInfo.
  26837. */
  26838. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26839. var intersectInfo = null;
  26840. // LineMesh first as it's also a Mesh...
  26841. if (this._mesh instanceof BABYLON.LinesMesh) {
  26842. var lineMesh = this._mesh;
  26843. // Line test
  26844. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26845. var p0 = positions[indices[index]];
  26846. var p1 = positions[indices[index + 1]];
  26847. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26848. if (length < 0) {
  26849. continue;
  26850. }
  26851. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26852. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26853. if (fastCheck) {
  26854. break;
  26855. }
  26856. }
  26857. }
  26858. }
  26859. else {
  26860. // Triangles test
  26861. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26862. var p0 = positions[indices[index]];
  26863. var p1 = positions[indices[index + 1]];
  26864. var p2 = positions[indices[index + 2]];
  26865. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26866. if (currentIntersectInfo) {
  26867. if (currentIntersectInfo.distance < 0) {
  26868. continue;
  26869. }
  26870. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26871. intersectInfo = currentIntersectInfo;
  26872. intersectInfo.faceId = index / 3;
  26873. if (fastCheck) {
  26874. break;
  26875. }
  26876. }
  26877. }
  26878. }
  26879. }
  26880. return intersectInfo;
  26881. };
  26882. // Clone
  26883. /**
  26884. * Creates a new Submesh from the passed Mesh.
  26885. */
  26886. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26887. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26888. if (!this.IsGlobal) {
  26889. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  26890. }
  26891. return result;
  26892. };
  26893. // Dispose
  26894. /**
  26895. * Disposes the Submesh.
  26896. * Returns nothing.
  26897. */
  26898. SubMesh.prototype.dispose = function () {
  26899. if (this._linesIndexBuffer) {
  26900. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26901. this._linesIndexBuffer = null;
  26902. }
  26903. // Remove from mesh
  26904. var index = this._mesh.subMeshes.indexOf(this);
  26905. this._mesh.subMeshes.splice(index, 1);
  26906. };
  26907. // Statics
  26908. /**
  26909. * Creates a new Submesh from the passed parameters :
  26910. * - materialIndex (integer) : the index of the main mesh material.
  26911. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26912. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26913. * - mesh (Mesh) : the main mesh to create the submesh from.
  26914. * - renderingMesh (optional Mesh) : rendering mesh.
  26915. */
  26916. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26917. var minVertexIndex = Number.MAX_VALUE;
  26918. var maxVertexIndex = -Number.MAX_VALUE;
  26919. renderingMesh = renderingMesh || mesh;
  26920. var indices = renderingMesh.getIndices();
  26921. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26922. var vertexIndex = indices[index];
  26923. if (vertexIndex < minVertexIndex)
  26924. minVertexIndex = vertexIndex;
  26925. if (vertexIndex > maxVertexIndex)
  26926. maxVertexIndex = vertexIndex;
  26927. }
  26928. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26929. };
  26930. return SubMesh;
  26931. }());
  26932. BABYLON.SubMesh = SubMesh;
  26933. })(BABYLON || (BABYLON = {}));
  26934. //# sourceMappingURL=babylon.subMesh.js.map
  26935. var BABYLON;
  26936. (function (BABYLON) {
  26937. var MeshBuilder = (function () {
  26938. function MeshBuilder() {
  26939. }
  26940. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  26941. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  26942. return BABYLON.Mesh.DOUBLESIDE;
  26943. }
  26944. if (orientation === undefined || orientation === null) {
  26945. return BABYLON.Mesh.FRONTSIDE;
  26946. }
  26947. return orientation;
  26948. };
  26949. /**
  26950. * Creates a box mesh.
  26951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  26952. * The parameter `size` sets the size (float) of each box side (default 1).
  26953. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  26954. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  26955. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  26956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26959. */
  26960. MeshBuilder.CreateBox = function (name, options, scene) {
  26961. var box = new BABYLON.Mesh(name, scene);
  26962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26963. box.sideOrientation = options.sideOrientation;
  26964. var vertexData = BABYLON.VertexData.CreateBox(options);
  26965. vertexData.applyToMesh(box, options.updatable);
  26966. return box;
  26967. };
  26968. /**
  26969. * Creates a sphere mesh.
  26970. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  26971. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26972. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  26973. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26974. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  26975. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  26976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26979. */
  26980. MeshBuilder.CreateSphere = function (name, options, scene) {
  26981. var sphere = new BABYLON.Mesh(name, scene);
  26982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26983. sphere.sideOrientation = options.sideOrientation;
  26984. var vertexData = BABYLON.VertexData.CreateSphere(options);
  26985. vertexData.applyToMesh(sphere, options.updatable);
  26986. return sphere;
  26987. };
  26988. /**
  26989. * Creates a plane polygonal mesh. By default, this is a disc.
  26990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  26991. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26992. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  26993. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  26994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26997. */
  26998. MeshBuilder.CreateDisc = function (name, options, scene) {
  26999. var disc = new BABYLON.Mesh(name, scene);
  27000. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27001. disc.sideOrientation = options.sideOrientation;
  27002. var vertexData = BABYLON.VertexData.CreateDisc(options);
  27003. vertexData.applyToMesh(disc, options.updatable);
  27004. return disc;
  27005. };
  27006. /**
  27007. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27008. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  27009. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27010. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  27011. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27012. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  27013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27016. */
  27017. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  27018. var sphere = new BABYLON.Mesh(name, scene);
  27019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27020. sphere.sideOrientation = options.sideOrientation;
  27021. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  27022. vertexData.applyToMesh(sphere, options.updatable);
  27023. return sphere;
  27024. };
  27025. ;
  27026. /**
  27027. * Creates a ribbon mesh.
  27028. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27029. *
  27030. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27031. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27032. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27033. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27034. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  27035. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  27036. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  27037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27039. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  27040. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  27041. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  27042. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  27043. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  27044. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  27045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27046. */
  27047. MeshBuilder.CreateRibbon = function (name, options, scene) {
  27048. var pathArray = options.pathArray;
  27049. var closeArray = options.closeArray;
  27050. var closePath = options.closePath;
  27051. var offset = options.offset;
  27052. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27053. var instance = options.instance;
  27054. var updatable = options.updatable;
  27055. if (instance) {
  27056. // positionFunction : ribbon case
  27057. // only pathArray and sideOrientation parameters are taken into account for positions update
  27058. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  27059. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  27060. var positionFunction = function (positions) {
  27061. var minlg = pathArray[0].length;
  27062. var i = 0;
  27063. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  27064. for (var si = 1; si <= ns; si++) {
  27065. for (var p = 0; p < pathArray.length; p++) {
  27066. var path = pathArray[p];
  27067. var l = path.length;
  27068. minlg = (minlg < l) ? minlg : l;
  27069. var j = 0;
  27070. while (j < minlg) {
  27071. positions[i] = path[j].x;
  27072. positions[i + 1] = path[j].y;
  27073. positions[i + 2] = path[j].z;
  27074. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  27075. BABYLON.Tmp.Vector3[0].x = path[j].x;
  27076. }
  27077. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  27078. BABYLON.Tmp.Vector3[1].x = path[j].x;
  27079. }
  27080. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  27081. BABYLON.Tmp.Vector3[0].y = path[j].y;
  27082. }
  27083. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  27084. BABYLON.Tmp.Vector3[1].y = path[j].y;
  27085. }
  27086. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  27087. BABYLON.Tmp.Vector3[0].z = path[j].z;
  27088. }
  27089. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  27090. BABYLON.Tmp.Vector3[1].z = path[j].z;
  27091. }
  27092. j++;
  27093. i += 3;
  27094. }
  27095. if (instance._closePath) {
  27096. positions[i] = path[0].x;
  27097. positions[i + 1] = path[0].y;
  27098. positions[i + 2] = path[0].z;
  27099. i += 3;
  27100. }
  27101. }
  27102. }
  27103. };
  27104. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27105. positionFunction(positions);
  27106. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  27107. instance._boundingInfo.update(instance._worldMatrix);
  27108. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27109. if (options.colors) {
  27110. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27111. for (var c = 0; c < options.colors.length; c++) {
  27112. colors[c * 4] = options.colors[c].r;
  27113. colors[c * 4 + 1] = options.colors[c].g;
  27114. colors[c * 4 + 2] = options.colors[c].b;
  27115. colors[c * 4 + 3] = options.colors[c].a;
  27116. }
  27117. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  27118. }
  27119. if (options.uvs) {
  27120. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27121. for (var i = 0; i < options.uvs.length; i++) {
  27122. uvs[i * 2] = options.uvs[i].x;
  27123. uvs[i * 2 + 1] = options.uvs[i].y;
  27124. }
  27125. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  27126. }
  27127. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  27128. var indices = instance.getIndices();
  27129. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27130. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  27131. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  27132. if (instance._closePath) {
  27133. var indexFirst = 0;
  27134. var indexLast = 0;
  27135. for (var p = 0; p < pathArray.length; p++) {
  27136. indexFirst = instance._idx[p] * 3;
  27137. if (p + 1 < pathArray.length) {
  27138. indexLast = (instance._idx[p + 1] - 1) * 3;
  27139. }
  27140. else {
  27141. indexLast = normals.length - 3;
  27142. }
  27143. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27144. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27145. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27146. normals[indexLast] = normals[indexFirst];
  27147. normals[indexLast + 1] = normals[indexFirst + 1];
  27148. normals[indexLast + 2] = normals[indexFirst + 2];
  27149. }
  27150. }
  27151. if (!(instance.areNormalsFrozen)) {
  27152. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27153. }
  27154. }
  27155. return instance;
  27156. }
  27157. else {
  27158. var ribbon = new BABYLON.Mesh(name, scene);
  27159. ribbon.sideOrientation = sideOrientation;
  27160. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  27161. if (closePath) {
  27162. ribbon._idx = vertexData._idx;
  27163. }
  27164. ribbon._closePath = closePath;
  27165. ribbon._closeArray = closeArray;
  27166. vertexData.applyToMesh(ribbon, updatable);
  27167. return ribbon;
  27168. }
  27169. };
  27170. /**
  27171. * Creates a cylinder or a cone mesh.
  27172. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  27173. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27174. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27175. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  27176. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27177. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27178. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  27179. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  27180. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  27181. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  27182. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  27183. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  27184. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  27185. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  27186. * If `enclose` is false, a ring surface is one element.
  27187. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  27188. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  27189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27190. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27192. */
  27193. MeshBuilder.CreateCylinder = function (name, options, scene) {
  27194. var cylinder = new BABYLON.Mesh(name, scene);
  27195. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27196. cylinder.sideOrientation = options.sideOrientation;
  27197. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  27198. vertexData.applyToMesh(cylinder, options.updatable);
  27199. return cylinder;
  27200. };
  27201. /**
  27202. * Creates a torus mesh.
  27203. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  27204. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27205. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27206. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27210. */
  27211. MeshBuilder.CreateTorus = function (name, options, scene) {
  27212. var torus = new BABYLON.Mesh(name, scene);
  27213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27214. torus.sideOrientation = options.sideOrientation;
  27215. var vertexData = BABYLON.VertexData.CreateTorus(options);
  27216. vertexData.applyToMesh(torus, options.updatable);
  27217. return torus;
  27218. };
  27219. /**
  27220. * Creates a torus knot mesh.
  27221. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  27222. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27223. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27224. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27225. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27226. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27227. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27228. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27229. */
  27230. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  27231. var torusKnot = new BABYLON.Mesh(name, scene);
  27232. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27233. torusKnot.sideOrientation = options.sideOrientation;
  27234. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  27235. vertexData.applyToMesh(torusKnot, options.updatable);
  27236. return torusKnot;
  27237. };
  27238. /**
  27239. * Creates a line system mesh.
  27240. * A line system is a pool of many lines gathered in a single mesh.
  27241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  27242. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  27243. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  27244. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  27245. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  27246. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  27247. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  27248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27249. */
  27250. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  27251. var instance = options.instance;
  27252. var lines = options.lines;
  27253. if (instance) {
  27254. var positionFunction = function (positions) {
  27255. var i = 0;
  27256. for (var l = 0; l < lines.length; l++) {
  27257. var points = lines[l];
  27258. for (var p = 0; p < points.length; p++) {
  27259. positions[i] = points[p].x;
  27260. positions[i + 1] = points[p].y;
  27261. positions[i + 2] = points[p].z;
  27262. i += 3;
  27263. }
  27264. }
  27265. };
  27266. instance.updateMeshPositions(positionFunction, false);
  27267. return instance;
  27268. }
  27269. // line system creation
  27270. var lineSystem = new BABYLON.LinesMesh(name, scene);
  27271. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  27272. vertexData.applyToMesh(lineSystem, options.updatable);
  27273. return lineSystem;
  27274. };
  27275. /**
  27276. * Creates a line mesh.
  27277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  27278. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  27279. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27280. * The parameter `points` is an array successive Vector3.
  27281. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  27282. * When updating an instance, remember that only point positions can change, not the number of points.
  27283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27284. */
  27285. MeshBuilder.CreateLines = function (name, options, scene) {
  27286. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  27287. return lines;
  27288. };
  27289. /**
  27290. * Creates a dashed line mesh.
  27291. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  27292. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  27293. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27294. * The parameter `points` is an array successive Vector3.
  27295. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27296. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27297. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27298. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  27299. * When updating an instance, remember that only point positions can change, not the number of points.
  27300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27301. */
  27302. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  27303. var points = options.points;
  27304. var instance = options.instance;
  27305. var gapSize = options.gapSize;
  27306. var dashNb = options.dashNb;
  27307. var dashSize = options.dashSize;
  27308. if (instance) {
  27309. var positionFunction = function (positions) {
  27310. var curvect = BABYLON.Vector3.Zero();
  27311. var nbSeg = positions.length / 6;
  27312. var lg = 0;
  27313. var nb = 0;
  27314. var shft = 0;
  27315. var dashshft = 0;
  27316. var curshft = 0;
  27317. var p = 0;
  27318. var i = 0;
  27319. var j = 0;
  27320. for (i = 0; i < points.length - 1; i++) {
  27321. points[i + 1].subtractToRef(points[i], curvect);
  27322. lg += curvect.length();
  27323. }
  27324. shft = lg / nbSeg;
  27325. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  27326. for (i = 0; i < points.length - 1; i++) {
  27327. points[i + 1].subtractToRef(points[i], curvect);
  27328. nb = Math.floor(curvect.length() / shft);
  27329. curvect.normalize();
  27330. j = 0;
  27331. while (j < nb && p < positions.length) {
  27332. curshft = shft * j;
  27333. positions[p] = points[i].x + curshft * curvect.x;
  27334. positions[p + 1] = points[i].y + curshft * curvect.y;
  27335. positions[p + 2] = points[i].z + curshft * curvect.z;
  27336. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  27337. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  27338. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  27339. p += 6;
  27340. j++;
  27341. }
  27342. }
  27343. while (p < positions.length) {
  27344. positions[p] = points[i].x;
  27345. positions[p + 1] = points[i].y;
  27346. positions[p + 2] = points[i].z;
  27347. p += 3;
  27348. }
  27349. };
  27350. instance.updateMeshPositions(positionFunction, false);
  27351. return instance;
  27352. }
  27353. // dashed lines creation
  27354. var dashedLines = new BABYLON.LinesMesh(name, scene);
  27355. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  27356. vertexData.applyToMesh(dashedLines, options.updatable);
  27357. dashedLines.dashSize = dashSize;
  27358. dashedLines.gapSize = gapSize;
  27359. return dashedLines;
  27360. };
  27361. /**
  27362. * Creates an extruded shape mesh.
  27363. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27364. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  27365. *
  27366. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27367. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  27368. * extruded along the Z axis.
  27369. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27370. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  27371. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27372. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  27373. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  27374. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27375. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27376. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27377. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  27378. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27379. */
  27380. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  27381. var path = options.path;
  27382. var shape = options.shape;
  27383. var scale = options.scale || 1;
  27384. var rotation = options.rotation || 0;
  27385. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  27386. var updatable = options.updatable;
  27387. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27388. var instance = options.instance;
  27389. var invertUV = options.invertUV || false;
  27390. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  27391. };
  27392. /**
  27393. * Creates an custom extruded shape mesh.
  27394. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27395. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  27396. *
  27397. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27398. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  27399. * extruded along the Z axis.
  27400. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27401. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  27402. * and the distance of this point from the begining of the path :
  27403. * ```javascript
  27404. * var rotationFunction = function(i, distance) {
  27405. * // do things
  27406. * return rotationValue; }
  27407. * ```
  27408. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27409. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  27410. * and the distance of this point from the begining of the path :
  27411. * ```javascript
  27412. * var scaleFunction = function(i, distance) {
  27413. * // do things
  27414. * return scaleValue;}
  27415. * ```
  27416. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27417. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27418. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27419. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  27420. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  27421. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27424. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  27425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27426. */
  27427. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  27428. var path = options.path;
  27429. var shape = options.shape;
  27430. var scaleFunction = options.scaleFunction || (function () { return 1; });
  27431. var rotationFunction = options.rotationFunction || (function () { return 0; });
  27432. var ribbonCloseArray = options.ribbonCloseArray || false;
  27433. var ribbonClosePath = options.ribbonClosePath || false;
  27434. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  27435. var updatable = options.updatable;
  27436. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27437. var instance = options.instance;
  27438. var invertUV = options.invertUV || false;
  27439. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  27440. };
  27441. /**
  27442. * Creates lathe mesh.
  27443. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27444. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  27445. *
  27446. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  27447. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27448. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27449. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27450. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  27451. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  27452. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  27453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27455. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  27456. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27457. */
  27458. MeshBuilder.CreateLathe = function (name, options, scene) {
  27459. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  27460. var closed = (options.closed === undefined) ? true : options.closed;
  27461. var shape = options.shape;
  27462. var radius = options.radius || 1;
  27463. var tessellation = options.tessellation || 64;
  27464. var updatable = options.updatable;
  27465. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27466. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  27467. var pi2 = Math.PI * 2;
  27468. var paths = new Array();
  27469. var invertUV = options.invertUV || false;
  27470. var i = 0;
  27471. var p = 0;
  27472. var step = pi2 / tessellation * arc;
  27473. var rotated;
  27474. var path = new Array();
  27475. ;
  27476. for (i = 0; i <= tessellation; i++) {
  27477. var path = [];
  27478. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  27479. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  27480. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  27481. }
  27482. for (p = 0; p < shape.length; p++) {
  27483. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  27484. path.push(rotated);
  27485. }
  27486. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  27487. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  27488. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  27489. }
  27490. paths.push(path);
  27491. }
  27492. // lathe ribbon
  27493. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  27494. return lathe;
  27495. };
  27496. /**
  27497. * Creates a plane mesh.
  27498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  27499. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27500. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  27501. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  27502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27505. */
  27506. MeshBuilder.CreatePlane = function (name, options, scene) {
  27507. var plane = new BABYLON.Mesh(name, scene);
  27508. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27509. plane.sideOrientation = options.sideOrientation;
  27510. var vertexData = BABYLON.VertexData.CreatePlane(options);
  27511. vertexData.applyToMesh(plane, options.updatable);
  27512. if (options.sourcePlane) {
  27513. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  27514. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  27515. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  27516. plane.rotate(vectorProduct, product);
  27517. }
  27518. return plane;
  27519. };
  27520. /**
  27521. * Creates a ground mesh.
  27522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  27523. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27524. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27526. */
  27527. MeshBuilder.CreateGround = function (name, options, scene) {
  27528. var ground = new BABYLON.GroundMesh(name, scene);
  27529. ground._setReady(false);
  27530. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27531. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27532. ground._width = options.width || 1;
  27533. ground._height = options.height || 1;
  27534. ground._maxX = ground._width / 2;
  27535. ground._maxZ = ground._height / 2;
  27536. ground._minX = -ground._maxX;
  27537. ground._minZ = -ground._maxZ;
  27538. var vertexData = BABYLON.VertexData.CreateGround(options);
  27539. vertexData.applyToMesh(ground, options.updatable);
  27540. ground._setReady(true);
  27541. return ground;
  27542. };
  27543. /**
  27544. * Creates a tiled ground mesh.
  27545. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  27546. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27547. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27548. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27549. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27550. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27551. * numbers of subdivisions on the ground width and height of each tile.
  27552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27553. */
  27554. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  27555. var tiledGround = new BABYLON.Mesh(name, scene);
  27556. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  27557. vertexData.applyToMesh(tiledGround, options.updatable);
  27558. return tiledGround;
  27559. };
  27560. /**
  27561. * Creates a ground mesh from a height map.
  27562. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27563. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  27564. * The parameter `url` sets the URL of the height map image resource.
  27565. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27566. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27567. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27568. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27569. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  27570. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  27571. * This function is passed the newly built mesh :
  27572. * ```javascript
  27573. * function(mesh) { // do things
  27574. * return; }
  27575. * ```
  27576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27577. */
  27578. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  27579. var width = options.width || 10.0;
  27580. var height = options.height || 10.0;
  27581. var subdivisions = options.subdivisions || 1 | 0;
  27582. var minHeight = options.minHeight || 0.0;
  27583. var maxHeight = options.maxHeight || 10.0;
  27584. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27585. var updatable = options.updatable;
  27586. var onReady = options.onReady;
  27587. var ground = new BABYLON.GroundMesh(name, scene);
  27588. ground._subdivisionsX = subdivisions;
  27589. ground._subdivisionsY = subdivisions;
  27590. ground._width = width;
  27591. ground._height = height;
  27592. ground._maxX = ground._width / 2.0;
  27593. ground._maxZ = ground._height / 2.0;
  27594. ground._minX = -ground._maxX;
  27595. ground._minZ = -ground._maxZ;
  27596. ground._setReady(false);
  27597. var onload = function (img) {
  27598. // Getting height map data
  27599. var canvas = document.createElement("canvas");
  27600. var context = canvas.getContext("2d");
  27601. var bufferWidth = img.width;
  27602. var bufferHeight = img.height;
  27603. canvas.width = bufferWidth;
  27604. canvas.height = bufferHeight;
  27605. context.drawImage(img, 0, 0);
  27606. // Create VertexData from map data
  27607. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  27608. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  27609. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  27610. width: width, height: height,
  27611. subdivisions: subdivisions,
  27612. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  27613. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  27614. });
  27615. vertexData.applyToMesh(ground, updatable);
  27616. ground._setReady(true);
  27617. //execute ready callback, if set
  27618. if (onReady) {
  27619. onReady(ground);
  27620. }
  27621. };
  27622. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  27623. return ground;
  27624. };
  27625. /**
  27626. * Creates a tube mesh.
  27627. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  27628. *
  27629. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  27630. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27631. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27632. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27633. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27634. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  27635. * It must return a radius value (positive float) :
  27636. * ```javascript
  27637. * var radiusFunction = function(i, distance) {
  27638. * // do things
  27639. * return radius; }
  27640. * ```
  27641. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  27642. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  27643. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  27644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27646. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  27647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27648. */
  27649. MeshBuilder.CreateTube = function (name, options, scene) {
  27650. var path = options.path;
  27651. var radius = options.radius || 1.0;
  27652. var tessellation = options.tessellation || 64 | 0;
  27653. var radiusFunction = options.radiusFunction;
  27654. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  27655. var invertUV = options.invertUV || false;
  27656. var updatable = options.updatable;
  27657. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27658. var instance = options.instance;
  27659. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  27660. // tube geometry
  27661. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  27662. var tangents = path3D.getTangents();
  27663. var normals = path3D.getNormals();
  27664. var distances = path3D.getDistances();
  27665. var pi2 = Math.PI * 2;
  27666. var step = pi2 / tessellation * arc;
  27667. var returnRadius = function () { return radius; };
  27668. var radiusFunctionFinal = radiusFunction || returnRadius;
  27669. var circlePath;
  27670. var rad;
  27671. var normal;
  27672. var rotated;
  27673. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  27674. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  27675. for (var i = 0; i < path.length; i++) {
  27676. rad = radiusFunctionFinal(i, distances[i]); // current radius
  27677. circlePath = Array(); // current circle array
  27678. normal = normals[i]; // current normal
  27679. for (var t = 0; t < tessellation; t++) {
  27680. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  27681. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  27682. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  27683. rotated.scaleInPlace(rad).addInPlace(path[i]);
  27684. circlePath[t] = rotated;
  27685. }
  27686. circlePaths[index] = circlePath;
  27687. index++;
  27688. }
  27689. // cap
  27690. var capPath = function (nbPoints, pathIndex) {
  27691. var pointCap = Array();
  27692. for (var i = 0; i < nbPoints; i++) {
  27693. pointCap.push(path[pathIndex]);
  27694. }
  27695. return pointCap;
  27696. };
  27697. switch (cap) {
  27698. case BABYLON.Mesh.NO_CAP:
  27699. break;
  27700. case BABYLON.Mesh.CAP_START:
  27701. circlePaths[0] = capPath(tessellation, 0);
  27702. circlePaths[1] = circlePaths[2].slice(0);
  27703. break;
  27704. case BABYLON.Mesh.CAP_END:
  27705. circlePaths[index] = circlePaths[index - 1].slice(0);
  27706. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  27707. break;
  27708. case BABYLON.Mesh.CAP_ALL:
  27709. circlePaths[0] = capPath(tessellation, 0);
  27710. circlePaths[1] = circlePaths[2].slice(0);
  27711. circlePaths[index] = circlePaths[index - 1].slice(0);
  27712. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  27713. break;
  27714. default:
  27715. break;
  27716. }
  27717. return circlePaths;
  27718. };
  27719. var path3D;
  27720. var pathArray;
  27721. if (instance) {
  27722. var arc = options.arc || instance.arc;
  27723. path3D = (instance.path3D).update(path);
  27724. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  27725. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  27726. instance.path3D = path3D;
  27727. instance.pathArray = pathArray;
  27728. instance.arc = arc;
  27729. return instance;
  27730. }
  27731. // tube creation
  27732. path3D = new BABYLON.Path3D(path);
  27733. var newPathArray = new Array();
  27734. cap = (cap < 0 || cap > 3) ? 0 : cap;
  27735. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  27736. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  27737. tube.pathArray = pathArray;
  27738. tube.path3D = path3D;
  27739. tube.tessellation = tessellation;
  27740. tube.cap = cap;
  27741. tube.arc = options.arc;
  27742. return tube;
  27743. };
  27744. /**
  27745. * Creates a polyhedron mesh.
  27746. *
  27747. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  27748. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  27749. * to choose the wanted type.
  27750. * The parameter `size` (positive float, default 1) sets the polygon size.
  27751. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27752. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  27753. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  27754. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  27755. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  27756. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  27757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27758. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27760. */
  27761. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  27762. var polyhedron = new BABYLON.Mesh(name, scene);
  27763. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  27764. polyhedron.sideOrientation = options.sideOrientation;
  27765. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  27766. vertexData.applyToMesh(polyhedron, options.updatable);
  27767. return polyhedron;
  27768. };
  27769. /**
  27770. * Creates a decal mesh.
  27771. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  27772. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  27773. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27774. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27775. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27776. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27777. */
  27778. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  27779. var indices = sourceMesh.getIndices();
  27780. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27781. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27782. var position = options.position || BABYLON.Vector3.Zero();
  27783. var normal = options.normal || BABYLON.Vector3.Up();
  27784. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  27785. var angle = options.angle || 0;
  27786. // Getting correct rotation
  27787. if (!normal) {
  27788. var target = new BABYLON.Vector3(0, 0, 1);
  27789. var camera = sourceMesh.getScene().activeCamera;
  27790. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  27791. normal = camera.globalPosition.subtract(cameraWorldTarget);
  27792. }
  27793. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  27794. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  27795. var pitch = Math.atan2(normal.y, len);
  27796. // Matrix
  27797. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  27798. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  27799. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  27800. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  27801. var vertexData = new BABYLON.VertexData();
  27802. vertexData.indices = [];
  27803. vertexData.positions = [];
  27804. vertexData.normals = [];
  27805. vertexData.uvs = [];
  27806. var currentVertexDataIndex = 0;
  27807. var extractDecalVector3 = function (indexId) {
  27808. var vertexId = indices[indexId];
  27809. var result = new BABYLON.PositionNormalVertex();
  27810. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  27811. // Send vector to decal local world
  27812. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  27813. // Get normal
  27814. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  27815. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  27816. return result;
  27817. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  27818. var clip = function (vertices, axis) {
  27819. if (vertices.length === 0) {
  27820. return vertices;
  27821. }
  27822. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  27823. var clipVertices = function (v0, v1) {
  27824. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  27825. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  27826. };
  27827. var result = new Array();
  27828. for (var index = 0; index < vertices.length; index += 3) {
  27829. var v1Out;
  27830. var v2Out;
  27831. var v3Out;
  27832. var total = 0;
  27833. var nV1, nV2, nV3, nV4;
  27834. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  27835. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  27836. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  27837. v1Out = d1 > 0;
  27838. v2Out = d2 > 0;
  27839. v3Out = d3 > 0;
  27840. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  27841. switch (total) {
  27842. case 0:
  27843. result.push(vertices[index]);
  27844. result.push(vertices[index + 1]);
  27845. result.push(vertices[index + 2]);
  27846. break;
  27847. case 1:
  27848. if (v1Out) {
  27849. nV1 = vertices[index + 1];
  27850. nV2 = vertices[index + 2];
  27851. nV3 = clipVertices(vertices[index], nV1);
  27852. nV4 = clipVertices(vertices[index], nV2);
  27853. }
  27854. if (v2Out) {
  27855. nV1 = vertices[index];
  27856. nV2 = vertices[index + 2];
  27857. nV3 = clipVertices(vertices[index + 1], nV1);
  27858. nV4 = clipVertices(vertices[index + 1], nV2);
  27859. result.push(nV3);
  27860. result.push(nV2.clone());
  27861. result.push(nV1.clone());
  27862. result.push(nV2.clone());
  27863. result.push(nV3.clone());
  27864. result.push(nV4);
  27865. break;
  27866. }
  27867. if (v3Out) {
  27868. nV1 = vertices[index];
  27869. nV2 = vertices[index + 1];
  27870. nV3 = clipVertices(vertices[index + 2], nV1);
  27871. nV4 = clipVertices(vertices[index + 2], nV2);
  27872. }
  27873. result.push(nV1.clone());
  27874. result.push(nV2.clone());
  27875. result.push(nV3);
  27876. result.push(nV4);
  27877. result.push(nV3.clone());
  27878. result.push(nV2.clone());
  27879. break;
  27880. case 2:
  27881. if (!v1Out) {
  27882. nV1 = vertices[index].clone();
  27883. nV2 = clipVertices(nV1, vertices[index + 1]);
  27884. nV3 = clipVertices(nV1, vertices[index + 2]);
  27885. result.push(nV1);
  27886. result.push(nV2);
  27887. result.push(nV3);
  27888. }
  27889. if (!v2Out) {
  27890. nV1 = vertices[index + 1].clone();
  27891. nV2 = clipVertices(nV1, vertices[index + 2]);
  27892. nV3 = clipVertices(nV1, vertices[index]);
  27893. result.push(nV1);
  27894. result.push(nV2);
  27895. result.push(nV3);
  27896. }
  27897. if (!v3Out) {
  27898. nV1 = vertices[index + 2].clone();
  27899. nV2 = clipVertices(nV1, vertices[index]);
  27900. nV3 = clipVertices(nV1, vertices[index + 1]);
  27901. result.push(nV1);
  27902. result.push(nV2);
  27903. result.push(nV3);
  27904. }
  27905. break;
  27906. case 3:
  27907. break;
  27908. }
  27909. }
  27910. return result;
  27911. };
  27912. for (var index = 0; index < indices.length; index += 3) {
  27913. var faceVertices = new Array();
  27914. faceVertices.push(extractDecalVector3(index));
  27915. faceVertices.push(extractDecalVector3(index + 1));
  27916. faceVertices.push(extractDecalVector3(index + 2));
  27917. // Clip
  27918. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  27919. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  27920. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  27921. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  27922. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  27923. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  27924. if (faceVertices.length === 0) {
  27925. continue;
  27926. }
  27927. // Add UVs and get back to world
  27928. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  27929. var vertex = faceVertices[vIndex];
  27930. //TODO check for Int32Array | Uint32Array | Uint16Array
  27931. vertexData.indices.push(currentVertexDataIndex);
  27932. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  27933. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  27934. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  27935. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  27936. currentVertexDataIndex++;
  27937. }
  27938. }
  27939. // Return mesh
  27940. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  27941. vertexData.applyToMesh(decal);
  27942. decal.position = position.clone();
  27943. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  27944. return decal;
  27945. };
  27946. // Privates
  27947. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  27948. // extrusion geometry
  27949. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  27950. var tangents = path3D.getTangents();
  27951. var normals = path3D.getNormals();
  27952. var binormals = path3D.getBinormals();
  27953. var distances = path3D.getDistances();
  27954. var angle = 0;
  27955. var returnScale = function () { return scale; };
  27956. var returnRotation = function () { return rotation; };
  27957. var rotate = custom ? rotateFunction : returnRotation;
  27958. var scl = custom ? scaleFunction : returnScale;
  27959. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  27960. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  27961. for (var i = 0; i < curve.length; i++) {
  27962. var shapePath = new Array();
  27963. var angleStep = rotate(i, distances[i]);
  27964. var scaleRatio = scl(i, distances[i]);
  27965. for (var p = 0; p < shape.length; p++) {
  27966. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  27967. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  27968. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  27969. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  27970. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  27971. shapePath[p] = rotated;
  27972. }
  27973. shapePaths[index] = shapePath;
  27974. angle += angleStep;
  27975. index++;
  27976. }
  27977. // cap
  27978. var capPath = function (shapePath) {
  27979. var pointCap = Array();
  27980. var barycenter = BABYLON.Vector3.Zero();
  27981. var i;
  27982. for (i = 0; i < shapePath.length; i++) {
  27983. barycenter.addInPlace(shapePath[i]);
  27984. }
  27985. barycenter.scaleInPlace(1.0 / shapePath.length);
  27986. for (i = 0; i < shapePath.length; i++) {
  27987. pointCap.push(barycenter);
  27988. }
  27989. return pointCap;
  27990. };
  27991. switch (cap) {
  27992. case BABYLON.Mesh.NO_CAP:
  27993. break;
  27994. case BABYLON.Mesh.CAP_START:
  27995. shapePaths[0] = capPath(shapePaths[2]);
  27996. shapePaths[1] = shapePaths[2];
  27997. break;
  27998. case BABYLON.Mesh.CAP_END:
  27999. shapePaths[index] = shapePaths[index - 1];
  28000. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  28001. break;
  28002. case BABYLON.Mesh.CAP_ALL:
  28003. shapePaths[0] = capPath(shapePaths[2]);
  28004. shapePaths[1] = shapePaths[2];
  28005. shapePaths[index] = shapePaths[index - 1];
  28006. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  28007. break;
  28008. default:
  28009. break;
  28010. }
  28011. return shapePaths;
  28012. };
  28013. var path3D;
  28014. var pathArray;
  28015. if (instance) {
  28016. path3D = (instance.path3D).update(curve);
  28017. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  28018. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  28019. return instance;
  28020. }
  28021. // extruded shape creation
  28022. path3D = new BABYLON.Path3D(curve);
  28023. var newShapePaths = new Array();
  28024. cap = (cap < 0 || cap > 3) ? 0 : cap;
  28025. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  28026. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  28027. extrudedGeneric.pathArray = pathArray;
  28028. extrudedGeneric.path3D = path3D;
  28029. extrudedGeneric.cap = cap;
  28030. return extrudedGeneric;
  28031. };
  28032. return MeshBuilder;
  28033. }());
  28034. BABYLON.MeshBuilder = MeshBuilder;
  28035. })(BABYLON || (BABYLON = {}));
  28036. //# sourceMappingURL=babylon.meshBuilder.js.map
  28037. var BABYLON;
  28038. (function (BABYLON) {
  28039. var BaseTexture = (function () {
  28040. function BaseTexture(scene) {
  28041. this._hasAlpha = false;
  28042. this.getAlphaFromRGB = false;
  28043. this.level = 1;
  28044. this.coordinatesIndex = 0;
  28045. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  28046. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28047. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28048. this.anisotropicFilteringLevel = 4;
  28049. this.isCube = false;
  28050. this.isRenderTarget = false;
  28051. this.animations = new Array();
  28052. /**
  28053. * An event triggered when the texture is disposed.
  28054. * @type {BABYLON.Observable}
  28055. */
  28056. this.onDisposeObservable = new BABYLON.Observable();
  28057. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28058. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28059. this._scene.textures.push(this);
  28060. this._uid = null;
  28061. }
  28062. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  28063. get: function () {
  28064. return this._hasAlpha;
  28065. },
  28066. set: function (value) {
  28067. if (this._hasAlpha === value) {
  28068. return;
  28069. }
  28070. this._hasAlpha = value;
  28071. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28072. },
  28073. enumerable: true,
  28074. configurable: true
  28075. });
  28076. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  28077. get: function () {
  28078. return this._coordinatesMode;
  28079. },
  28080. set: function (value) {
  28081. if (this._coordinatesMode === value) {
  28082. return;
  28083. }
  28084. this._coordinatesMode = value;
  28085. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28086. },
  28087. enumerable: true,
  28088. configurable: true
  28089. });
  28090. Object.defineProperty(BaseTexture.prototype, "uid", {
  28091. get: function () {
  28092. if (!this._uid) {
  28093. this._uid = BABYLON.Tools.RandomId();
  28094. }
  28095. return this._uid;
  28096. },
  28097. enumerable: true,
  28098. configurable: true
  28099. });
  28100. BaseTexture.prototype.toString = function () {
  28101. return this.name;
  28102. };
  28103. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  28104. set: function (callback) {
  28105. if (this._onDisposeObserver) {
  28106. this.onDisposeObservable.remove(this._onDisposeObserver);
  28107. }
  28108. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28109. },
  28110. enumerable: true,
  28111. configurable: true
  28112. });
  28113. BaseTexture.prototype.getScene = function () {
  28114. return this._scene;
  28115. };
  28116. BaseTexture.prototype.getTextureMatrix = function () {
  28117. return null;
  28118. };
  28119. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  28120. return null;
  28121. };
  28122. BaseTexture.prototype.getInternalTexture = function () {
  28123. return this._texture;
  28124. };
  28125. BaseTexture.prototype.isReady = function () {
  28126. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28127. return true;
  28128. }
  28129. if (this._texture) {
  28130. return this._texture.isReady;
  28131. }
  28132. return false;
  28133. };
  28134. BaseTexture.prototype.getSize = function () {
  28135. if (this._texture._width) {
  28136. return new BABYLON.Size(this._texture._width, this._texture._height);
  28137. }
  28138. if (this._texture._size) {
  28139. return new BABYLON.Size(this._texture._size, this._texture._size);
  28140. }
  28141. return BABYLON.Size.Zero();
  28142. };
  28143. BaseTexture.prototype.getBaseSize = function () {
  28144. if (!this.isReady() || !this._texture)
  28145. return BABYLON.Size.Zero();
  28146. if (this._texture._size) {
  28147. return new BABYLON.Size(this._texture._size, this._texture._size);
  28148. }
  28149. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  28150. };
  28151. BaseTexture.prototype.scale = function (ratio) {
  28152. };
  28153. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  28154. get: function () {
  28155. return false;
  28156. },
  28157. enumerable: true,
  28158. configurable: true
  28159. });
  28160. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  28161. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  28162. for (var index = 0; index < texturesCache.length; index++) {
  28163. var texturesCacheEntry = texturesCache[index];
  28164. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  28165. texturesCache.splice(index, 1);
  28166. return;
  28167. }
  28168. }
  28169. };
  28170. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  28171. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  28172. for (var index = 0; index < texturesCache.length; index++) {
  28173. var texturesCacheEntry = texturesCache[index];
  28174. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  28175. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  28176. texturesCacheEntry.references++;
  28177. return texturesCacheEntry;
  28178. }
  28179. }
  28180. }
  28181. return null;
  28182. };
  28183. BaseTexture.prototype.delayLoad = function () {
  28184. };
  28185. BaseTexture.prototype.clone = function () {
  28186. return null;
  28187. };
  28188. BaseTexture.prototype.releaseInternalTexture = function () {
  28189. if (this._texture) {
  28190. this._scene.getEngine().releaseInternalTexture(this._texture);
  28191. delete this._texture;
  28192. }
  28193. };
  28194. BaseTexture.prototype.dispose = function () {
  28195. // Animations
  28196. this.getScene().stopAnimation(this);
  28197. // Remove from scene
  28198. this._scene._removePendingData(this);
  28199. var index = this._scene.textures.indexOf(this);
  28200. if (index >= 0) {
  28201. this._scene.textures.splice(index, 1);
  28202. }
  28203. if (this._texture === undefined) {
  28204. return;
  28205. }
  28206. // Release
  28207. this.releaseInternalTexture();
  28208. // Callback
  28209. this.onDisposeObservable.notifyObservers(this);
  28210. this.onDisposeObservable.clear();
  28211. };
  28212. BaseTexture.prototype.serialize = function () {
  28213. if (!this.name) {
  28214. return null;
  28215. }
  28216. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28217. // Animations
  28218. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28219. return serializationObject;
  28220. };
  28221. return BaseTexture;
  28222. }());
  28223. __decorate([
  28224. BABYLON.serialize()
  28225. ], BaseTexture.prototype, "name", void 0);
  28226. __decorate([
  28227. BABYLON.serialize("hasAlpha")
  28228. ], BaseTexture.prototype, "_hasAlpha", void 0);
  28229. __decorate([
  28230. BABYLON.serialize()
  28231. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  28232. __decorate([
  28233. BABYLON.serialize()
  28234. ], BaseTexture.prototype, "level", void 0);
  28235. __decorate([
  28236. BABYLON.serialize()
  28237. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  28238. __decorate([
  28239. BABYLON.serialize("coordinatesMode")
  28240. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  28241. __decorate([
  28242. BABYLON.serialize()
  28243. ], BaseTexture.prototype, "wrapU", void 0);
  28244. __decorate([
  28245. BABYLON.serialize()
  28246. ], BaseTexture.prototype, "wrapV", void 0);
  28247. __decorate([
  28248. BABYLON.serialize()
  28249. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  28250. __decorate([
  28251. BABYLON.serialize()
  28252. ], BaseTexture.prototype, "isCube", void 0);
  28253. __decorate([
  28254. BABYLON.serialize()
  28255. ], BaseTexture.prototype, "isRenderTarget", void 0);
  28256. BABYLON.BaseTexture = BaseTexture;
  28257. })(BABYLON || (BABYLON = {}));
  28258. //# sourceMappingURL=babylon.baseTexture.js.map
  28259. var BABYLON;
  28260. (function (BABYLON) {
  28261. var Texture = (function (_super) {
  28262. __extends(Texture, _super);
  28263. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  28264. if (noMipmap === void 0) { noMipmap = false; }
  28265. if (invertY === void 0) { invertY = true; }
  28266. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28267. if (onLoad === void 0) { onLoad = null; }
  28268. if (onError === void 0) { onError = null; }
  28269. if (buffer === void 0) { buffer = null; }
  28270. if (deleteBuffer === void 0) { deleteBuffer = false; }
  28271. var _this = _super.call(this, scene) || this;
  28272. _this.uOffset = 0;
  28273. _this.vOffset = 0;
  28274. _this.uScale = 1.0;
  28275. _this.vScale = 1.0;
  28276. _this.uAng = 0;
  28277. _this.vAng = 0;
  28278. _this.wAng = 0;
  28279. _this.name = url;
  28280. _this.url = url;
  28281. _this._noMipmap = noMipmap;
  28282. _this._invertY = invertY;
  28283. _this._samplingMode = samplingMode;
  28284. _this._buffer = buffer;
  28285. _this._deleteBuffer = deleteBuffer;
  28286. _this._format = format;
  28287. if (!url) {
  28288. return _this;
  28289. }
  28290. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  28291. var load = function () {
  28292. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  28293. _this.onLoadObservable.notifyObservers(true);
  28294. }
  28295. if (onLoad) {
  28296. onLoad();
  28297. }
  28298. };
  28299. if (!_this._texture) {
  28300. if (!scene.useDelayedTextureLoading) {
  28301. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  28302. if (deleteBuffer) {
  28303. delete _this._buffer;
  28304. }
  28305. }
  28306. else {
  28307. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28308. _this._delayedOnLoad = load;
  28309. _this._delayedOnError = onError;
  28310. }
  28311. }
  28312. else {
  28313. if (_this._texture.isReady) {
  28314. BABYLON.Tools.SetImmediate(function () { return load(); });
  28315. }
  28316. else {
  28317. _this._texture.onLoadedCallbacks.push(load);
  28318. }
  28319. }
  28320. return _this;
  28321. }
  28322. Object.defineProperty(Texture.prototype, "noMipmap", {
  28323. get: function () {
  28324. return this._noMipmap;
  28325. },
  28326. enumerable: true,
  28327. configurable: true
  28328. });
  28329. Texture.prototype.delayLoad = function () {
  28330. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28331. return;
  28332. }
  28333. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28334. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  28335. if (!this._texture) {
  28336. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  28337. if (this._deleteBuffer) {
  28338. delete this._buffer;
  28339. }
  28340. }
  28341. };
  28342. Texture.prototype.updateSamplingMode = function (samplingMode) {
  28343. if (!this._texture) {
  28344. return;
  28345. }
  28346. this._samplingMode = samplingMode;
  28347. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  28348. };
  28349. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  28350. x *= this.uScale;
  28351. y *= this.vScale;
  28352. x -= 0.5 * this.uScale;
  28353. y -= 0.5 * this.vScale;
  28354. z -= 0.5;
  28355. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  28356. t.x += 0.5 * this.uScale + this.uOffset;
  28357. t.y += 0.5 * this.vScale + this.vOffset;
  28358. t.z += 0.5;
  28359. };
  28360. Texture.prototype.getTextureMatrix = function () {
  28361. if (this.uOffset === this._cachedUOffset &&
  28362. this.vOffset === this._cachedVOffset &&
  28363. this.uScale === this._cachedUScale &&
  28364. this.vScale === this._cachedVScale &&
  28365. this.uAng === this._cachedUAng &&
  28366. this.vAng === this._cachedVAng &&
  28367. this.wAng === this._cachedWAng) {
  28368. return this._cachedTextureMatrix;
  28369. }
  28370. this._cachedUOffset = this.uOffset;
  28371. this._cachedVOffset = this.vOffset;
  28372. this._cachedUScale = this.uScale;
  28373. this._cachedVScale = this.vScale;
  28374. this._cachedUAng = this.uAng;
  28375. this._cachedVAng = this.vAng;
  28376. this._cachedWAng = this.wAng;
  28377. if (!this._cachedTextureMatrix) {
  28378. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  28379. this._rowGenerationMatrix = new BABYLON.Matrix();
  28380. this._t0 = BABYLON.Vector3.Zero();
  28381. this._t1 = BABYLON.Vector3.Zero();
  28382. this._t2 = BABYLON.Vector3.Zero();
  28383. }
  28384. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  28385. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  28386. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  28387. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  28388. this._t1.subtractInPlace(this._t0);
  28389. this._t2.subtractInPlace(this._t0);
  28390. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28391. this._cachedTextureMatrix.m[0] = this._t1.x;
  28392. this._cachedTextureMatrix.m[1] = this._t1.y;
  28393. this._cachedTextureMatrix.m[2] = this._t1.z;
  28394. this._cachedTextureMatrix.m[4] = this._t2.x;
  28395. this._cachedTextureMatrix.m[5] = this._t2.y;
  28396. this._cachedTextureMatrix.m[6] = this._t2.z;
  28397. this._cachedTextureMatrix.m[8] = this._t0.x;
  28398. this._cachedTextureMatrix.m[9] = this._t0.y;
  28399. this._cachedTextureMatrix.m[10] = this._t0.z;
  28400. return this._cachedTextureMatrix;
  28401. };
  28402. Texture.prototype.getReflectionTextureMatrix = function () {
  28403. if (this.uOffset === this._cachedUOffset &&
  28404. this.vOffset === this._cachedVOffset &&
  28405. this.uScale === this._cachedUScale &&
  28406. this.vScale === this._cachedVScale &&
  28407. this.coordinatesMode === this._cachedCoordinatesMode) {
  28408. return this._cachedTextureMatrix;
  28409. }
  28410. if (!this._cachedTextureMatrix) {
  28411. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  28412. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  28413. }
  28414. this._cachedCoordinatesMode = this.coordinatesMode;
  28415. switch (this.coordinatesMode) {
  28416. case Texture.PLANAR_MODE:
  28417. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28418. this._cachedTextureMatrix[0] = this.uScale;
  28419. this._cachedTextureMatrix[5] = this.vScale;
  28420. this._cachedTextureMatrix[12] = this.uOffset;
  28421. this._cachedTextureMatrix[13] = this.vOffset;
  28422. break;
  28423. case Texture.PROJECTION_MODE:
  28424. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  28425. this._projectionModeMatrix.m[0] = 0.5;
  28426. this._projectionModeMatrix.m[5] = -0.5;
  28427. this._projectionModeMatrix.m[10] = 0.0;
  28428. this._projectionModeMatrix.m[12] = 0.5;
  28429. this._projectionModeMatrix.m[13] = 0.5;
  28430. this._projectionModeMatrix.m[14] = 1.0;
  28431. this._projectionModeMatrix.m[15] = 1.0;
  28432. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  28433. break;
  28434. default:
  28435. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28436. break;
  28437. }
  28438. return this._cachedTextureMatrix;
  28439. };
  28440. Texture.prototype.clone = function () {
  28441. var _this = this;
  28442. return BABYLON.SerializationHelper.Clone(function () {
  28443. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  28444. }, this);
  28445. };
  28446. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  28447. get: function () {
  28448. if (!this._onLoadObservarble) {
  28449. this._onLoadObservarble = new BABYLON.Observable();
  28450. }
  28451. return this._onLoadObservarble;
  28452. },
  28453. enumerable: true,
  28454. configurable: true
  28455. });
  28456. // Statics
  28457. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  28458. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28459. if (onLoad === void 0) { onLoad = null; }
  28460. if (onError === void 0) { onError = null; }
  28461. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28462. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  28463. };
  28464. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  28465. if (parsedTexture.customType) {
  28466. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  28467. // Update Sampling Mode
  28468. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  28469. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  28470. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  28471. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  28472. }
  28473. }
  28474. return parsedCustomTexture;
  28475. }
  28476. if (parsedTexture.isCube) {
  28477. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  28478. }
  28479. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  28480. return null;
  28481. }
  28482. var texture = BABYLON.SerializationHelper.Parse(function () {
  28483. if (parsedTexture.mirrorPlane) {
  28484. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  28485. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  28486. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  28487. return mirrorTexture;
  28488. }
  28489. else if (parsedTexture.isRenderTarget) {
  28490. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  28491. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  28492. return renderTargetTexture;
  28493. }
  28494. else {
  28495. var texture;
  28496. if (parsedTexture.base64String) {
  28497. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  28498. }
  28499. else {
  28500. texture = new Texture(rootUrl + parsedTexture.name, scene);
  28501. }
  28502. return texture;
  28503. }
  28504. }, parsedTexture, scene);
  28505. // Update Sampling Mode
  28506. if (parsedTexture.samplingMode) {
  28507. var sampling = parsedTexture.samplingMode;
  28508. if (texture._samplingMode !== sampling) {
  28509. texture.updateSamplingMode(sampling);
  28510. }
  28511. }
  28512. // Animations
  28513. if (parsedTexture.animations) {
  28514. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  28515. var parsedAnimation = parsedTexture.animations[animationIndex];
  28516. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28517. }
  28518. }
  28519. return texture;
  28520. };
  28521. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  28522. if (deleteBuffer === void 0) { deleteBuffer = false; }
  28523. if (noMipmap === void 0) { noMipmap = false; }
  28524. if (invertY === void 0) { invertY = true; }
  28525. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28526. if (onLoad === void 0) { onLoad = null; }
  28527. if (onError === void 0) { onError = null; }
  28528. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28529. if (name.substr(0, 5) !== "data:") {
  28530. name = "data:" + name;
  28531. }
  28532. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  28533. };
  28534. return Texture;
  28535. }(BABYLON.BaseTexture));
  28536. // Constants
  28537. Texture.NEAREST_SAMPLINGMODE = 1;
  28538. Texture.BILINEAR_SAMPLINGMODE = 2;
  28539. Texture.TRILINEAR_SAMPLINGMODE = 3;
  28540. Texture.EXPLICIT_MODE = 0;
  28541. Texture.SPHERICAL_MODE = 1;
  28542. Texture.PLANAR_MODE = 2;
  28543. Texture.CUBIC_MODE = 3;
  28544. Texture.PROJECTION_MODE = 4;
  28545. Texture.SKYBOX_MODE = 5;
  28546. Texture.INVCUBIC_MODE = 6;
  28547. Texture.EQUIRECTANGULAR_MODE = 7;
  28548. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  28549. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  28550. Texture.CLAMP_ADDRESSMODE = 0;
  28551. Texture.WRAP_ADDRESSMODE = 1;
  28552. Texture.MIRROR_ADDRESSMODE = 2;
  28553. __decorate([
  28554. BABYLON.serialize()
  28555. ], Texture.prototype, "url", void 0);
  28556. __decorate([
  28557. BABYLON.serialize()
  28558. ], Texture.prototype, "uOffset", void 0);
  28559. __decorate([
  28560. BABYLON.serialize()
  28561. ], Texture.prototype, "vOffset", void 0);
  28562. __decorate([
  28563. BABYLON.serialize()
  28564. ], Texture.prototype, "uScale", void 0);
  28565. __decorate([
  28566. BABYLON.serialize()
  28567. ], Texture.prototype, "vScale", void 0);
  28568. __decorate([
  28569. BABYLON.serialize()
  28570. ], Texture.prototype, "uAng", void 0);
  28571. __decorate([
  28572. BABYLON.serialize()
  28573. ], Texture.prototype, "vAng", void 0);
  28574. __decorate([
  28575. BABYLON.serialize()
  28576. ], Texture.prototype, "wAng", void 0);
  28577. BABYLON.Texture = Texture;
  28578. })(BABYLON || (BABYLON = {}));
  28579. //# sourceMappingURL=babylon.texture.js.map
  28580. var BABYLON;
  28581. (function (BABYLON) {
  28582. var CubeTexture = (function (_super) {
  28583. __extends(CubeTexture, _super);
  28584. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  28585. if (onLoad === void 0) { onLoad = null; }
  28586. if (onError === void 0) { onError = null; }
  28587. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28588. var _this = _super.call(this, scene) || this;
  28589. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  28590. _this.name = rootUrl;
  28591. _this.url = rootUrl;
  28592. _this._noMipmap = noMipmap;
  28593. _this.hasAlpha = false;
  28594. _this._format = format;
  28595. if (!rootUrl && !files) {
  28596. return _this;
  28597. }
  28598. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  28599. if (!files) {
  28600. if (!extensions) {
  28601. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  28602. }
  28603. files = [];
  28604. for (var index = 0; index < extensions.length; index++) {
  28605. files.push(rootUrl + extensions[index]);
  28606. }
  28607. _this._extensions = extensions;
  28608. }
  28609. _this._files = files;
  28610. if (!_this._texture) {
  28611. if (!scene.useDelayedTextureLoading) {
  28612. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  28613. }
  28614. else {
  28615. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28616. }
  28617. }
  28618. else if (onLoad) {
  28619. if (_this._texture.isReady) {
  28620. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  28621. }
  28622. else {
  28623. _this._texture.onLoadedCallbacks.push(onLoad);
  28624. }
  28625. }
  28626. _this.isCube = true;
  28627. _this._textureMatrix = BABYLON.Matrix.Identity();
  28628. return _this;
  28629. }
  28630. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  28631. return new CubeTexture("", scene, null, noMipmap, files);
  28632. };
  28633. // Methods
  28634. CubeTexture.prototype.delayLoad = function () {
  28635. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28636. return;
  28637. }
  28638. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28639. this._texture = this._getFromCache(this.url, this._noMipmap);
  28640. if (!this._texture) {
  28641. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  28642. }
  28643. };
  28644. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  28645. return this._textureMatrix;
  28646. };
  28647. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  28648. var texture = BABYLON.SerializationHelper.Parse(function () {
  28649. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  28650. }, parsedTexture, scene);
  28651. // Animations
  28652. if (parsedTexture.animations) {
  28653. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  28654. var parsedAnimation = parsedTexture.animations[animationIndex];
  28655. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28656. }
  28657. }
  28658. return texture;
  28659. };
  28660. CubeTexture.prototype.clone = function () {
  28661. var _this = this;
  28662. return BABYLON.SerializationHelper.Clone(function () {
  28663. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  28664. }, this);
  28665. };
  28666. return CubeTexture;
  28667. }(BABYLON.BaseTexture));
  28668. BABYLON.CubeTexture = CubeTexture;
  28669. })(BABYLON || (BABYLON = {}));
  28670. //# sourceMappingURL=babylon.cubeTexture.js.map
  28671. var BABYLON;
  28672. (function (BABYLON) {
  28673. var RenderTargetTexture = (function (_super) {
  28674. __extends(RenderTargetTexture, _super);
  28675. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  28676. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  28677. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28678. if (isCube === void 0) { isCube = false; }
  28679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28680. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28681. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  28682. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  28683. _this.isCube = isCube;
  28684. /**
  28685. * Use this list to define the list of mesh you want to render.
  28686. */
  28687. _this.renderList = new Array();
  28688. _this.renderParticles = true;
  28689. _this.renderSprites = false;
  28690. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  28691. // Events
  28692. /**
  28693. * An event triggered when the texture is unbind.
  28694. * @type {BABYLON.Observable}
  28695. */
  28696. _this.onAfterUnbindObservable = new BABYLON.Observable();
  28697. /**
  28698. * An event triggered before rendering the texture
  28699. * @type {BABYLON.Observable}
  28700. */
  28701. _this.onBeforeRenderObservable = new BABYLON.Observable();
  28702. /**
  28703. * An event triggered after rendering the texture
  28704. * @type {BABYLON.Observable}
  28705. */
  28706. _this.onAfterRenderObservable = new BABYLON.Observable();
  28707. /**
  28708. * An event triggered after the texture clear
  28709. * @type {BABYLON.Observable}
  28710. */
  28711. _this.onClearObservable = new BABYLON.Observable();
  28712. _this._currentRefreshId = -1;
  28713. _this._refreshRate = 1;
  28714. _this._samples = 1;
  28715. _this.name = name;
  28716. _this.isRenderTarget = true;
  28717. _this._size = size;
  28718. _this._generateMipMaps = generateMipMaps;
  28719. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  28720. _this._renderTargetOptions = {
  28721. generateMipMaps: generateMipMaps,
  28722. type: type,
  28723. samplingMode: samplingMode,
  28724. generateDepthBuffer: generateDepthBuffer,
  28725. generateStencilBuffer: generateStencilBuffer
  28726. };
  28727. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28728. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28729. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28730. }
  28731. if (isCube) {
  28732. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  28733. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  28734. _this._textureMatrix = BABYLON.Matrix.Identity();
  28735. }
  28736. else {
  28737. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  28738. }
  28739. // Rendering groups
  28740. _this._renderingManager = new BABYLON.RenderingManager(scene);
  28741. return _this;
  28742. }
  28743. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  28744. get: function () {
  28745. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  28746. },
  28747. enumerable: true,
  28748. configurable: true
  28749. });
  28750. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  28751. get: function () {
  28752. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  28753. },
  28754. enumerable: true,
  28755. configurable: true
  28756. });
  28757. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  28758. get: function () {
  28759. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  28760. },
  28761. enumerable: true,
  28762. configurable: true
  28763. });
  28764. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  28765. set: function (callback) {
  28766. if (this._onAfterUnbindObserver) {
  28767. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  28768. }
  28769. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  28770. },
  28771. enumerable: true,
  28772. configurable: true
  28773. });
  28774. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  28775. set: function (callback) {
  28776. if (this._onBeforeRenderObserver) {
  28777. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28778. }
  28779. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28780. },
  28781. enumerable: true,
  28782. configurable: true
  28783. });
  28784. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  28785. set: function (callback) {
  28786. if (this._onAfterRenderObserver) {
  28787. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28788. }
  28789. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28790. },
  28791. enumerable: true,
  28792. configurable: true
  28793. });
  28794. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  28795. set: function (callback) {
  28796. if (this._onClearObserver) {
  28797. this.onClearObservable.remove(this._onClearObserver);
  28798. }
  28799. this._onClearObserver = this.onClearObservable.add(callback);
  28800. },
  28801. enumerable: true,
  28802. configurable: true
  28803. });
  28804. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  28805. get: function () {
  28806. return this._samples;
  28807. },
  28808. set: function (value) {
  28809. if (this._samples === value) {
  28810. return;
  28811. }
  28812. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  28813. },
  28814. enumerable: true,
  28815. configurable: true
  28816. });
  28817. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  28818. this._currentRefreshId = -1;
  28819. };
  28820. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  28821. get: function () {
  28822. return this._refreshRate;
  28823. },
  28824. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  28825. set: function (value) {
  28826. this._refreshRate = value;
  28827. this.resetRefreshCounter();
  28828. },
  28829. enumerable: true,
  28830. configurable: true
  28831. });
  28832. RenderTargetTexture.prototype._shouldRender = function () {
  28833. if (this._currentRefreshId === -1) {
  28834. this._currentRefreshId = 1;
  28835. return true;
  28836. }
  28837. if (this.refreshRate === this._currentRefreshId) {
  28838. this._currentRefreshId = 1;
  28839. return true;
  28840. }
  28841. this._currentRefreshId++;
  28842. return false;
  28843. };
  28844. RenderTargetTexture.prototype.isReady = function () {
  28845. if (!this.getScene().renderTargetsEnabled) {
  28846. return false;
  28847. }
  28848. return _super.prototype.isReady.call(this);
  28849. };
  28850. RenderTargetTexture.prototype.getRenderSize = function () {
  28851. return this._size;
  28852. };
  28853. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  28854. get: function () {
  28855. return true;
  28856. },
  28857. enumerable: true,
  28858. configurable: true
  28859. });
  28860. RenderTargetTexture.prototype.scale = function (ratio) {
  28861. var newSize = this._size * ratio;
  28862. this.resize(newSize);
  28863. };
  28864. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  28865. if (this.isCube) {
  28866. return this._textureMatrix;
  28867. }
  28868. return _super.prototype.getReflectionTextureMatrix.call(this);
  28869. };
  28870. RenderTargetTexture.prototype.resize = function (size) {
  28871. this.releaseInternalTexture();
  28872. if (this.isCube) {
  28873. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  28874. }
  28875. else {
  28876. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  28877. }
  28878. };
  28879. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  28880. var scene = this.getScene();
  28881. var engine = scene.getEngine();
  28882. if (this.useCameraPostProcesses !== undefined) {
  28883. useCameraPostProcess = this.useCameraPostProcesses;
  28884. }
  28885. if (this._waitingRenderList) {
  28886. this.renderList = [];
  28887. for (var index = 0; index < this._waitingRenderList.length; index++) {
  28888. var id = this._waitingRenderList[index];
  28889. this.renderList.push(scene.getMeshByID(id));
  28890. }
  28891. delete this._waitingRenderList;
  28892. }
  28893. // Is predicate defined?
  28894. if (this.renderListPredicate) {
  28895. this.renderList.splice(0); // Clear previous renderList
  28896. var sceneMeshes = this.getScene().meshes;
  28897. for (var index = 0; index < sceneMeshes.length; index++) {
  28898. var mesh = sceneMeshes[index];
  28899. if (this.renderListPredicate(mesh)) {
  28900. this.renderList.push(mesh);
  28901. }
  28902. }
  28903. }
  28904. if (this.renderList && this.renderList.length === 0) {
  28905. return;
  28906. }
  28907. // Set custom projection.
  28908. // Needs to be before binding to prevent changing the aspect ratio.
  28909. if (this.activeCamera) {
  28910. engine.setViewport(this.activeCamera.viewport);
  28911. if (this.activeCamera !== scene.activeCamera) {
  28912. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  28913. }
  28914. }
  28915. else {
  28916. engine.setViewport(scene.activeCamera.viewport);
  28917. }
  28918. // Prepare renderingManager
  28919. this._renderingManager.reset();
  28920. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  28921. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  28922. var sceneRenderId = scene.getRenderId();
  28923. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  28924. var mesh = currentRenderList[meshIndex];
  28925. if (mesh) {
  28926. if (!mesh.isReady()) {
  28927. // Reset _currentRefreshId
  28928. this.resetRefreshCounter();
  28929. continue;
  28930. }
  28931. mesh._preActivateForIntermediateRendering(sceneRenderId);
  28932. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  28933. mesh._activate(sceneRenderId);
  28934. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28935. var subMesh = mesh.subMeshes[subIndex];
  28936. scene._activeIndices.addCount(subMesh.indexCount, false);
  28937. this._renderingManager.dispatch(subMesh);
  28938. }
  28939. }
  28940. }
  28941. }
  28942. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  28943. var particleSystem = scene.particleSystems[particleIndex];
  28944. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  28945. continue;
  28946. }
  28947. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  28948. this._renderingManager.dispatchParticles(particleSystem);
  28949. }
  28950. }
  28951. if (this.isCube) {
  28952. for (var face = 0; face < 6; face++) {
  28953. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  28954. scene.incrementRenderId();
  28955. scene.resetCachedMaterial();
  28956. }
  28957. }
  28958. else {
  28959. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  28960. }
  28961. this.onAfterUnbindObservable.notifyObservers(this);
  28962. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  28963. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  28964. }
  28965. engine.setViewport(scene.activeCamera.viewport);
  28966. scene.resetCachedMaterial();
  28967. };
  28968. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  28969. var _this = this;
  28970. var scene = this.getScene();
  28971. var engine = scene.getEngine();
  28972. // Bind
  28973. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  28974. if (this.isCube) {
  28975. engine.bindFramebuffer(this._texture, faceIndex);
  28976. }
  28977. else {
  28978. engine.bindFramebuffer(this._texture);
  28979. }
  28980. }
  28981. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  28982. // Clear
  28983. if (this.onClearObservable.hasObservers()) {
  28984. this.onClearObservable.notifyObservers(engine);
  28985. }
  28986. else {
  28987. engine.clear(scene.clearColor, true, true, true);
  28988. }
  28989. if (!this._doNotChangeAspectRatio) {
  28990. scene.updateTransformMatrix(true);
  28991. }
  28992. // Render
  28993. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  28994. if (useCameraPostProcess) {
  28995. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  28996. }
  28997. if (!this._doNotChangeAspectRatio) {
  28998. scene.updateTransformMatrix(true);
  28999. }
  29000. // Dump ?
  29001. if (dumpForDebug) {
  29002. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  29003. }
  29004. // Unbind
  29005. if (!this.isCube || faceIndex === 5) {
  29006. if (this.isCube) {
  29007. if (faceIndex === 5) {
  29008. engine.generateMipMapsForCubemap(this._texture);
  29009. }
  29010. }
  29011. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  29012. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  29013. });
  29014. }
  29015. else {
  29016. this.onAfterRenderObservable.notifyObservers(faceIndex);
  29017. }
  29018. };
  29019. /**
  29020. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29021. * This allowed control for front to back rendering or reversly depending of the special needs.
  29022. *
  29023. * @param renderingGroupId The rendering group id corresponding to its index
  29024. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29025. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29026. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29027. */
  29028. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29029. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29030. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29031. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29032. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29033. };
  29034. /**
  29035. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29036. *
  29037. * @param renderingGroupId The rendering group id corresponding to its index
  29038. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29039. */
  29040. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  29041. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  29042. };
  29043. RenderTargetTexture.prototype.clone = function () {
  29044. var textureSize = this.getSize();
  29045. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  29046. // Base texture
  29047. newTexture.hasAlpha = this.hasAlpha;
  29048. newTexture.level = this.level;
  29049. // RenderTarget Texture
  29050. newTexture.coordinatesMode = this.coordinatesMode;
  29051. newTexture.renderList = this.renderList.slice(0);
  29052. return newTexture;
  29053. };
  29054. RenderTargetTexture.prototype.serialize = function () {
  29055. if (!this.name) {
  29056. return null;
  29057. }
  29058. var serializationObject = _super.prototype.serialize.call(this);
  29059. serializationObject.renderTargetSize = this.getRenderSize();
  29060. serializationObject.renderList = [];
  29061. for (var index = 0; index < this.renderList.length; index++) {
  29062. serializationObject.renderList.push(this.renderList[index].id);
  29063. }
  29064. return serializationObject;
  29065. };
  29066. return RenderTargetTexture;
  29067. }(BABYLON.Texture));
  29068. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  29069. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  29070. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  29071. BABYLON.RenderTargetTexture = RenderTargetTexture;
  29072. })(BABYLON || (BABYLON = {}));
  29073. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  29074. var BABYLON;
  29075. (function (BABYLON) {
  29076. var ProceduralTexture = (function (_super) {
  29077. __extends(ProceduralTexture, _super);
  29078. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  29079. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29080. if (isCube === void 0) { isCube = false; }
  29081. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  29082. _this.isCube = isCube;
  29083. _this.isEnabled = true;
  29084. _this._currentRefreshId = -1;
  29085. _this._refreshRate = 1;
  29086. _this._vertexBuffers = {};
  29087. _this._uniforms = new Array();
  29088. _this._samplers = new Array();
  29089. _this._textures = new Array();
  29090. _this._floats = new Array();
  29091. _this._floatsArrays = {};
  29092. _this._colors3 = new Array();
  29093. _this._colors4 = new Array();
  29094. _this._vectors2 = new Array();
  29095. _this._vectors3 = new Array();
  29096. _this._matrices = new Array();
  29097. _this._fallbackTextureUsed = false;
  29098. scene._proceduralTextures.push(_this);
  29099. _this.name = name;
  29100. _this.isRenderTarget = true;
  29101. _this._size = size;
  29102. _this._generateMipMaps = generateMipMaps;
  29103. _this.setFragment(fragment);
  29104. _this._fallbackTexture = fallbackTexture;
  29105. var engine = scene.getEngine();
  29106. if (isCube) {
  29107. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  29108. _this.setFloat("face", 0);
  29109. }
  29110. else {
  29111. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  29112. }
  29113. // VBO
  29114. var vertices = [];
  29115. vertices.push(1, 1);
  29116. vertices.push(-1, 1);
  29117. vertices.push(-1, -1);
  29118. vertices.push(1, -1);
  29119. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29120. // Indices
  29121. var indices = [];
  29122. indices.push(0);
  29123. indices.push(1);
  29124. indices.push(2);
  29125. indices.push(0);
  29126. indices.push(2);
  29127. indices.push(3);
  29128. _this._indexBuffer = engine.createIndexBuffer(indices);
  29129. return _this;
  29130. }
  29131. ProceduralTexture.prototype.reset = function () {
  29132. if (this._effect === undefined) {
  29133. return;
  29134. }
  29135. var engine = this.getScene().getEngine();
  29136. engine._releaseEffect(this._effect);
  29137. };
  29138. ProceduralTexture.prototype.isReady = function () {
  29139. var _this = this;
  29140. var engine = this.getScene().getEngine();
  29141. var shaders;
  29142. if (!this._fragment) {
  29143. return false;
  29144. }
  29145. if (this._fallbackTextureUsed) {
  29146. return true;
  29147. }
  29148. if (this._fragment.fragmentElement !== undefined) {
  29149. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  29150. }
  29151. else {
  29152. shaders = { vertex: "procedural", fragment: this._fragment };
  29153. }
  29154. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  29155. _this.releaseInternalTexture();
  29156. if (_this._fallbackTexture) {
  29157. _this._texture = _this._fallbackTexture._texture;
  29158. _this._texture.references++;
  29159. }
  29160. _this._fallbackTextureUsed = true;
  29161. });
  29162. return this._effect.isReady();
  29163. };
  29164. ProceduralTexture.prototype.resetRefreshCounter = function () {
  29165. this._currentRefreshId = -1;
  29166. };
  29167. ProceduralTexture.prototype.setFragment = function (fragment) {
  29168. this._fragment = fragment;
  29169. };
  29170. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  29171. get: function () {
  29172. return this._refreshRate;
  29173. },
  29174. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  29175. set: function (value) {
  29176. this._refreshRate = value;
  29177. this.resetRefreshCounter();
  29178. },
  29179. enumerable: true,
  29180. configurable: true
  29181. });
  29182. ProceduralTexture.prototype._shouldRender = function () {
  29183. if (!this.isEnabled || !this.isReady() || !this._texture) {
  29184. return false;
  29185. }
  29186. if (this._fallbackTextureUsed) {
  29187. return false;
  29188. }
  29189. if (this._currentRefreshId === -1) {
  29190. this._currentRefreshId = 1;
  29191. return true;
  29192. }
  29193. if (this.refreshRate === this._currentRefreshId) {
  29194. this._currentRefreshId = 1;
  29195. return true;
  29196. }
  29197. this._currentRefreshId++;
  29198. return false;
  29199. };
  29200. ProceduralTexture.prototype.getRenderSize = function () {
  29201. return this._size;
  29202. };
  29203. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  29204. if (this._fallbackTextureUsed) {
  29205. return;
  29206. }
  29207. this.releaseInternalTexture();
  29208. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  29209. };
  29210. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  29211. if (this._uniforms.indexOf(uniformName) === -1) {
  29212. this._uniforms.push(uniformName);
  29213. }
  29214. };
  29215. ProceduralTexture.prototype.setTexture = function (name, texture) {
  29216. if (this._samplers.indexOf(name) === -1) {
  29217. this._samplers.push(name);
  29218. }
  29219. this._textures[name] = texture;
  29220. return this;
  29221. };
  29222. ProceduralTexture.prototype.setFloat = function (name, value) {
  29223. this._checkUniform(name);
  29224. this._floats[name] = value;
  29225. return this;
  29226. };
  29227. ProceduralTexture.prototype.setFloats = function (name, value) {
  29228. this._checkUniform(name);
  29229. this._floatsArrays[name] = value;
  29230. return this;
  29231. };
  29232. ProceduralTexture.prototype.setColor3 = function (name, value) {
  29233. this._checkUniform(name);
  29234. this._colors3[name] = value;
  29235. return this;
  29236. };
  29237. ProceduralTexture.prototype.setColor4 = function (name, value) {
  29238. this._checkUniform(name);
  29239. this._colors4[name] = value;
  29240. return this;
  29241. };
  29242. ProceduralTexture.prototype.setVector2 = function (name, value) {
  29243. this._checkUniform(name);
  29244. this._vectors2[name] = value;
  29245. return this;
  29246. };
  29247. ProceduralTexture.prototype.setVector3 = function (name, value) {
  29248. this._checkUniform(name);
  29249. this._vectors3[name] = value;
  29250. return this;
  29251. };
  29252. ProceduralTexture.prototype.setMatrix = function (name, value) {
  29253. this._checkUniform(name);
  29254. this._matrices[name] = value;
  29255. return this;
  29256. };
  29257. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  29258. var scene = this.getScene();
  29259. var engine = scene.getEngine();
  29260. // Render
  29261. engine.enableEffect(this._effect);
  29262. engine.setState(false);
  29263. // Texture
  29264. for (var name in this._textures) {
  29265. this._effect.setTexture(name, this._textures[name]);
  29266. }
  29267. // Float
  29268. for (name in this._floats) {
  29269. this._effect.setFloat(name, this._floats[name]);
  29270. }
  29271. // Floats
  29272. for (name in this._floatsArrays) {
  29273. this._effect.setArray(name, this._floatsArrays[name]);
  29274. }
  29275. // Color3
  29276. for (name in this._colors3) {
  29277. this._effect.setColor3(name, this._colors3[name]);
  29278. }
  29279. // Color4
  29280. for (name in this._colors4) {
  29281. var color = this._colors4[name];
  29282. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  29283. }
  29284. // Vector2
  29285. for (name in this._vectors2) {
  29286. this._effect.setVector2(name, this._vectors2[name]);
  29287. }
  29288. // Vector3
  29289. for (name in this._vectors3) {
  29290. this._effect.setVector3(name, this._vectors3[name]);
  29291. }
  29292. // Matrix
  29293. for (name in this._matrices) {
  29294. this._effect.setMatrix(name, this._matrices[name]);
  29295. }
  29296. if (this.isCube) {
  29297. for (var face = 0; face < 6; face++) {
  29298. engine.bindFramebuffer(this._texture, face);
  29299. // VBOs
  29300. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  29301. this._effect.setFloat("face", face);
  29302. // Clear
  29303. engine.clear(scene.clearColor, true, true, true);
  29304. // Draw order
  29305. engine.draw(true, 0, 6);
  29306. // Mipmaps
  29307. if (face === 5) {
  29308. engine.generateMipMapsForCubemap(this._texture);
  29309. }
  29310. }
  29311. }
  29312. else {
  29313. engine.bindFramebuffer(this._texture);
  29314. // VBOs
  29315. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  29316. // Clear
  29317. engine.clear(scene.clearColor, true, true, true);
  29318. // Draw order
  29319. engine.draw(true, 0, 6);
  29320. }
  29321. // Unbind
  29322. engine.unBindFramebuffer(this._texture, this.isCube);
  29323. if (this.onGenerated) {
  29324. this.onGenerated();
  29325. }
  29326. };
  29327. ProceduralTexture.prototype.clone = function () {
  29328. var textureSize = this.getSize();
  29329. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  29330. // Base texture
  29331. newTexture.hasAlpha = this.hasAlpha;
  29332. newTexture.level = this.level;
  29333. // RenderTarget Texture
  29334. newTexture.coordinatesMode = this.coordinatesMode;
  29335. return newTexture;
  29336. };
  29337. ProceduralTexture.prototype.dispose = function () {
  29338. var index = this.getScene()._proceduralTextures.indexOf(this);
  29339. if (index >= 0) {
  29340. this.getScene()._proceduralTextures.splice(index, 1);
  29341. }
  29342. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29343. if (vertexBuffer) {
  29344. vertexBuffer.dispose();
  29345. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29346. }
  29347. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  29348. this._indexBuffer = null;
  29349. }
  29350. _super.prototype.dispose.call(this);
  29351. };
  29352. return ProceduralTexture;
  29353. }(BABYLON.Texture));
  29354. BABYLON.ProceduralTexture = ProceduralTexture;
  29355. })(BABYLON || (BABYLON = {}));
  29356. //# sourceMappingURL=babylon.proceduralTexture.js.map
  29357. /// <reference path="babylon.renderTargetTexture.ts" />
  29358. var BABYLON;
  29359. (function (BABYLON) {
  29360. var MirrorTexture = (function (_super) {
  29361. __extends(MirrorTexture, _super);
  29362. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  29363. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29365. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  29366. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  29367. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  29368. _this._transformMatrix = BABYLON.Matrix.Zero();
  29369. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  29370. _this.onBeforeRenderObservable.add(function () {
  29371. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  29372. _this._savedViewMatrix = scene.getViewMatrix();
  29373. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  29374. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  29375. scene.clipPlane = _this.mirrorPlane;
  29376. scene.getEngine().cullBackFaces = false;
  29377. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  29378. });
  29379. _this.onAfterRenderObservable.add(function () {
  29380. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  29381. scene.getEngine().cullBackFaces = true;
  29382. scene._mirroredCameraPosition = null;
  29383. delete scene.clipPlane;
  29384. });
  29385. return _this;
  29386. }
  29387. MirrorTexture.prototype.clone = function () {
  29388. var textureSize = this.getSize();
  29389. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  29390. // Base texture
  29391. newTexture.hasAlpha = this.hasAlpha;
  29392. newTexture.level = this.level;
  29393. // Mirror Texture
  29394. newTexture.mirrorPlane = this.mirrorPlane.clone();
  29395. newTexture.renderList = this.renderList.slice(0);
  29396. return newTexture;
  29397. };
  29398. MirrorTexture.prototype.serialize = function () {
  29399. if (!this.name) {
  29400. return null;
  29401. }
  29402. var serializationObject = _super.prototype.serialize.call(this);
  29403. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  29404. return serializationObject;
  29405. };
  29406. return MirrorTexture;
  29407. }(BABYLON.RenderTargetTexture));
  29408. BABYLON.MirrorTexture = MirrorTexture;
  29409. })(BABYLON || (BABYLON = {}));
  29410. //# sourceMappingURL=babylon.mirrorTexture.js.map
  29411. /// <reference path="babylon.renderTargetTexture.ts" />
  29412. var BABYLON;
  29413. (function (BABYLON) {
  29414. /**
  29415. * Creates a refraction texture used by refraction channel of the standard material.
  29416. * @param name the texture name
  29417. * @param size size of the underlying texture
  29418. * @param scene root scene
  29419. */
  29420. var RefractionTexture = (function (_super) {
  29421. __extends(RefractionTexture, _super);
  29422. function RefractionTexture(name, size, scene, generateMipMaps) {
  29423. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  29424. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  29425. _this.depth = 2.0;
  29426. _this.onBeforeRenderObservable.add(function () {
  29427. scene.clipPlane = _this.refractionPlane;
  29428. });
  29429. _this.onAfterRenderObservable.add(function () {
  29430. delete scene.clipPlane;
  29431. });
  29432. return _this;
  29433. }
  29434. RefractionTexture.prototype.clone = function () {
  29435. var textureSize = this.getSize();
  29436. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  29437. // Base texture
  29438. newTexture.hasAlpha = this.hasAlpha;
  29439. newTexture.level = this.level;
  29440. // Refraction Texture
  29441. newTexture.refractionPlane = this.refractionPlane.clone();
  29442. newTexture.renderList = this.renderList.slice(0);
  29443. newTexture.depth = this.depth;
  29444. return newTexture;
  29445. };
  29446. RefractionTexture.prototype.serialize = function () {
  29447. if (!this.name) {
  29448. return null;
  29449. }
  29450. var serializationObject = _super.prototype.serialize.call(this);
  29451. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  29452. serializationObject.depth = this.depth;
  29453. return serializationObject;
  29454. };
  29455. return RefractionTexture;
  29456. }(BABYLON.RenderTargetTexture));
  29457. BABYLON.RefractionTexture = RefractionTexture;
  29458. })(BABYLON || (BABYLON = {}));
  29459. //# sourceMappingURL=babylon.refractionTexture.js.map
  29460. /// <reference path="babylon.texture.ts" />
  29461. var BABYLON;
  29462. (function (BABYLON) {
  29463. var DynamicTexture = (function (_super) {
  29464. __extends(DynamicTexture, _super);
  29465. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  29466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29467. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  29468. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  29469. _this.name = name;
  29470. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29471. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29472. _this._generateMipMaps = generateMipMaps;
  29473. if (options.getContext) {
  29474. _this._canvas = options;
  29475. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  29476. }
  29477. else {
  29478. _this._canvas = document.createElement("canvas");
  29479. if (options.width) {
  29480. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  29481. }
  29482. else {
  29483. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  29484. }
  29485. }
  29486. var textureSize = _this.getSize();
  29487. _this._canvas.width = textureSize.width;
  29488. _this._canvas.height = textureSize.height;
  29489. _this._context = _this._canvas.getContext("2d");
  29490. return _this;
  29491. }
  29492. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  29493. get: function () {
  29494. return true;
  29495. },
  29496. enumerable: true,
  29497. configurable: true
  29498. });
  29499. DynamicTexture.prototype.scale = function (ratio) {
  29500. var textureSize = this.getSize();
  29501. textureSize.width *= ratio;
  29502. textureSize.height *= ratio;
  29503. this._canvas.width = textureSize.width;
  29504. this._canvas.height = textureSize.height;
  29505. this.releaseInternalTexture();
  29506. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  29507. };
  29508. DynamicTexture.prototype.getContext = function () {
  29509. return this._context;
  29510. };
  29511. DynamicTexture.prototype.clear = function () {
  29512. var size = this.getSize();
  29513. this._context.fillRect(0, 0, size.width, size.height);
  29514. };
  29515. DynamicTexture.prototype.update = function (invertY) {
  29516. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  29517. };
  29518. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  29519. if (update === void 0) { update = true; }
  29520. var size = this.getSize();
  29521. if (clearColor) {
  29522. this._context.fillStyle = clearColor;
  29523. this._context.fillRect(0, 0, size.width, size.height);
  29524. }
  29525. this._context.font = font;
  29526. if (x === null || x === undefined) {
  29527. var textSize = this._context.measureText(text);
  29528. x = (size.width - textSize.width) / 2;
  29529. }
  29530. if (y === null || y === undefined) {
  29531. var fontSize = parseInt((font.replace(/\D/g, '')));
  29532. ;
  29533. y = (size.height / 2) + (fontSize / 3.65);
  29534. }
  29535. this._context.fillStyle = color;
  29536. this._context.fillText(text, x, y);
  29537. if (update) {
  29538. this.update(invertY);
  29539. }
  29540. };
  29541. DynamicTexture.prototype.clone = function () {
  29542. var textureSize = this.getSize();
  29543. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  29544. // Base texture
  29545. newTexture.hasAlpha = this.hasAlpha;
  29546. newTexture.level = this.level;
  29547. // Dynamic Texture
  29548. newTexture.wrapU = this.wrapU;
  29549. newTexture.wrapV = this.wrapV;
  29550. return newTexture;
  29551. };
  29552. return DynamicTexture;
  29553. }(BABYLON.Texture));
  29554. BABYLON.DynamicTexture = DynamicTexture;
  29555. })(BABYLON || (BABYLON = {}));
  29556. //# sourceMappingURL=babylon.dynamicTexture.js.map
  29557. var BABYLON;
  29558. (function (BABYLON) {
  29559. var VideoTexture = (function (_super) {
  29560. __extends(VideoTexture, _super);
  29561. /**
  29562. * Creates a video texture.
  29563. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  29564. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  29565. * @param {BABYLON.Scene} scene is obviously the current scene.
  29566. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  29567. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  29568. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  29569. */
  29570. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  29571. if (generateMipMaps === void 0) { generateMipMaps = false; }
  29572. if (invertY === void 0) { invertY = false; }
  29573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29574. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  29575. _this._autoLaunch = true;
  29576. var urls;
  29577. _this.name = name;
  29578. if (urlsOrVideo instanceof HTMLVideoElement) {
  29579. _this.video = urlsOrVideo;
  29580. }
  29581. else {
  29582. urls = urlsOrVideo;
  29583. _this.video = document.createElement("video");
  29584. _this.video.autoplay = false;
  29585. _this.video.loop = true;
  29586. }
  29587. _this._generateMipMaps = generateMipMaps;
  29588. _this._samplingMode = samplingMode;
  29589. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  29590. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29591. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29592. }
  29593. else {
  29594. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29595. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29596. _this._generateMipMaps = false;
  29597. }
  29598. if (urls) {
  29599. _this.video.addEventListener("canplay", function () {
  29600. _this._createTexture();
  29601. });
  29602. urls.forEach(function (url) {
  29603. var source = document.createElement("source");
  29604. source.src = url;
  29605. _this.video.appendChild(source);
  29606. });
  29607. }
  29608. else {
  29609. _this._createTexture();
  29610. }
  29611. _this._lastUpdate = BABYLON.Tools.Now;
  29612. return _this;
  29613. }
  29614. VideoTexture.prototype._createTexture = function () {
  29615. var _this = this;
  29616. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  29617. if (this._autoLaunch) {
  29618. this._autoLaunch = false;
  29619. this.video.play();
  29620. }
  29621. this.video.addEventListener("playing", function () {
  29622. _this._texture.isReady = true;
  29623. });
  29624. };
  29625. VideoTexture.prototype.update = function () {
  29626. var now = BABYLON.Tools.Now;
  29627. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  29628. return false;
  29629. }
  29630. this._lastUpdate = now;
  29631. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  29632. return true;
  29633. };
  29634. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  29635. var video = document.createElement("video");
  29636. var constraintsDeviceId;
  29637. if (constraints && constraints.deviceId) {
  29638. constraintsDeviceId = {
  29639. exact: constraints.deviceId
  29640. };
  29641. }
  29642. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  29643. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  29644. if (navigator.getUserMedia) {
  29645. navigator.getUserMedia({
  29646. video: {
  29647. deviceId: constraintsDeviceId,
  29648. width: {
  29649. min: (constraints && constraints.minWidth) || 256,
  29650. max: (constraints && constraints.maxWidth) || 640
  29651. },
  29652. height: {
  29653. min: (constraints && constraints.minHeight) || 256,
  29654. max: (constraints && constraints.maxHeight) || 480
  29655. }
  29656. }
  29657. }, function (stream) {
  29658. if (video.mozSrcObject !== undefined) {
  29659. video.mozSrcObject = stream;
  29660. }
  29661. else {
  29662. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  29663. }
  29664. video.play();
  29665. if (onReady) {
  29666. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  29667. }
  29668. }, function (e) {
  29669. BABYLON.Tools.Error(e.name);
  29670. });
  29671. }
  29672. };
  29673. return VideoTexture;
  29674. }(BABYLON.Texture));
  29675. BABYLON.VideoTexture = VideoTexture;
  29676. })(BABYLON || (BABYLON = {}));
  29677. //# sourceMappingURL=babylon.videoTexture.js.map
  29678. /// <reference path="babylon.proceduralTexture.ts" />
  29679. var BABYLON;
  29680. (function (BABYLON) {
  29681. var CustomProceduralTexture = (function (_super) {
  29682. __extends(CustomProceduralTexture, _super);
  29683. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  29684. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  29685. _this._animate = true;
  29686. _this._time = 0;
  29687. _this._texturePath = texturePath;
  29688. //Try to load json
  29689. _this.loadJson(texturePath);
  29690. _this.refreshRate = 1;
  29691. return _this;
  29692. }
  29693. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  29694. var _this = this;
  29695. var that = this;
  29696. function noConfigFile() {
  29697. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  29698. try {
  29699. that.setFragment(that._texturePath);
  29700. }
  29701. catch (ex) {
  29702. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  29703. }
  29704. }
  29705. var configFileUrl = jsonUrl + "/config.json";
  29706. var xhr = new XMLHttpRequest();
  29707. xhr.open("GET", configFileUrl, true);
  29708. xhr.addEventListener("load", function () {
  29709. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  29710. try {
  29711. _this._config = JSON.parse(xhr.response);
  29712. _this.updateShaderUniforms();
  29713. _this.updateTextures();
  29714. _this.setFragment(_this._texturePath + "/custom");
  29715. _this._animate = _this._config.animate;
  29716. _this.refreshRate = _this._config.refreshrate;
  29717. }
  29718. catch (ex) {
  29719. noConfigFile();
  29720. }
  29721. }
  29722. else {
  29723. noConfigFile();
  29724. }
  29725. }, false);
  29726. xhr.addEventListener("error", function () {
  29727. noConfigFile();
  29728. }, false);
  29729. try {
  29730. xhr.send();
  29731. }
  29732. catch (ex) {
  29733. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  29734. }
  29735. };
  29736. CustomProceduralTexture.prototype.isReady = function () {
  29737. if (!_super.prototype.isReady.call(this)) {
  29738. return false;
  29739. }
  29740. for (var name in this._textures) {
  29741. var texture = this._textures[name];
  29742. if (!texture.isReady()) {
  29743. return false;
  29744. }
  29745. }
  29746. return true;
  29747. };
  29748. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  29749. if (this._animate) {
  29750. this._time += this.getScene().getAnimationRatio() * 0.03;
  29751. this.updateShaderUniforms();
  29752. }
  29753. _super.prototype.render.call(this, useCameraPostProcess);
  29754. };
  29755. CustomProceduralTexture.prototype.updateTextures = function () {
  29756. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  29757. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  29758. }
  29759. };
  29760. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  29761. if (this._config) {
  29762. for (var j = 0; j < this._config.uniforms.length; j++) {
  29763. var uniform = this._config.uniforms[j];
  29764. switch (uniform.type) {
  29765. case "float":
  29766. this.setFloat(uniform.name, uniform.value);
  29767. break;
  29768. case "color3":
  29769. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  29770. break;
  29771. case "color4":
  29772. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  29773. break;
  29774. case "vector2":
  29775. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  29776. break;
  29777. case "vector3":
  29778. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  29779. break;
  29780. }
  29781. }
  29782. }
  29783. this.setFloat("time", this._time);
  29784. };
  29785. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  29786. get: function () {
  29787. return this._animate;
  29788. },
  29789. set: function (value) {
  29790. this._animate = value;
  29791. },
  29792. enumerable: true,
  29793. configurable: true
  29794. });
  29795. return CustomProceduralTexture;
  29796. }(BABYLON.ProceduralTexture));
  29797. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  29798. })(BABYLON || (BABYLON = {}));
  29799. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  29800. var BABYLON;
  29801. (function (BABYLON) {
  29802. var EffectFallbacks = (function () {
  29803. function EffectFallbacks() {
  29804. this._defines = {};
  29805. this._currentRank = 32;
  29806. this._maxRank = -1;
  29807. }
  29808. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29809. if (!this._defines[rank]) {
  29810. if (rank < this._currentRank) {
  29811. this._currentRank = rank;
  29812. }
  29813. if (rank > this._maxRank) {
  29814. this._maxRank = rank;
  29815. }
  29816. this._defines[rank] = new Array();
  29817. }
  29818. this._defines[rank].push(define);
  29819. };
  29820. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  29821. this._meshRank = rank;
  29822. this._mesh = mesh;
  29823. if (rank < this._currentRank) {
  29824. this._currentRank = rank;
  29825. }
  29826. if (rank > this._maxRank) {
  29827. this._maxRank = rank;
  29828. }
  29829. };
  29830. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  29831. get: function () {
  29832. return this._currentRank <= this._maxRank;
  29833. },
  29834. enumerable: true,
  29835. configurable: true
  29836. });
  29837. EffectFallbacks.prototype.reduce = function (currentDefines) {
  29838. // First we try to switch to CPU skinning
  29839. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  29840. this._mesh.computeBonesUsingShaders = false;
  29841. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  29842. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  29843. var scene = this._mesh.getScene();
  29844. for (var index = 0; index < scene.meshes.length; index++) {
  29845. var otherMesh = scene.meshes[index];
  29846. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  29847. otherMesh.computeBonesUsingShaders = false;
  29848. }
  29849. }
  29850. }
  29851. else {
  29852. var currentFallbacks = this._defines[this._currentRank];
  29853. if (currentFallbacks) {
  29854. for (var index = 0; index < currentFallbacks.length; index++) {
  29855. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  29856. }
  29857. }
  29858. this._currentRank++;
  29859. }
  29860. return currentDefines;
  29861. };
  29862. return EffectFallbacks;
  29863. }());
  29864. BABYLON.EffectFallbacks = EffectFallbacks;
  29865. var EffectCreationOptions = (function () {
  29866. function EffectCreationOptions() {
  29867. }
  29868. return EffectCreationOptions;
  29869. }());
  29870. BABYLON.EffectCreationOptions = EffectCreationOptions;
  29871. var Effect = (function () {
  29872. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  29873. var _this = this;
  29874. this.uniqueId = 0;
  29875. this._isReady = false;
  29876. this._compilationError = "";
  29877. this._valueCache = {};
  29878. this.name = baseName;
  29879. if (attributesNamesOrOptions.attributes) {
  29880. var options = attributesNamesOrOptions;
  29881. this._engine = uniformsNamesOrEngine;
  29882. this._attributesNames = options.attributes;
  29883. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  29884. this._samplers = options.samplers;
  29885. this.defines = options.defines;
  29886. this.onError = options.onError;
  29887. this.onCompiled = options.onCompiled;
  29888. this._fallbacks = options.fallbacks;
  29889. this._indexParameters = options.indexParameters;
  29890. }
  29891. else {
  29892. this._engine = engine;
  29893. this.defines = defines;
  29894. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  29895. this._samplers = samplers;
  29896. this._attributesNames = attributesNamesOrOptions;
  29897. this.onError = onError;
  29898. this.onCompiled = onCompiled;
  29899. this._indexParameters = indexParameters;
  29900. this._fallbacks = fallbacks;
  29901. }
  29902. this.uniqueId = Effect._uniqueIdSeed++;
  29903. var vertexSource;
  29904. var fragmentSource;
  29905. if (baseName.vertexElement) {
  29906. vertexSource = document.getElementById(baseName.vertexElement);
  29907. if (!vertexSource) {
  29908. vertexSource = baseName.vertexElement;
  29909. }
  29910. }
  29911. else {
  29912. vertexSource = baseName.vertex || baseName;
  29913. }
  29914. if (baseName.fragmentElement) {
  29915. fragmentSource = document.getElementById(baseName.fragmentElement);
  29916. if (!fragmentSource) {
  29917. fragmentSource = baseName.fragmentElement;
  29918. }
  29919. }
  29920. else {
  29921. fragmentSource = baseName.fragment || baseName;
  29922. }
  29923. this._loadVertexShader(vertexSource, function (vertexCode) {
  29924. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  29925. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  29926. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  29927. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  29928. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  29929. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  29930. });
  29931. });
  29932. });
  29933. });
  29934. });
  29935. });
  29936. }
  29937. Object.defineProperty(Effect.prototype, "key", {
  29938. get: function () {
  29939. return this._key;
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. // Properties
  29945. Effect.prototype.isReady = function () {
  29946. return this._isReady;
  29947. };
  29948. Effect.prototype.getProgram = function () {
  29949. return this._program;
  29950. };
  29951. Effect.prototype.getAttributesNames = function () {
  29952. return this._attributesNames;
  29953. };
  29954. Effect.prototype.getAttributeLocation = function (index) {
  29955. return this._attributes[index];
  29956. };
  29957. Effect.prototype.getAttributeLocationByName = function (name) {
  29958. var index = this._attributesNames.indexOf(name);
  29959. return this._attributes[index];
  29960. };
  29961. Effect.prototype.getAttributesCount = function () {
  29962. return this._attributes.length;
  29963. };
  29964. Effect.prototype.getUniformIndex = function (uniformName) {
  29965. return this._uniformsNames.indexOf(uniformName);
  29966. };
  29967. Effect.prototype.getUniform = function (uniformName) {
  29968. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  29969. };
  29970. Effect.prototype.getSamplers = function () {
  29971. return this._samplers;
  29972. };
  29973. Effect.prototype.getCompilationError = function () {
  29974. return this._compilationError;
  29975. };
  29976. Effect.prototype.getVertexShaderSource = function () {
  29977. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  29978. };
  29979. Effect.prototype.getFragmentShaderSource = function () {
  29980. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  29981. };
  29982. // Methods
  29983. Effect.prototype._loadVertexShader = function (vertex, callback) {
  29984. // DOM element ?
  29985. if (vertex instanceof HTMLElement) {
  29986. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  29987. callback(vertexCode);
  29988. return;
  29989. }
  29990. // Base64 encoded ?
  29991. if (vertex.substr(0, 7) === "base64:") {
  29992. var vertexBinary = window.atob(vertex.substr(7));
  29993. callback(vertexBinary);
  29994. return;
  29995. }
  29996. // Is in local store ?
  29997. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  29998. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  29999. return;
  30000. }
  30001. var vertexShaderUrl;
  30002. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  30003. vertexShaderUrl = vertex;
  30004. }
  30005. else {
  30006. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  30007. }
  30008. // Vertex shader
  30009. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  30010. };
  30011. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  30012. // DOM element ?
  30013. if (fragment instanceof HTMLElement) {
  30014. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  30015. callback(fragmentCode);
  30016. return;
  30017. }
  30018. // Base64 encoded ?
  30019. if (fragment.substr(0, 7) === "base64:") {
  30020. var fragmentBinary = window.atob(fragment.substr(7));
  30021. callback(fragmentBinary);
  30022. return;
  30023. }
  30024. // Is in local store ?
  30025. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  30026. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  30027. return;
  30028. }
  30029. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  30030. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  30031. return;
  30032. }
  30033. var fragmentShaderUrl;
  30034. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  30035. fragmentShaderUrl = fragment;
  30036. }
  30037. else {
  30038. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  30039. }
  30040. // Fragment shader
  30041. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  30042. };
  30043. Effect.prototype._dumpShadersName = function () {
  30044. if (this.name.vertexElement) {
  30045. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  30046. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  30047. }
  30048. else if (this.name.vertex) {
  30049. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  30050. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  30051. }
  30052. else {
  30053. BABYLON.Tools.Error("Vertex shader:" + this.name);
  30054. BABYLON.Tools.Error("Fragment shader:" + this.name);
  30055. }
  30056. };
  30057. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  30058. var preparedSourceCode = this._processPrecision(sourceCode);
  30059. if (this._engine.webGLVersion == 1) {
  30060. callback(preparedSourceCode);
  30061. return;
  30062. }
  30063. // Already converted
  30064. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  30065. callback(preparedSourceCode);
  30066. return;
  30067. }
  30068. // Remove extensions
  30069. // #extension GL_OES_standard_derivatives : enable
  30070. // #extension GL_EXT_shader_texture_lod : enable
  30071. // #extension GL_EXT_frag_depth : enable
  30072. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  30073. var result = preparedSourceCode.replace(regex, "");
  30074. // Migrate to GLSL v300
  30075. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  30076. result = result.replace(/attribute[ \t]/g, "in ");
  30077. result = result.replace(/[ \t]attribute/g, " in");
  30078. if (isFragment) {
  30079. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  30080. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  30081. result = result.replace(/texture2D\(/g, "texture(");
  30082. result = result.replace(/textureCube\(/g, "texture(");
  30083. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  30084. result = result.replace(/gl_FragColor/g, "glFragColor");
  30085. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  30086. }
  30087. callback(result);
  30088. };
  30089. Effect.prototype._processIncludes = function (sourceCode, callback) {
  30090. var _this = this;
  30091. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  30092. var match = regex.exec(sourceCode);
  30093. var returnValue = new String(sourceCode);
  30094. while (match != null) {
  30095. var includeFile = match[1];
  30096. if (Effect.IncludesShadersStore[includeFile]) {
  30097. // Substitution
  30098. var includeContent = Effect.IncludesShadersStore[includeFile];
  30099. if (match[2]) {
  30100. var splits = match[3].split(",");
  30101. for (var index = 0; index < splits.length; index += 2) {
  30102. var source = new RegExp(splits[index], "g");
  30103. var dest = splits[index + 1];
  30104. includeContent = includeContent.replace(source, dest);
  30105. }
  30106. }
  30107. if (match[4]) {
  30108. var indexString = match[5];
  30109. if (indexString.indexOf("..") !== -1) {
  30110. var indexSplits = indexString.split("..");
  30111. var minIndex = parseInt(indexSplits[0]);
  30112. var maxIndex = parseInt(indexSplits[1]);
  30113. var sourceIncludeContent = includeContent.slice(0);
  30114. includeContent = "";
  30115. if (isNaN(maxIndex)) {
  30116. maxIndex = this._indexParameters[indexSplits[1]];
  30117. }
  30118. for (var i = minIndex; i < maxIndex; i++) {
  30119. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  30120. }
  30121. }
  30122. else {
  30123. includeContent = includeContent.replace(/\{X\}/g, indexString);
  30124. }
  30125. }
  30126. // Replace
  30127. returnValue = returnValue.replace(match[0], includeContent);
  30128. }
  30129. else {
  30130. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  30131. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  30132. Effect.IncludesShadersStore[includeFile] = fileContent;
  30133. _this._processIncludes(returnValue, callback);
  30134. });
  30135. return;
  30136. }
  30137. match = regex.exec(sourceCode);
  30138. }
  30139. callback(returnValue);
  30140. };
  30141. Effect.prototype._processPrecision = function (source) {
  30142. if (source.indexOf("precision highp float") === -1) {
  30143. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  30144. source = "precision mediump float;\n" + source;
  30145. }
  30146. else {
  30147. source = "precision highp float;\n" + source;
  30148. }
  30149. }
  30150. else {
  30151. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  30152. source = source.replace("precision highp float", "precision mediump float");
  30153. }
  30154. }
  30155. return source;
  30156. };
  30157. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  30158. try {
  30159. var engine = this._engine;
  30160. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  30161. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  30162. this._attributes = engine.getAttributes(this._program, attributesNames);
  30163. var index;
  30164. for (index = 0; index < this._samplers.length; index++) {
  30165. var sampler = this.getUniform(this._samplers[index]);
  30166. if (sampler == null) {
  30167. this._samplers.splice(index, 1);
  30168. index--;
  30169. }
  30170. }
  30171. engine.bindSamplers(this);
  30172. this._compilationError = "";
  30173. this._isReady = true;
  30174. if (this.onCompiled) {
  30175. this.onCompiled(this);
  30176. }
  30177. }
  30178. catch (e) {
  30179. this._compilationError = e.message;
  30180. // Let's go through fallbacks then
  30181. BABYLON.Tools.Error("Unable to compile effect: ");
  30182. BABYLON.Tools.Error("Defines: " + defines);
  30183. BABYLON.Tools.Error("Error: " + this._compilationError);
  30184. this._dumpShadersName();
  30185. if (fallbacks && fallbacks.isMoreFallbacks) {
  30186. BABYLON.Tools.Error("Trying next fallback.");
  30187. defines = fallbacks.reduce(defines);
  30188. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  30189. }
  30190. else {
  30191. if (this.onError) {
  30192. this.onError(this, this._compilationError);
  30193. }
  30194. }
  30195. }
  30196. };
  30197. Object.defineProperty(Effect.prototype, "isSupported", {
  30198. get: function () {
  30199. return this._compilationError === "";
  30200. },
  30201. enumerable: true,
  30202. configurable: true
  30203. });
  30204. Effect.prototype._bindTexture = function (channel, texture) {
  30205. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  30206. };
  30207. Effect.prototype.setTexture = function (channel, texture) {
  30208. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  30209. };
  30210. Effect.prototype.setTextureArray = function (channel, textures) {
  30211. if (this._samplers.indexOf(channel + "Ex") === -1) {
  30212. var initialPos = this._samplers.indexOf(channel);
  30213. for (var index = 1; index < textures.length; index++) {
  30214. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  30215. }
  30216. }
  30217. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  30218. };
  30219. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  30220. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  30221. };
  30222. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  30223. var cache = this._valueCache[uniformName];
  30224. var flag = matrix.updateFlag;
  30225. if (cache !== undefined && cache === flag) {
  30226. return false;
  30227. }
  30228. this._valueCache[uniformName] = flag;
  30229. return true;
  30230. };
  30231. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  30232. var cache = this._valueCache[uniformName];
  30233. if (!cache) {
  30234. cache = [x, y];
  30235. this._valueCache[uniformName] = cache;
  30236. return true;
  30237. }
  30238. var changed = false;
  30239. if (cache[0] !== x) {
  30240. cache[0] = x;
  30241. changed = true;
  30242. }
  30243. if (cache[1] !== y) {
  30244. cache[1] = y;
  30245. changed = true;
  30246. }
  30247. return changed;
  30248. };
  30249. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  30250. var cache = this._valueCache[uniformName];
  30251. if (!cache) {
  30252. cache = [x, y, z];
  30253. this._valueCache[uniformName] = cache;
  30254. return true;
  30255. }
  30256. var changed = false;
  30257. if (cache[0] !== x) {
  30258. cache[0] = x;
  30259. changed = true;
  30260. }
  30261. if (cache[1] !== y) {
  30262. cache[1] = y;
  30263. changed = true;
  30264. }
  30265. if (cache[2] !== z) {
  30266. cache[2] = z;
  30267. changed = true;
  30268. }
  30269. return changed;
  30270. };
  30271. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  30272. var cache = this._valueCache[uniformName];
  30273. if (!cache) {
  30274. cache = [x, y, z, w];
  30275. this._valueCache[uniformName] = cache;
  30276. return true;
  30277. }
  30278. var changed = false;
  30279. if (cache[0] !== x) {
  30280. cache[0] = x;
  30281. changed = true;
  30282. }
  30283. if (cache[1] !== y) {
  30284. cache[1] = y;
  30285. changed = true;
  30286. }
  30287. if (cache[2] !== z) {
  30288. cache[2] = z;
  30289. changed = true;
  30290. }
  30291. if (cache[3] !== w) {
  30292. cache[3] = w;
  30293. changed = true;
  30294. }
  30295. return changed;
  30296. };
  30297. Effect.prototype.setIntArray = function (uniformName, array) {
  30298. this._valueCache[uniformName] = null;
  30299. this._engine.setIntArray(this.getUniform(uniformName), array);
  30300. return this;
  30301. };
  30302. Effect.prototype.setIntArray2 = function (uniformName, array) {
  30303. this._valueCache[uniformName] = null;
  30304. this._engine.setIntArray2(this.getUniform(uniformName), array);
  30305. return this;
  30306. };
  30307. Effect.prototype.setIntArray3 = function (uniformName, array) {
  30308. this._valueCache[uniformName] = null;
  30309. this._engine.setIntArray3(this.getUniform(uniformName), array);
  30310. return this;
  30311. };
  30312. Effect.prototype.setIntArray4 = function (uniformName, array) {
  30313. this._valueCache[uniformName] = null;
  30314. this._engine.setIntArray4(this.getUniform(uniformName), array);
  30315. return this;
  30316. };
  30317. Effect.prototype.setFloatArray = function (uniformName, array) {
  30318. this._valueCache[uniformName] = null;
  30319. this._engine.setFloatArray(this.getUniform(uniformName), array);
  30320. return this;
  30321. };
  30322. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  30323. this._valueCache[uniformName] = null;
  30324. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  30325. return this;
  30326. };
  30327. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  30328. this._valueCache[uniformName] = null;
  30329. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  30330. return this;
  30331. };
  30332. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  30333. this._valueCache[uniformName] = null;
  30334. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  30335. return this;
  30336. };
  30337. Effect.prototype.setArray = function (uniformName, array) {
  30338. this._valueCache[uniformName] = null;
  30339. this._engine.setArray(this.getUniform(uniformName), array);
  30340. return this;
  30341. };
  30342. Effect.prototype.setArray2 = function (uniformName, array) {
  30343. this._valueCache[uniformName] = null;
  30344. this._engine.setArray2(this.getUniform(uniformName), array);
  30345. return this;
  30346. };
  30347. Effect.prototype.setArray3 = function (uniformName, array) {
  30348. this._valueCache[uniformName] = null;
  30349. this._engine.setArray3(this.getUniform(uniformName), array);
  30350. return this;
  30351. };
  30352. Effect.prototype.setArray4 = function (uniformName, array) {
  30353. this._valueCache[uniformName] = null;
  30354. this._engine.setArray4(this.getUniform(uniformName), array);
  30355. return this;
  30356. };
  30357. Effect.prototype.setMatrices = function (uniformName, matrices) {
  30358. this._valueCache[uniformName] = null;
  30359. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  30360. return this;
  30361. };
  30362. Effect.prototype.setMatrix = function (uniformName, matrix) {
  30363. if (this._cacheMatrix(uniformName, matrix)) {
  30364. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  30365. }
  30366. return this;
  30367. };
  30368. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  30369. this._valueCache[uniformName] = null;
  30370. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  30371. return this;
  30372. };
  30373. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  30374. this._valueCache[uniformName] = null;
  30375. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  30376. return this;
  30377. };
  30378. Effect.prototype.setFloat = function (uniformName, value) {
  30379. var cache = this._valueCache[uniformName];
  30380. if (cache !== undefined && cache === value)
  30381. return this;
  30382. this._valueCache[uniformName] = value;
  30383. this._engine.setFloat(this.getUniform(uniformName), value);
  30384. return this;
  30385. };
  30386. Effect.prototype.setBool = function (uniformName, bool) {
  30387. var cache = this._valueCache[uniformName];
  30388. if (cache !== undefined && cache === bool)
  30389. return this;
  30390. this._valueCache[uniformName] = bool;
  30391. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  30392. return this;
  30393. };
  30394. Effect.prototype.setVector2 = function (uniformName, vector2) {
  30395. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  30396. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  30397. }
  30398. return this;
  30399. };
  30400. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  30401. if (this._cacheFloat2(uniformName, x, y)) {
  30402. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  30403. }
  30404. return this;
  30405. };
  30406. Effect.prototype.setVector3 = function (uniformName, vector3) {
  30407. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  30408. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  30409. }
  30410. return this;
  30411. };
  30412. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  30413. if (this._cacheFloat3(uniformName, x, y, z)) {
  30414. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  30415. }
  30416. return this;
  30417. };
  30418. Effect.prototype.setVector4 = function (uniformName, vector4) {
  30419. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  30420. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  30421. }
  30422. return this;
  30423. };
  30424. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  30425. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  30426. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  30427. }
  30428. return this;
  30429. };
  30430. Effect.prototype.setColor3 = function (uniformName, color3) {
  30431. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  30432. this._engine.setColor3(this.getUniform(uniformName), color3);
  30433. }
  30434. return this;
  30435. };
  30436. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  30437. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  30438. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  30439. }
  30440. return this;
  30441. };
  30442. Effect.prototype._recombineShader = function (node) {
  30443. if (node.define) {
  30444. if (node.condition) {
  30445. var defineIndex = this.defines.indexOf("#define " + node.define);
  30446. if (defineIndex === -1) {
  30447. return null;
  30448. }
  30449. var nextComma = this.defines.indexOf("\n", defineIndex);
  30450. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  30451. var condition = defineValue + node.condition;
  30452. if (!eval(condition)) {
  30453. return null;
  30454. }
  30455. }
  30456. else if (node.ndef) {
  30457. if (this.defines.indexOf("#define " + node.define) !== -1) {
  30458. return null;
  30459. }
  30460. }
  30461. else if (this.defines.indexOf("#define " + node.define) === -1) {
  30462. return null;
  30463. }
  30464. }
  30465. var result = "";
  30466. for (var index = 0; index < node.children.length; index++) {
  30467. var line = node.children[index];
  30468. if (line.children) {
  30469. var combined = this._recombineShader(line);
  30470. if (combined !== null) {
  30471. result += combined + "\r\n";
  30472. }
  30473. continue;
  30474. }
  30475. if (line.length > 0) {
  30476. result += line + "\r\n";
  30477. }
  30478. }
  30479. return result;
  30480. };
  30481. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  30482. var root = {
  30483. children: []
  30484. };
  30485. var currentNode = root;
  30486. var lines = shaderString.split("\n");
  30487. for (var index = 0; index < lines.length; index++) {
  30488. var line = lines[index].trim();
  30489. // #ifdef
  30490. var pos = line.indexOf("#ifdef ");
  30491. if (pos !== -1) {
  30492. var define = line.substr(pos + 7);
  30493. var newNode = {
  30494. condition: null,
  30495. ndef: false,
  30496. define: define,
  30497. children: [],
  30498. parent: currentNode
  30499. };
  30500. currentNode.children.push(newNode);
  30501. currentNode = newNode;
  30502. continue;
  30503. }
  30504. // #ifndef
  30505. var pos = line.indexOf("#ifndef ");
  30506. if (pos !== -1) {
  30507. var define = line.substr(pos + 8);
  30508. newNode = {
  30509. condition: null,
  30510. define: define,
  30511. ndef: true,
  30512. children: [],
  30513. parent: currentNode
  30514. };
  30515. currentNode.children.push(newNode);
  30516. currentNode = newNode;
  30517. continue;
  30518. }
  30519. // #if
  30520. var pos = line.indexOf("#if ");
  30521. if (pos !== -1) {
  30522. var define = line.substr(pos + 4).trim();
  30523. var conditionPos = define.indexOf(" ");
  30524. newNode = {
  30525. condition: define.substr(conditionPos + 1),
  30526. define: define.substr(0, conditionPos),
  30527. ndef: false,
  30528. children: [],
  30529. parent: currentNode
  30530. };
  30531. currentNode.children.push(newNode);
  30532. currentNode = newNode;
  30533. continue;
  30534. }
  30535. // #endif
  30536. pos = line.indexOf("#endif");
  30537. if (pos !== -1) {
  30538. currentNode = currentNode.parent;
  30539. continue;
  30540. }
  30541. currentNode.children.push(line);
  30542. }
  30543. // Recombine
  30544. return this._recombineShader(root);
  30545. };
  30546. return Effect;
  30547. }());
  30548. Effect._uniqueIdSeed = 0;
  30549. // Statics
  30550. Effect.ShadersStore = {};
  30551. Effect.IncludesShadersStore = {};
  30552. BABYLON.Effect = Effect;
  30553. })(BABYLON || (BABYLON = {}));
  30554. //# sourceMappingURL=babylon.effect.js.map
  30555. var BABYLON;
  30556. (function (BABYLON) {
  30557. var MaterialHelper = (function () {
  30558. function MaterialHelper() {
  30559. }
  30560. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  30561. if (defines._areMiscDirty) {
  30562. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  30563. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  30564. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  30565. }
  30566. };
  30567. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  30568. var changed = false;
  30569. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  30570. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  30571. changed = true;
  30572. }
  30573. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  30574. defines["ALPHATEST"] = !defines["ALPHATEST"];
  30575. changed = true;
  30576. }
  30577. if (defines["INSTANCES"] !== useInstances) {
  30578. defines["INSTANCES"] = useInstances;
  30579. changed = true;
  30580. }
  30581. if (changed) {
  30582. defines.markAsUnprocessed();
  30583. }
  30584. };
  30585. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  30586. if (useMorphTargets === void 0) { useMorphTargets = false; }
  30587. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  30588. return;
  30589. }
  30590. defines._normals = defines._needNormals;
  30591. defines._uvs = defines._needUVs;
  30592. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  30593. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30594. defines["TANGENT"] = true;
  30595. }
  30596. if (defines._needUVs) {
  30597. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  30598. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  30599. }
  30600. else {
  30601. defines["UV1"] = false;
  30602. defines["UV2"] = false;
  30603. }
  30604. if (useVertexColor) {
  30605. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  30606. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  30607. }
  30608. if (useBones) {
  30609. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30610. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  30611. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  30612. }
  30613. else {
  30614. defines["NUM_BONE_INFLUENCERS"] = 0;
  30615. defines["BonesPerMesh"] = 0;
  30616. }
  30617. }
  30618. if (useMorphTargets) {
  30619. if (mesh.morphTargetManager) {
  30620. var manager = mesh.morphTargetManager;
  30621. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  30622. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  30623. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  30624. }
  30625. else {
  30626. defines["MORPHTARGETS_NORMAL"] = false;
  30627. defines["MORPHTARGETS"] = false;
  30628. defines["NUM_MORPH_INFLUENCERS"] = 0;
  30629. }
  30630. }
  30631. };
  30632. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  30633. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  30634. if (disableLighting === void 0) { disableLighting = false; }
  30635. if (!defines._areLightsDirty) {
  30636. return defines._needNormals;
  30637. }
  30638. var lightIndex = 0;
  30639. var needNormals = false;
  30640. var needRebuild = false;
  30641. var lightmapMode = false;
  30642. var shadowEnabled = false;
  30643. var specularEnabled = false;
  30644. if (scene.lightsEnabled && !disableLighting) {
  30645. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  30646. var light = _a[_i];
  30647. needNormals = true;
  30648. if (defines["LIGHT" + lightIndex] === undefined) {
  30649. needRebuild = true;
  30650. }
  30651. defines["LIGHT" + lightIndex] = true;
  30652. defines["SPOTLIGHT" + lightIndex] = false;
  30653. defines["HEMILIGHT" + lightIndex] = false;
  30654. defines["POINTLIGHT" + lightIndex] = false;
  30655. defines["DIRLIGHT" + lightIndex] = false;
  30656. var type;
  30657. if (light.getTypeID() === 2) {
  30658. type = "SPOTLIGHT" + lightIndex;
  30659. }
  30660. else if (light.getTypeID() === 3) {
  30661. type = "HEMILIGHT" + lightIndex;
  30662. }
  30663. else if (light.getTypeID() === 0) {
  30664. type = "POINTLIGHT" + lightIndex;
  30665. }
  30666. else {
  30667. type = "DIRLIGHT" + lightIndex;
  30668. }
  30669. defines[type] = true;
  30670. // Specular
  30671. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  30672. specularEnabled = true;
  30673. }
  30674. // Shadows
  30675. defines["SHADOW" + lightIndex] = false;
  30676. if (scene.shadowsEnabled) {
  30677. var shadowGenerator = light.getShadowGenerator();
  30678. if (mesh && mesh.receiveShadows && shadowGenerator) {
  30679. defines["SHADOW" + lightIndex] = true;
  30680. shadowEnabled = true;
  30681. defines["SHADOWPCF" + lightIndex] = false;
  30682. defines["SHADOWESM" + lightIndex] = false;
  30683. if (shadowGenerator.usePoissonSampling) {
  30684. defines["SHADOWPCF" + lightIndex] = true;
  30685. }
  30686. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  30687. defines["SHADOWESM" + lightIndex] = true;
  30688. }
  30689. }
  30690. }
  30691. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  30692. lightmapMode = true;
  30693. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  30694. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  30695. }
  30696. else {
  30697. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  30698. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  30699. }
  30700. lightIndex++;
  30701. if (lightIndex === maxSimultaneousLights)
  30702. break;
  30703. }
  30704. }
  30705. defines["SPECULARTERM"] = specularEnabled;
  30706. defines["SHADOWS"] = shadowEnabled;
  30707. // Resetting all other lights if any
  30708. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  30709. if (defines["LIGHT" + index] !== undefined) {
  30710. defines["LIGHT" + index] = false;
  30711. }
  30712. }
  30713. var caps = scene.getEngine().getCaps();
  30714. if (defines["SHADOWFULLFLOAT"] === undefined) {
  30715. needRebuild = true;
  30716. }
  30717. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  30718. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  30719. if (needRebuild) {
  30720. defines.rebuild();
  30721. }
  30722. return needNormals;
  30723. };
  30724. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  30725. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  30726. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  30727. if (!defines["LIGHT" + lightIndex]) {
  30728. break;
  30729. }
  30730. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  30731. samplersList.push("shadowSampler" + lightIndex);
  30732. }
  30733. if (defines["NUM_MORPH_INFLUENCERS"]) {
  30734. uniformsList.push("morphTargetInfluences");
  30735. }
  30736. };
  30737. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  30738. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  30739. if (!defines["SHADOWS"]) {
  30740. return;
  30741. }
  30742. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  30743. if (!defines["LIGHT" + lightIndex]) {
  30744. break;
  30745. }
  30746. if (lightIndex > 0) {
  30747. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  30748. }
  30749. if (defines["SHADOW" + lightIndex]) {
  30750. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  30751. }
  30752. if (defines["SHADOWPCF" + lightIndex]) {
  30753. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  30754. }
  30755. if (defines["SHADOWESM" + lightIndex]) {
  30756. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  30757. }
  30758. }
  30759. };
  30760. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  30761. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  30762. if (influencers > 0) {
  30763. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  30764. var manager = mesh.morphTargetManager;
  30765. var normal = manager.supportsNormals && defines["NORMAL"];
  30766. for (var index = 0; index < influencers; index++) {
  30767. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  30768. if (normal) {
  30769. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  30770. }
  30771. if (attribs.length > maxAttributesCount) {
  30772. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  30773. }
  30774. }
  30775. }
  30776. };
  30777. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  30778. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  30779. fallbacks.addCPUSkinningFallback(0, mesh);
  30780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30782. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  30783. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30784. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  30785. }
  30786. }
  30787. };
  30788. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  30789. if (defines["INSTANCES"]) {
  30790. attribs.push("world0");
  30791. attribs.push("world1");
  30792. attribs.push("world2");
  30793. attribs.push("world3");
  30794. }
  30795. };
  30796. // Bindings
  30797. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  30798. var shadowGenerator = light.getShadowGenerator();
  30799. if (mesh.receiveShadows && shadowGenerator) {
  30800. if (!light.needCube()) {
  30801. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  30802. }
  30803. else {
  30804. if (!depthValuesAlreadySet) {
  30805. depthValuesAlreadySet = true;
  30806. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  30807. }
  30808. }
  30809. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  30810. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  30811. }
  30812. return depthValuesAlreadySet;
  30813. };
  30814. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  30815. if (light.getTypeID() === 0) {
  30816. // Point Light
  30817. light.transferToEffect(effect, "vLightData" + lightIndex);
  30818. }
  30819. else if (light.getTypeID() === 1) {
  30820. // Directional Light
  30821. light.transferToEffect(effect, "vLightData" + lightIndex);
  30822. }
  30823. else if (light.getTypeID() === 2) {
  30824. // Spot Light
  30825. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  30826. }
  30827. else if (light.getTypeID() === 3) {
  30828. // Hemispheric Light
  30829. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  30830. }
  30831. };
  30832. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  30833. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  30834. var lightIndex = 0;
  30835. var depthValuesAlreadySet = false;
  30836. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  30837. var light = _a[_i];
  30838. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  30839. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  30840. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  30841. if (defines["SPECULARTERM"]) {
  30842. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  30843. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  30844. }
  30845. // Shadows
  30846. if (scene.shadowsEnabled) {
  30847. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  30848. }
  30849. lightIndex++;
  30850. if (lightIndex === maxSimultaneousLights)
  30851. break;
  30852. }
  30853. };
  30854. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  30855. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  30856. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  30857. effect.setColor3("vFogColor", scene.fogColor);
  30858. }
  30859. };
  30860. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  30861. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30862. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  30863. if (matrices) {
  30864. effect.setMatrices("mBones", matrices);
  30865. }
  30866. }
  30867. };
  30868. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  30869. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  30870. return;
  30871. }
  30872. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  30873. };
  30874. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  30875. if (defines["LOGARITHMICDEPTH"]) {
  30876. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  30877. }
  30878. };
  30879. MaterialHelper.BindClipPlane = function (effect, scene) {
  30880. if (scene.clipPlane) {
  30881. var clipPlane = scene.clipPlane;
  30882. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  30883. }
  30884. };
  30885. return MaterialHelper;
  30886. }());
  30887. BABYLON.MaterialHelper = MaterialHelper;
  30888. })(BABYLON || (BABYLON = {}));
  30889. //# sourceMappingURL=babylon.materialHelper.js.map
  30890. var BABYLON;
  30891. (function (BABYLON) {
  30892. var FresnelParameters = (function () {
  30893. function FresnelParameters() {
  30894. this._isEnabled = true;
  30895. this.leftColor = BABYLON.Color3.White();
  30896. this.rightColor = BABYLON.Color3.Black();
  30897. this.bias = 0;
  30898. this.power = 1;
  30899. }
  30900. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  30901. get: function () {
  30902. return this._isEnabled;
  30903. },
  30904. set: function (value) {
  30905. if (this._isEnabled === value) {
  30906. return;
  30907. }
  30908. this._isEnabled = value;
  30909. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. FresnelParameters.prototype.clone = function () {
  30915. var newFresnelParameters = new FresnelParameters();
  30916. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  30917. return newFresnelParameters;
  30918. };
  30919. FresnelParameters.prototype.serialize = function () {
  30920. var serializationObject = {};
  30921. serializationObject.isEnabled = this.isEnabled;
  30922. serializationObject.leftColor = this.leftColor;
  30923. serializationObject.rightColor = this.rightColor;
  30924. serializationObject.bias = this.bias;
  30925. serializationObject.power = this.power;
  30926. return serializationObject;
  30927. };
  30928. FresnelParameters.Parse = function (parsedFresnelParameters) {
  30929. var fresnelParameters = new FresnelParameters();
  30930. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  30931. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  30932. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  30933. fresnelParameters.bias = parsedFresnelParameters.bias;
  30934. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  30935. return fresnelParameters;
  30936. };
  30937. return FresnelParameters;
  30938. }());
  30939. BABYLON.FresnelParameters = FresnelParameters;
  30940. })(BABYLON || (BABYLON = {}));
  30941. //# sourceMappingURL=babylon.fresnelParameters.js.map
  30942. var BABYLON;
  30943. (function (BABYLON) {
  30944. var MaterialDefines = (function () {
  30945. function MaterialDefines() {
  30946. this._isDirty = true;
  30947. this._areLightsDirty = true;
  30948. this._areAttributesDirty = true;
  30949. this._areTexturesDirty = true;
  30950. this._areFresnelDirty = true;
  30951. this._areMiscDirty = true;
  30952. this._normals = false;
  30953. this._uvs = false;
  30954. this._needNormals = false;
  30955. this._needUVs = false;
  30956. }
  30957. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30958. get: function () {
  30959. return this._isDirty;
  30960. },
  30961. enumerable: true,
  30962. configurable: true
  30963. });
  30964. MaterialDefines.prototype.markAsProcessed = function () {
  30965. this._isDirty = false;
  30966. this._areAttributesDirty = false;
  30967. this._areTexturesDirty = false;
  30968. this._areFresnelDirty = false;
  30969. this._areLightsDirty = false;
  30970. this._areMiscDirty = false;
  30971. };
  30972. MaterialDefines.prototype.markAsUnprocessed = function () {
  30973. this._isDirty = true;
  30974. };
  30975. MaterialDefines.prototype.markAllAsDirty = function () {
  30976. this._areTexturesDirty = true;
  30977. this._areAttributesDirty = true;
  30978. this._areLightsDirty = true;
  30979. this._areFresnelDirty = true;
  30980. this._areMiscDirty = true;
  30981. this._isDirty = true;
  30982. };
  30983. MaterialDefines.prototype.markAsLightDirty = function () {
  30984. this._areLightsDirty = true;
  30985. this._isDirty = true;
  30986. };
  30987. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30988. this._areAttributesDirty = true;
  30989. this._isDirty = true;
  30990. };
  30991. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30992. this._areTexturesDirty = true;
  30993. this._isDirty = true;
  30994. };
  30995. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30996. this._areFresnelDirty = true;
  30997. this._isDirty = true;
  30998. };
  30999. MaterialDefines.prototype.markAsMiscDirty = function () {
  31000. this._areMiscDirty = true;
  31001. this._isDirty = true;
  31002. };
  31003. MaterialDefines.prototype.rebuild = function () {
  31004. if (this._keys) {
  31005. delete this._keys;
  31006. }
  31007. this._keys = [];
  31008. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31009. var key = _a[_i];
  31010. if (key[0] === "_") {
  31011. continue;
  31012. }
  31013. this._keys.push(key);
  31014. }
  31015. };
  31016. MaterialDefines.prototype.isEqual = function (other) {
  31017. if (this._keys.length !== other._keys.length) {
  31018. return false;
  31019. }
  31020. for (var index = 0; index < this._keys.length; index++) {
  31021. var prop = this._keys[index];
  31022. if (this[prop] !== other[prop]) {
  31023. return false;
  31024. }
  31025. }
  31026. return true;
  31027. };
  31028. MaterialDefines.prototype.cloneTo = function (other) {
  31029. if (this._keys.length !== other._keys.length) {
  31030. other._keys = this._keys.slice(0);
  31031. }
  31032. for (var index = 0; index < this._keys.length; index++) {
  31033. var prop = this._keys[index];
  31034. other[prop] = this[prop];
  31035. }
  31036. };
  31037. MaterialDefines.prototype.reset = function () {
  31038. for (var index = 0; index < this._keys.length; index++) {
  31039. var prop = this._keys[index];
  31040. if (typeof (this[prop]) === "number") {
  31041. this[prop] = 0;
  31042. }
  31043. else {
  31044. this[prop] = false;
  31045. }
  31046. }
  31047. };
  31048. MaterialDefines.prototype.toString = function () {
  31049. var result = "";
  31050. for (var index = 0; index < this._keys.length; index++) {
  31051. var prop = this._keys[index];
  31052. var value = this[prop];
  31053. if (typeof (value) === "number") {
  31054. result += "#define " + prop + " " + this[prop] + "\n";
  31055. }
  31056. else if (value) {
  31057. result += "#define " + prop + "\n";
  31058. }
  31059. }
  31060. return result;
  31061. };
  31062. return MaterialDefines;
  31063. }());
  31064. BABYLON.MaterialDefines = MaterialDefines;
  31065. var Material = (function () {
  31066. function Material(name, scene, doNotAdd) {
  31067. this.checkReadyOnEveryCall = false;
  31068. this.checkReadyOnlyOnce = false;
  31069. this.state = "";
  31070. this.alpha = 1.0;
  31071. this._backFaceCulling = true;
  31072. this.doNotSerialize = false;
  31073. this.storeEffectOnSubMeshes = false;
  31074. /**
  31075. * An event triggered when the material is disposed.
  31076. * @type {BABYLON.Observable}
  31077. */
  31078. this.onDisposeObservable = new BABYLON.Observable();
  31079. /**
  31080. * An event triggered when the material is bound.
  31081. * @type {BABYLON.Observable}
  31082. */
  31083. this.onBindObservable = new BABYLON.Observable();
  31084. /**
  31085. * An event triggered when the material is unbound.
  31086. * @type {BABYLON.Observable}
  31087. */
  31088. this.onUnBindObservable = new BABYLON.Observable();
  31089. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31090. this.disableDepthWrite = false;
  31091. this._fogEnabled = true;
  31092. this.pointSize = 1.0;
  31093. this.zOffset = 0;
  31094. this._wasPreviouslyReady = false;
  31095. this._fillMode = Material.TriangleFillMode;
  31096. this.name = name;
  31097. this.id = name;
  31098. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31099. if (this._scene.useRightHandedSystem) {
  31100. this.sideOrientation = Material.ClockWiseSideOrientation;
  31101. }
  31102. else {
  31103. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31104. }
  31105. if (!doNotAdd) {
  31106. this._scene.materials.push(this);
  31107. }
  31108. }
  31109. Object.defineProperty(Material, "TriangleFillMode", {
  31110. get: function () {
  31111. return Material._TriangleFillMode;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Material, "WireFrameFillMode", {
  31117. get: function () {
  31118. return Material._WireFrameFillMode;
  31119. },
  31120. enumerable: true,
  31121. configurable: true
  31122. });
  31123. Object.defineProperty(Material, "PointFillMode", {
  31124. get: function () {
  31125. return Material._PointFillMode;
  31126. },
  31127. enumerable: true,
  31128. configurable: true
  31129. });
  31130. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31131. get: function () {
  31132. return Material._ClockWiseSideOrientation;
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31138. get: function () {
  31139. return Material._CounterClockWiseSideOrientation;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(Material, "TextureDirtyFlag", {
  31145. get: function () {
  31146. return Material._TextureDirtyFlag;
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Object.defineProperty(Material, "LightDirtyFlag", {
  31152. get: function () {
  31153. return Material._LightDirtyFlag;
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31159. get: function () {
  31160. return Material._FresnelDirtyFlag;
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31166. get: function () {
  31167. return Material._AttributesDirtyFlag;
  31168. },
  31169. enumerable: true,
  31170. configurable: true
  31171. });
  31172. Object.defineProperty(Material, "MiscDirtyFlag", {
  31173. get: function () {
  31174. return Material._MiscDirtyFlag;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31180. get: function () {
  31181. return this._backFaceCulling;
  31182. },
  31183. set: function (value) {
  31184. if (this._backFaceCulling === value) {
  31185. return;
  31186. }
  31187. this._backFaceCulling = value;
  31188. this.markAsDirty(Material.TextureDirtyFlag);
  31189. },
  31190. enumerable: true,
  31191. configurable: true
  31192. });
  31193. Object.defineProperty(Material.prototype, "onDispose", {
  31194. set: function (callback) {
  31195. if (this._onDisposeObserver) {
  31196. this.onDisposeObservable.remove(this._onDisposeObserver);
  31197. }
  31198. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31199. },
  31200. enumerable: true,
  31201. configurable: true
  31202. });
  31203. Object.defineProperty(Material.prototype, "onBind", {
  31204. set: function (callback) {
  31205. if (this._onBindObserver) {
  31206. this.onBindObservable.remove(this._onBindObserver);
  31207. }
  31208. this._onBindObserver = this.onBindObservable.add(callback);
  31209. },
  31210. enumerable: true,
  31211. configurable: true
  31212. });
  31213. Object.defineProperty(Material.prototype, "fogEnabled", {
  31214. get: function () {
  31215. return this._fogEnabled;
  31216. },
  31217. set: function (value) {
  31218. if (this._fogEnabled === value) {
  31219. return;
  31220. }
  31221. this._fogEnabled = value;
  31222. this.markAsDirty(Material.MiscDirtyFlag);
  31223. },
  31224. enumerable: true,
  31225. configurable: true
  31226. });
  31227. Object.defineProperty(Material.prototype, "wireframe", {
  31228. get: function () {
  31229. return this._fillMode === Material.WireFrameFillMode;
  31230. },
  31231. set: function (value) {
  31232. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31233. },
  31234. enumerable: true,
  31235. configurable: true
  31236. });
  31237. Object.defineProperty(Material.prototype, "pointsCloud", {
  31238. get: function () {
  31239. return this._fillMode === Material.PointFillMode;
  31240. },
  31241. set: function (value) {
  31242. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31243. },
  31244. enumerable: true,
  31245. configurable: true
  31246. });
  31247. Object.defineProperty(Material.prototype, "fillMode", {
  31248. get: function () {
  31249. return this._fillMode;
  31250. },
  31251. set: function (value) {
  31252. if (this._fillMode === value) {
  31253. return;
  31254. }
  31255. this._fillMode = value;
  31256. this.markAsDirty(Material.MiscDirtyFlag);
  31257. },
  31258. enumerable: true,
  31259. configurable: true
  31260. });
  31261. /**
  31262. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31263. * subclasses should override adding information pertainent to themselves
  31264. */
  31265. Material.prototype.toString = function (fullDetails) {
  31266. var ret = "Name: " + this.name;
  31267. if (fullDetails) {
  31268. }
  31269. return ret;
  31270. };
  31271. /**
  31272. * Child classes can use it to update shaders
  31273. */
  31274. Material.prototype.markAsDirty = function (flag) {
  31275. };
  31276. Material.prototype.getClassName = function () {
  31277. return "Material";
  31278. };
  31279. Object.defineProperty(Material.prototype, "isFrozen", {
  31280. get: function () {
  31281. return this.checkReadyOnlyOnce;
  31282. },
  31283. enumerable: true,
  31284. configurable: true
  31285. });
  31286. Material.prototype.freeze = function () {
  31287. this.checkReadyOnlyOnce = true;
  31288. };
  31289. Material.prototype.unfreeze = function () {
  31290. this.checkReadyOnlyOnce = false;
  31291. };
  31292. Material.prototype.isReady = function (mesh, useInstances) {
  31293. return true;
  31294. };
  31295. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31296. return false;
  31297. };
  31298. Material.prototype.getEffect = function () {
  31299. return this._effect;
  31300. };
  31301. Material.prototype.getScene = function () {
  31302. return this._scene;
  31303. };
  31304. Material.prototype.needAlphaBlending = function () {
  31305. return (this.alpha < 1.0);
  31306. };
  31307. Material.prototype.needAlphaTesting = function () {
  31308. return false;
  31309. };
  31310. Material.prototype.getAlphaTestTexture = function () {
  31311. return null;
  31312. };
  31313. Material.prototype.markDirty = function () {
  31314. this._wasPreviouslyReady = false;
  31315. };
  31316. Material.prototype._preBind = function (effect) {
  31317. var engine = this._scene.getEngine();
  31318. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  31319. engine.enableEffect(effect ? effect : this._effect);
  31320. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31321. };
  31322. Material.prototype.bind = function (world, mesh) {
  31323. };
  31324. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31325. };
  31326. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31327. };
  31328. Material.prototype._afterBind = function (mesh) {
  31329. this._scene._cachedMaterial = this;
  31330. this.onBindObservable.notifyObservers(mesh);
  31331. if (this.disableDepthWrite) {
  31332. var engine = this._scene.getEngine();
  31333. this._cachedDepthWriteState = engine.getDepthWrite();
  31334. engine.setDepthWrite(false);
  31335. }
  31336. };
  31337. Material.prototype.unbind = function () {
  31338. this.onUnBindObservable.notifyObservers(this);
  31339. if (this.disableDepthWrite) {
  31340. var engine = this._scene.getEngine();
  31341. engine.setDepthWrite(this._cachedDepthWriteState);
  31342. }
  31343. };
  31344. Material.prototype.clone = function (name) {
  31345. return null;
  31346. };
  31347. Material.prototype.getBindedMeshes = function () {
  31348. var result = new Array();
  31349. for (var index = 0; index < this._scene.meshes.length; index++) {
  31350. var mesh = this._scene.meshes[index];
  31351. if (mesh.material === this) {
  31352. result.push(mesh);
  31353. }
  31354. }
  31355. return result;
  31356. };
  31357. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31358. // Animations
  31359. this.getScene().stopAnimation(this);
  31360. // Remove from scene
  31361. var index = this._scene.materials.indexOf(this);
  31362. if (index >= 0) {
  31363. this._scene.materials.splice(index, 1);
  31364. }
  31365. // Remove from meshes
  31366. for (index = 0; index < this._scene.meshes.length; index++) {
  31367. var mesh = this._scene.meshes[index];
  31368. if (mesh.material === this) {
  31369. mesh.material = null;
  31370. if (mesh.geometry) {
  31371. var geometry = mesh.geometry;
  31372. if (this.storeEffectOnSubMeshes) {
  31373. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31374. var subMesh = _a[_i];
  31375. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31376. }
  31377. }
  31378. else {
  31379. geometry._releaseVertexArrayObject(this._effect);
  31380. }
  31381. }
  31382. }
  31383. }
  31384. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31385. if (forceDisposeEffect && this._effect) {
  31386. if (this.storeEffectOnSubMeshes) {
  31387. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31388. var subMesh = _c[_b];
  31389. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31390. }
  31391. }
  31392. else {
  31393. this._scene.getEngine()._releaseEffect(this._effect);
  31394. }
  31395. this._effect = null;
  31396. }
  31397. // Callback
  31398. this.onDisposeObservable.notifyObservers(this);
  31399. this.onDisposeObservable.clear();
  31400. this.onBindObservable.clear();
  31401. this.onUnBindObservable.clear();
  31402. };
  31403. Material.prototype.serialize = function () {
  31404. return BABYLON.SerializationHelper.Serialize(this);
  31405. };
  31406. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31407. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31408. multiMaterial.id = parsedMultiMaterial.id;
  31409. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31410. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31411. var subMatId = parsedMultiMaterial.materials[matIndex];
  31412. if (subMatId) {
  31413. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31414. }
  31415. else {
  31416. multiMaterial.subMaterials.push(null);
  31417. }
  31418. }
  31419. return multiMaterial;
  31420. };
  31421. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31422. if (!parsedMaterial.customType) {
  31423. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31424. }
  31425. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31426. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31427. ;
  31428. };
  31429. return Material;
  31430. }());
  31431. Material._TriangleFillMode = 0;
  31432. Material._WireFrameFillMode = 1;
  31433. Material._PointFillMode = 2;
  31434. Material._ClockWiseSideOrientation = 0;
  31435. Material._CounterClockWiseSideOrientation = 1;
  31436. Material._TextureDirtyFlag = 0;
  31437. Material._LightDirtyFlag = 1;
  31438. Material._FresnelDirtyFlag = 2;
  31439. Material._AttributesDirtyFlag = 4;
  31440. Material._MiscDirtyFlag = 8;
  31441. __decorate([
  31442. BABYLON.serialize()
  31443. ], Material.prototype, "id", void 0);
  31444. __decorate([
  31445. BABYLON.serialize()
  31446. ], Material.prototype, "name", void 0);
  31447. __decorate([
  31448. BABYLON.serialize()
  31449. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31450. __decorate([
  31451. BABYLON.serialize()
  31452. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31453. __decorate([
  31454. BABYLON.serialize()
  31455. ], Material.prototype, "state", void 0);
  31456. __decorate([
  31457. BABYLON.serialize()
  31458. ], Material.prototype, "alpha", void 0);
  31459. __decorate([
  31460. BABYLON.serialize("backFaceCulling")
  31461. ], Material.prototype, "_backFaceCulling", void 0);
  31462. __decorate([
  31463. BABYLON.serialize()
  31464. ], Material.prototype, "sideOrientation", void 0);
  31465. __decorate([
  31466. BABYLON.serialize()
  31467. ], Material.prototype, "alphaMode", void 0);
  31468. __decorate([
  31469. BABYLON.serialize()
  31470. ], Material.prototype, "disableDepthWrite", void 0);
  31471. __decorate([
  31472. BABYLON.serialize("fogEnabled")
  31473. ], Material.prototype, "_fogEnabled", void 0);
  31474. __decorate([
  31475. BABYLON.serialize()
  31476. ], Material.prototype, "pointSize", void 0);
  31477. __decorate([
  31478. BABYLON.serialize()
  31479. ], Material.prototype, "zOffset", void 0);
  31480. __decorate([
  31481. BABYLON.serialize()
  31482. ], Material.prototype, "wireframe", null);
  31483. __decorate([
  31484. BABYLON.serialize()
  31485. ], Material.prototype, "pointsCloud", null);
  31486. __decorate([
  31487. BABYLON.serialize()
  31488. ], Material.prototype, "fillMode", null);
  31489. BABYLON.Material = Material;
  31490. })(BABYLON || (BABYLON = {}));
  31491. //# sourceMappingURL=babylon.material.js.map
  31492. var BABYLON;
  31493. (function (BABYLON) {
  31494. var PushMaterial = (function (_super) {
  31495. __extends(PushMaterial, _super);
  31496. function PushMaterial(name, scene) {
  31497. var _this = _super.call(this, name, scene) || this;
  31498. _this.storeEffectOnSubMeshes = true;
  31499. return _this;
  31500. }
  31501. PushMaterial.prototype.getEffect = function () {
  31502. return this._activeEffect;
  31503. };
  31504. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  31505. if (!mesh) {
  31506. return false;
  31507. }
  31508. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  31509. return true;
  31510. }
  31511. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  31512. };
  31513. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  31514. this._activeEffect.setMatrix("world", world);
  31515. };
  31516. PushMaterial.prototype.bind = function (world, mesh) {
  31517. if (!mesh) {
  31518. return;
  31519. }
  31520. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  31521. };
  31522. PushMaterial.prototype._afterBind = function (mesh, effect) {
  31523. _super.prototype._afterBind.call(this, mesh);
  31524. this.getScene()._cachedEffect = effect;
  31525. };
  31526. PushMaterial.prototype._mustRebind = function (scene, effect) {
  31527. return scene.getCachedEffect() !== effect || scene.getCachedMaterial() !== this;
  31528. };
  31529. PushMaterial.prototype.markAsDirty = function (flag) {
  31530. if (flag & BABYLON.Material.TextureDirtyFlag) {
  31531. this._markAllSubMeshesAsTexturesDirty();
  31532. }
  31533. if (flag & BABYLON.Material.LightDirtyFlag) {
  31534. this._markAllSubMeshesAsLightsDirty();
  31535. }
  31536. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  31537. this._markAllSubMeshesAsFresnelDirty();
  31538. }
  31539. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  31540. this._markAllSubMeshesAsAttributesDirty();
  31541. }
  31542. if (flag & BABYLON.Material.MiscDirtyFlag) {
  31543. this._markAllSubMeshesAsMiscDirty();
  31544. }
  31545. };
  31546. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  31547. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31548. var mesh = _a[_i];
  31549. if (!mesh.subMeshes) {
  31550. continue;
  31551. }
  31552. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31553. var subMesh = _c[_b];
  31554. if (subMesh.getMaterial() !== this) {
  31555. continue;
  31556. }
  31557. if (!subMesh._materialDefines) {
  31558. return;
  31559. }
  31560. func(subMesh._materialDefines);
  31561. }
  31562. }
  31563. };
  31564. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31565. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31566. };
  31567. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31568. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31569. };
  31570. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  31571. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31572. };
  31573. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31574. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31575. };
  31576. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  31577. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31578. };
  31579. return PushMaterial;
  31580. }(BABYLON.Material));
  31581. BABYLON.PushMaterial = PushMaterial;
  31582. })(BABYLON || (BABYLON = {}));
  31583. //# sourceMappingURL=babylon.pushMaterial.js.map
  31584. var BABYLON;
  31585. (function (BABYLON) {
  31586. var StandardMaterialDefines = (function (_super) {
  31587. __extends(StandardMaterialDefines, _super);
  31588. function StandardMaterialDefines() {
  31589. var _this = _super.call(this) || this;
  31590. _this.DIFFUSE = false;
  31591. _this.AMBIENT = false;
  31592. _this.OPACITY = false;
  31593. _this.OPACITYRGB = false;
  31594. _this.REFLECTION = false;
  31595. _this.EMISSIVE = false;
  31596. _this.SPECULAR = false;
  31597. _this.BUMP = false;
  31598. _this.PARALLAX = false;
  31599. _this.PARALLAXOCCLUSION = false;
  31600. _this.SPECULAROVERALPHA = false;
  31601. _this.CLIPPLANE = false;
  31602. _this.ALPHATEST = false;
  31603. _this.ALPHAFROMDIFFUSE = false;
  31604. _this.POINTSIZE = false;
  31605. _this.FOG = false;
  31606. _this.SPECULARTERM = false;
  31607. _this.DIFFUSEFRESNEL = false;
  31608. _this.OPACITYFRESNEL = false;
  31609. _this.REFLECTIONFRESNEL = false;
  31610. _this.REFRACTIONFRESNEL = false;
  31611. _this.EMISSIVEFRESNEL = false;
  31612. _this.FRESNEL = false;
  31613. _this.NORMAL = false;
  31614. _this.UV1 = false;
  31615. _this.UV2 = false;
  31616. _this.VERTEXCOLOR = false;
  31617. _this.VERTEXALPHA = false;
  31618. _this.NUM_BONE_INFLUENCERS = 0;
  31619. _this.BonesPerMesh = 0;
  31620. _this.INSTANCES = false;
  31621. _this.GLOSSINESS = false;
  31622. _this.ROUGHNESS = false;
  31623. _this.EMISSIVEASILLUMINATION = false;
  31624. _this.LINKEMISSIVEWITHDIFFUSE = false;
  31625. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  31626. _this.LIGHTMAP = false;
  31627. _this.USELIGHTMAPASSHADOWMAP = false;
  31628. _this.REFLECTIONMAP_3D = false;
  31629. _this.REFLECTIONMAP_SPHERICAL = false;
  31630. _this.REFLECTIONMAP_PLANAR = false;
  31631. _this.REFLECTIONMAP_CUBIC = false;
  31632. _this.REFLECTIONMAP_PROJECTION = false;
  31633. _this.REFLECTIONMAP_SKYBOX = false;
  31634. _this.REFLECTIONMAP_EXPLICIT = false;
  31635. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31636. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31637. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31638. _this.INVERTCUBICMAP = false;
  31639. _this.LOGARITHMICDEPTH = false;
  31640. _this.REFRACTION = false;
  31641. _this.REFRACTIONMAP_3D = false;
  31642. _this.REFLECTIONOVERALPHA = false;
  31643. _this.INVERTNORMALMAPX = false;
  31644. _this.INVERTNORMALMAPY = false;
  31645. _this.TWOSIDEDLIGHTING = false;
  31646. _this.SHADOWFULLFLOAT = false;
  31647. _this.CAMERACOLORGRADING = false;
  31648. _this.CAMERACOLORCURVES = false;
  31649. _this.MORPHTARGETS = false;
  31650. _this.MORPHTARGETS_NORMAL = false;
  31651. _this.NUM_MORPH_INFLUENCERS = 0;
  31652. _this.rebuild();
  31653. return _this;
  31654. }
  31655. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  31656. var modes = [
  31657. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  31658. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  31659. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  31660. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  31661. ];
  31662. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  31663. var mode = modes_1[_i];
  31664. this[mode] = (mode === modeToEnable);
  31665. }
  31666. };
  31667. return StandardMaterialDefines;
  31668. }(BABYLON.MaterialDefines));
  31669. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  31670. var StandardMaterial = (function (_super) {
  31671. __extends(StandardMaterial, _super);
  31672. function StandardMaterial(name, scene) {
  31673. var _this = _super.call(this, name, scene) || this;
  31674. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  31675. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  31676. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  31677. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  31678. _this.specularPower = 64;
  31679. _this._useAlphaFromDiffuseTexture = false;
  31680. _this._useEmissiveAsIllumination = false;
  31681. _this._linkEmissiveWithDiffuse = false;
  31682. _this._useSpecularOverAlpha = false;
  31683. _this._useReflectionOverAlpha = false;
  31684. _this._disableLighting = false;
  31685. _this._useParallax = false;
  31686. _this._useParallaxOcclusion = false;
  31687. _this.parallaxScaleBias = 0.05;
  31688. _this._roughness = 0;
  31689. _this.indexOfRefraction = 0.98;
  31690. _this.invertRefractionY = true;
  31691. _this._useLightmapAsShadowmap = false;
  31692. _this._useReflectionFresnelFromSpecular = false;
  31693. _this._useGlossinessFromSpecularMapAlpha = false;
  31694. _this._maxSimultaneousLights = 4;
  31695. /**
  31696. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  31697. */
  31698. _this._invertNormalMapX = false;
  31699. /**
  31700. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  31701. */
  31702. _this._invertNormalMapY = false;
  31703. /**
  31704. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31705. */
  31706. _this._twoSidedLighting = false;
  31707. /**
  31708. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31709. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31710. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  31711. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31712. */
  31713. _this._cameraColorCurves = null;
  31714. _this._renderTargets = new BABYLON.SmartArray(16);
  31715. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31716. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31717. _this.getRenderTargetTextures = function () {
  31718. _this._renderTargets.reset();
  31719. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31720. _this._renderTargets.push(_this._reflectionTexture);
  31721. }
  31722. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31723. _this._renderTargets.push(_this._refractionTexture);
  31724. }
  31725. return _this._renderTargets;
  31726. };
  31727. return _this;
  31728. }
  31729. StandardMaterial.prototype.getClassName = function () {
  31730. return "StandardMaterial";
  31731. };
  31732. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  31733. get: function () {
  31734. return this._useLogarithmicDepth;
  31735. },
  31736. set: function (value) {
  31737. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31738. this._markAllSubMeshesAsMiscDirty();
  31739. },
  31740. enumerable: true,
  31741. configurable: true
  31742. });
  31743. StandardMaterial.prototype.needAlphaBlending = function () {
  31744. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  31745. };
  31746. StandardMaterial.prototype.needAlphaTesting = function () {
  31747. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  31748. };
  31749. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  31750. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  31751. };
  31752. StandardMaterial.prototype.getAlphaTestTexture = function () {
  31753. return this._diffuseTexture;
  31754. };
  31755. /**
  31756. * Child classes can use it to update shaders
  31757. */
  31758. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31759. if (this.isFrozen) {
  31760. if (this._wasPreviouslyReady && subMesh.effect) {
  31761. return true;
  31762. }
  31763. }
  31764. if (!subMesh._materialDefines) {
  31765. subMesh._materialDefines = new StandardMaterialDefines();
  31766. }
  31767. var scene = this.getScene();
  31768. var defines = subMesh._materialDefines;
  31769. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31770. if (defines._renderId === scene.getRenderId()) {
  31771. return true;
  31772. }
  31773. }
  31774. var engine = scene.getEngine();
  31775. // Lights
  31776. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31777. // Textures
  31778. if (defines._areTexturesDirty) {
  31779. defines._needUVs = false;
  31780. if (scene.texturesEnabled) {
  31781. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31782. if (!this._diffuseTexture.isReady()) {
  31783. return false;
  31784. }
  31785. else {
  31786. defines._needUVs = true;
  31787. defines.DIFFUSE = true;
  31788. }
  31789. }
  31790. else {
  31791. defines.DIFFUSE = false;
  31792. }
  31793. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31794. if (!this._ambientTexture.isReady()) {
  31795. return false;
  31796. }
  31797. else {
  31798. defines._needUVs = true;
  31799. defines.AMBIENT = true;
  31800. }
  31801. }
  31802. else {
  31803. defines.AMBIENT = false;
  31804. }
  31805. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31806. if (!this._opacityTexture.isReady()) {
  31807. return false;
  31808. }
  31809. else {
  31810. defines._needUVs = true;
  31811. defines.OPACITY = true;
  31812. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31813. }
  31814. }
  31815. else {
  31816. defines.OPACITY = false;
  31817. }
  31818. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31819. if (!this._reflectionTexture.isReady()) {
  31820. return false;
  31821. }
  31822. else {
  31823. defines._needNormals = true;
  31824. defines.REFLECTION = true;
  31825. defines.ROUGHNESS = (this._roughness > 0);
  31826. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  31827. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  31828. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  31829. switch (this._reflectionTexture.coordinatesMode) {
  31830. case BABYLON.Texture.CUBIC_MODE:
  31831. case BABYLON.Texture.INVCUBIC_MODE:
  31832. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  31833. break;
  31834. case BABYLON.Texture.EXPLICIT_MODE:
  31835. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  31836. break;
  31837. case BABYLON.Texture.PLANAR_MODE:
  31838. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  31839. break;
  31840. case BABYLON.Texture.PROJECTION_MODE:
  31841. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  31842. break;
  31843. case BABYLON.Texture.SKYBOX_MODE:
  31844. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  31845. break;
  31846. case BABYLON.Texture.SPHERICAL_MODE:
  31847. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  31848. break;
  31849. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31850. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  31851. break;
  31852. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31853. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  31854. break;
  31855. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31856. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  31857. break;
  31858. }
  31859. }
  31860. }
  31861. else {
  31862. defines.REFLECTION = false;
  31863. }
  31864. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31865. if (!this._emissiveTexture.isReady()) {
  31866. return false;
  31867. }
  31868. else {
  31869. defines._needUVs = true;
  31870. defines.EMISSIVE = true;
  31871. }
  31872. }
  31873. else {
  31874. defines.EMISSIVE = false;
  31875. }
  31876. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31877. if (!this._lightmapTexture.isReady()) {
  31878. return false;
  31879. }
  31880. else {
  31881. defines._needUVs = true;
  31882. defines.LIGHTMAP = true;
  31883. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31884. }
  31885. }
  31886. else {
  31887. defines.LIGHTMAP = false;
  31888. }
  31889. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31890. if (!this._specularTexture.isReady()) {
  31891. return false;
  31892. }
  31893. else {
  31894. defines._needUVs = true;
  31895. defines.SPECULAR = true;
  31896. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  31897. }
  31898. }
  31899. else {
  31900. defines.SPECULAR = false;
  31901. }
  31902. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  31903. if (!this._bumpTexture.isReady()) {
  31904. return false;
  31905. }
  31906. else {
  31907. defines._needUVs = true;
  31908. defines.BUMP = true;
  31909. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  31910. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  31911. defines.PARALLAX = this._useParallax;
  31912. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  31913. }
  31914. }
  31915. else {
  31916. defines.BUMP = false;
  31917. }
  31918. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31919. if (!this._refractionTexture.isReady()) {
  31920. return false;
  31921. }
  31922. else {
  31923. defines._needUVs = true;
  31924. defines.REFRACTION = true;
  31925. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  31926. }
  31927. }
  31928. else {
  31929. defines.REFRACTION = false;
  31930. }
  31931. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  31932. if (!this._cameraColorGradingTexture.isReady()) {
  31933. return false;
  31934. }
  31935. else {
  31936. defines.CAMERACOLORGRADING = true;
  31937. }
  31938. }
  31939. else {
  31940. defines.CAMERACOLORGRADING = false;
  31941. }
  31942. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  31943. }
  31944. else {
  31945. defines.DIFFUSE = false;
  31946. defines.AMBIENT = false;
  31947. defines.OPACITY = false;
  31948. defines.REFLECTION = false;
  31949. defines.EMISSIVE = false;
  31950. defines.LIGHTMAP = false;
  31951. defines.BUMP = false;
  31952. defines.REFRACTION = false;
  31953. defines.CAMERACOLORGRADING = false;
  31954. }
  31955. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  31956. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  31957. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  31958. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  31959. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  31960. }
  31961. if (defines._areFresnelDirty) {
  31962. if (StandardMaterial.FresnelEnabled) {
  31963. // Fresnel
  31964. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  31965. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  31966. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  31967. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  31968. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  31969. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  31970. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  31971. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  31972. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  31973. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  31974. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  31975. defines._needNormals = true;
  31976. defines.FRESNEL = true;
  31977. }
  31978. }
  31979. else {
  31980. defines.FRESNEL = false;
  31981. }
  31982. }
  31983. // Misc.
  31984. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  31985. // Attribs
  31986. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  31987. // Values that need to be evaluated on every frame
  31988. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  31989. if (scene._mirroredCameraPosition && defines.BUMP) {
  31990. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  31991. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  31992. defines.markAsUnprocessed();
  31993. }
  31994. // Get correct effect
  31995. if (defines.isDirty) {
  31996. defines.markAsProcessed();
  31997. scene.resetCachedMaterial();
  31998. // Fallbacks
  31999. var fallbacks = new BABYLON.EffectFallbacks();
  32000. if (defines.REFLECTION) {
  32001. fallbacks.addFallback(0, "REFLECTION");
  32002. }
  32003. if (defines.SPECULAR) {
  32004. fallbacks.addFallback(0, "SPECULAR");
  32005. }
  32006. if (defines.BUMP) {
  32007. fallbacks.addFallback(0, "BUMP");
  32008. }
  32009. if (defines.PARALLAX) {
  32010. fallbacks.addFallback(1, "PARALLAX");
  32011. }
  32012. if (defines.PARALLAXOCCLUSION) {
  32013. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32014. }
  32015. if (defines.SPECULAROVERALPHA) {
  32016. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32017. }
  32018. if (defines.FOG) {
  32019. fallbacks.addFallback(1, "FOG");
  32020. }
  32021. if (defines.POINTSIZE) {
  32022. fallbacks.addFallback(0, "POINTSIZE");
  32023. }
  32024. if (defines.LOGARITHMICDEPTH) {
  32025. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32026. }
  32027. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32028. if (defines.SPECULARTERM) {
  32029. fallbacks.addFallback(0, "SPECULARTERM");
  32030. }
  32031. if (defines.DIFFUSEFRESNEL) {
  32032. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  32033. }
  32034. if (defines.OPACITYFRESNEL) {
  32035. fallbacks.addFallback(2, "OPACITYFRESNEL");
  32036. }
  32037. if (defines.REFLECTIONFRESNEL) {
  32038. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  32039. }
  32040. if (defines.EMISSIVEFRESNEL) {
  32041. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  32042. }
  32043. if (defines.FRESNEL) {
  32044. fallbacks.addFallback(4, "FRESNEL");
  32045. }
  32046. //Attributes
  32047. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32048. if (defines.NORMAL) {
  32049. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32050. }
  32051. if (defines.UV1) {
  32052. attribs.push(BABYLON.VertexBuffer.UVKind);
  32053. }
  32054. if (defines.UV2) {
  32055. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32056. }
  32057. if (defines.VERTEXCOLOR) {
  32058. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32059. }
  32060. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32061. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32062. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32063. var shaderName = "default";
  32064. if (this.customShaderNameResolve) {
  32065. shaderName = this.customShaderNameResolve(shaderName);
  32066. }
  32067. var join = defines.toString();
  32068. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  32069. "vFogInfos", "vFogColor", "pointSize",
  32070. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32071. "mBones",
  32072. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32073. "depthValues",
  32074. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  32075. "logarithmicDepthConstant"
  32076. ];
  32077. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  32078. if (defines.CAMERACOLORCURVES) {
  32079. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32080. }
  32081. if (defines.CAMERACOLORGRADING) {
  32082. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  32083. }
  32084. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, defines, this._maxSimultaneousLights);
  32085. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  32086. attributes: attribs,
  32087. uniformsNames: uniforms,
  32088. samplers: samplers,
  32089. defines: join,
  32090. fallbacks: fallbacks,
  32091. onCompiled: this.onCompiled,
  32092. onError: this.onError,
  32093. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32094. }, engine), defines);
  32095. }
  32096. if (!subMesh.effect.isReady()) {
  32097. return false;
  32098. }
  32099. defines._renderId = scene.getRenderId();
  32100. this._wasPreviouslyReady = true;
  32101. return true;
  32102. };
  32103. StandardMaterial.prototype.unbind = function () {
  32104. if (this._activeEffect) {
  32105. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32106. this._activeEffect.setTexture("reflection2DSampler", null);
  32107. }
  32108. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32109. this._activeEffect.setTexture("refraction2DSampler", null);
  32110. }
  32111. }
  32112. _super.prototype.unbind.call(this);
  32113. };
  32114. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32115. var scene = this.getScene();
  32116. var defines = subMesh._materialDefines;
  32117. if (!defines) {
  32118. return;
  32119. }
  32120. var effect = subMesh.effect;
  32121. this._activeEffect = effect;
  32122. // Matrices
  32123. this.bindOnlyWorldMatrix(world);
  32124. // Bones
  32125. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  32126. if (this._mustRebind(scene, effect)) {
  32127. effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32128. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  32129. // Fresnel
  32130. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  32131. effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  32132. effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  32133. }
  32134. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  32135. effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  32136. }
  32137. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  32138. effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  32139. effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  32140. }
  32141. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  32142. effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  32143. effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  32144. }
  32145. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  32146. effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  32147. effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  32148. }
  32149. }
  32150. // Textures
  32151. if (scene.texturesEnabled) {
  32152. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32153. effect.setTexture("diffuseSampler", this._diffuseTexture);
  32154. effect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  32155. effect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  32156. }
  32157. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32158. effect.setTexture("ambientSampler", this._ambientTexture);
  32159. effect.setFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  32160. effect.setMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  32161. }
  32162. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32163. effect.setTexture("opacitySampler", this._opacityTexture);
  32164. effect.setFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32165. effect.setMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  32166. }
  32167. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32168. if (this._reflectionTexture.isCube) {
  32169. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  32170. }
  32171. else {
  32172. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  32173. }
  32174. effect.setMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  32175. effect.setFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  32176. }
  32177. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32178. effect.setTexture("emissiveSampler", this._emissiveTexture);
  32179. effect.setFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32180. effect.setMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  32181. }
  32182. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32183. effect.setTexture("lightmapSampler", this._lightmapTexture);
  32184. effect.setFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32185. effect.setMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  32186. }
  32187. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32188. effect.setTexture("specularSampler", this._specularTexture);
  32189. effect.setFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  32190. effect.setMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  32191. }
  32192. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  32193. effect.setTexture("bumpSampler", this._bumpTexture);
  32194. effect.setFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  32195. effect.setMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  32196. }
  32197. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32198. var depth = 1.0;
  32199. if (this._refractionTexture.isCube) {
  32200. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  32201. }
  32202. else {
  32203. effect.setTexture("refraction2DSampler", this._refractionTexture);
  32204. effect.setMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  32205. if (this._refractionTexture.depth) {
  32206. depth = this._refractionTexture.depth;
  32207. }
  32208. }
  32209. effect.setFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  32210. }
  32211. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  32212. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  32213. }
  32214. }
  32215. // Clip plane
  32216. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  32217. // Point size
  32218. if (this.pointsCloud) {
  32219. effect.setFloat("pointSize", this.pointSize);
  32220. }
  32221. // Colors
  32222. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  32223. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  32224. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32225. if (defines.SPECULARTERM) {
  32226. effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  32227. }
  32228. effect.setColor3("vEmissiveColor", this.emissiveColor);
  32229. }
  32230. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  32231. // Diffuse
  32232. effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  32233. // Lights
  32234. if (scene.lightsEnabled && !this.disableLighting) {
  32235. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  32236. }
  32237. // View
  32238. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  32239. effect.setMatrix("view", scene.getViewMatrix());
  32240. }
  32241. // Fog
  32242. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  32243. // Morph targets
  32244. if (defines.NUM_MORPH_INFLUENCERS) {
  32245. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  32246. }
  32247. // Log. depth
  32248. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  32249. // Color Curves
  32250. if (this.cameraColorCurves) {
  32251. BABYLON.ColorCurves.Bind(this.cameraColorCurves, effect);
  32252. }
  32253. }
  32254. this._afterBind(mesh, this._activeEffect);
  32255. };
  32256. StandardMaterial.prototype.getAnimatables = function () {
  32257. var results = [];
  32258. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  32259. results.push(this._diffuseTexture);
  32260. }
  32261. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32262. results.push(this._ambientTexture);
  32263. }
  32264. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32265. results.push(this._opacityTexture);
  32266. }
  32267. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32268. results.push(this._reflectionTexture);
  32269. }
  32270. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32271. results.push(this._emissiveTexture);
  32272. }
  32273. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  32274. results.push(this._specularTexture);
  32275. }
  32276. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32277. results.push(this._bumpTexture);
  32278. }
  32279. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32280. results.push(this._lightmapTexture);
  32281. }
  32282. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32283. results.push(this._refractionTexture);
  32284. }
  32285. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  32286. results.push(this._cameraColorGradingTexture);
  32287. }
  32288. return results;
  32289. };
  32290. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32291. if (forceDisposeTextures) {
  32292. if (this._diffuseTexture) {
  32293. this._diffuseTexture.dispose();
  32294. }
  32295. if (this._ambientTexture) {
  32296. this._ambientTexture.dispose();
  32297. }
  32298. if (this._opacityTexture) {
  32299. this._opacityTexture.dispose();
  32300. }
  32301. if (this._reflectionTexture) {
  32302. this._reflectionTexture.dispose();
  32303. }
  32304. if (this._emissiveTexture) {
  32305. this._emissiveTexture.dispose();
  32306. }
  32307. if (this._specularTexture) {
  32308. this._specularTexture.dispose();
  32309. }
  32310. if (this._bumpTexture) {
  32311. this._bumpTexture.dispose();
  32312. }
  32313. if (this._lightmapTexture) {
  32314. this._lightmapTexture.dispose();
  32315. }
  32316. if (this._refractionTexture) {
  32317. this._refractionTexture.dispose();
  32318. }
  32319. if (this._cameraColorGradingTexture) {
  32320. this._cameraColorGradingTexture.dispose();
  32321. }
  32322. }
  32323. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32324. };
  32325. StandardMaterial.prototype.clone = function (name) {
  32326. var _this = this;
  32327. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  32328. result.name = name;
  32329. result.id = name;
  32330. return result;
  32331. };
  32332. StandardMaterial.prototype.serialize = function () {
  32333. return BABYLON.SerializationHelper.Serialize(this);
  32334. };
  32335. // Statics
  32336. StandardMaterial.Parse = function (source, scene, rootUrl) {
  32337. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  32338. };
  32339. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  32340. get: function () {
  32341. return StandardMaterial._DiffuseTextureEnabled;
  32342. },
  32343. set: function (value) {
  32344. if (StandardMaterial._DiffuseTextureEnabled === value) {
  32345. return;
  32346. }
  32347. StandardMaterial._DiffuseTextureEnabled = value;
  32348. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32349. },
  32350. enumerable: true,
  32351. configurable: true
  32352. });
  32353. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  32354. get: function () {
  32355. return StandardMaterial._AmbientTextureEnabled;
  32356. },
  32357. set: function (value) {
  32358. if (StandardMaterial._AmbientTextureEnabled === value) {
  32359. return;
  32360. }
  32361. StandardMaterial._AmbientTextureEnabled = value;
  32362. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32363. },
  32364. enumerable: true,
  32365. configurable: true
  32366. });
  32367. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  32368. get: function () {
  32369. return StandardMaterial._OpacityTextureEnabled;
  32370. },
  32371. set: function (value) {
  32372. if (StandardMaterial._OpacityTextureEnabled === value) {
  32373. return;
  32374. }
  32375. StandardMaterial._OpacityTextureEnabled = value;
  32376. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32377. },
  32378. enumerable: true,
  32379. configurable: true
  32380. });
  32381. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  32382. get: function () {
  32383. return StandardMaterial._ReflectionTextureEnabled;
  32384. },
  32385. set: function (value) {
  32386. if (StandardMaterial._ReflectionTextureEnabled === value) {
  32387. return;
  32388. }
  32389. StandardMaterial._ReflectionTextureEnabled = value;
  32390. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32391. },
  32392. enumerable: true,
  32393. configurable: true
  32394. });
  32395. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  32396. get: function () {
  32397. return StandardMaterial._EmissiveTextureEnabled;
  32398. },
  32399. set: function (value) {
  32400. if (StandardMaterial._EmissiveTextureEnabled === value) {
  32401. return;
  32402. }
  32403. StandardMaterial._EmissiveTextureEnabled = value;
  32404. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32405. },
  32406. enumerable: true,
  32407. configurable: true
  32408. });
  32409. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  32410. get: function () {
  32411. return StandardMaterial._SpecularTextureEnabled;
  32412. },
  32413. set: function (value) {
  32414. if (StandardMaterial._SpecularTextureEnabled === value) {
  32415. return;
  32416. }
  32417. StandardMaterial._SpecularTextureEnabled = value;
  32418. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32419. },
  32420. enumerable: true,
  32421. configurable: true
  32422. });
  32423. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  32424. get: function () {
  32425. return StandardMaterial._BumpTextureEnabled;
  32426. },
  32427. set: function (value) {
  32428. if (StandardMaterial._BumpTextureEnabled === value) {
  32429. return;
  32430. }
  32431. StandardMaterial._BumpTextureEnabled = value;
  32432. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32433. },
  32434. enumerable: true,
  32435. configurable: true
  32436. });
  32437. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  32438. get: function () {
  32439. return StandardMaterial._LightmapTextureEnabled;
  32440. },
  32441. set: function (value) {
  32442. if (StandardMaterial._LightmapTextureEnabled === value) {
  32443. return;
  32444. }
  32445. StandardMaterial._LightmapTextureEnabled = value;
  32446. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32447. },
  32448. enumerable: true,
  32449. configurable: true
  32450. });
  32451. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  32452. get: function () {
  32453. return StandardMaterial._RefractionTextureEnabled;
  32454. },
  32455. set: function (value) {
  32456. if (StandardMaterial._RefractionTextureEnabled === value) {
  32457. return;
  32458. }
  32459. StandardMaterial._RefractionTextureEnabled = value;
  32460. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32461. },
  32462. enumerable: true,
  32463. configurable: true
  32464. });
  32465. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  32466. get: function () {
  32467. return StandardMaterial._ColorGradingTextureEnabled;
  32468. },
  32469. set: function (value) {
  32470. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  32471. return;
  32472. }
  32473. StandardMaterial._ColorGradingTextureEnabled = value;
  32474. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  32475. },
  32476. enumerable: true,
  32477. configurable: true
  32478. });
  32479. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  32480. get: function () {
  32481. return StandardMaterial._FresnelEnabled;
  32482. },
  32483. set: function (value) {
  32484. if (StandardMaterial._FresnelEnabled === value) {
  32485. return;
  32486. }
  32487. StandardMaterial._FresnelEnabled = value;
  32488. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  32489. },
  32490. enumerable: true,
  32491. configurable: true
  32492. });
  32493. return StandardMaterial;
  32494. }(BABYLON.PushMaterial));
  32495. // Flags used to enable or disable a type of texture for all Standard Materials
  32496. StandardMaterial._DiffuseTextureEnabled = true;
  32497. StandardMaterial._AmbientTextureEnabled = true;
  32498. StandardMaterial._OpacityTextureEnabled = true;
  32499. StandardMaterial._ReflectionTextureEnabled = true;
  32500. StandardMaterial._EmissiveTextureEnabled = true;
  32501. StandardMaterial._SpecularTextureEnabled = true;
  32502. StandardMaterial._BumpTextureEnabled = true;
  32503. StandardMaterial._LightmapTextureEnabled = true;
  32504. StandardMaterial._RefractionTextureEnabled = true;
  32505. StandardMaterial._ColorGradingTextureEnabled = true;
  32506. StandardMaterial._FresnelEnabled = true;
  32507. __decorate([
  32508. BABYLON.serializeAsTexture("diffuseTexture")
  32509. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  32510. __decorate([
  32511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32512. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  32513. __decorate([
  32514. BABYLON.serializeAsTexture("ambientTexture")
  32515. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  32516. __decorate([
  32517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32518. ], StandardMaterial.prototype, "ambientTexture", void 0);
  32519. __decorate([
  32520. BABYLON.serializeAsTexture("opacityTexture")
  32521. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  32522. __decorate([
  32523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32524. ], StandardMaterial.prototype, "opacityTexture", void 0);
  32525. __decorate([
  32526. BABYLON.serializeAsTexture("reflectionTexture")
  32527. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  32528. __decorate([
  32529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32530. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  32531. __decorate([
  32532. BABYLON.serializeAsTexture("emissiveTexture")
  32533. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  32534. __decorate([
  32535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32536. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  32537. __decorate([
  32538. BABYLON.serializeAsTexture("specularTexture")
  32539. ], StandardMaterial.prototype, "_specularTexture", void 0);
  32540. __decorate([
  32541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32542. ], StandardMaterial.prototype, "specularTexture", void 0);
  32543. __decorate([
  32544. BABYLON.serializeAsTexture("bumpTexture")
  32545. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  32546. __decorate([
  32547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32548. ], StandardMaterial.prototype, "bumpTexture", void 0);
  32549. __decorate([
  32550. BABYLON.serializeAsTexture("lightmapTexture")
  32551. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  32552. __decorate([
  32553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32554. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  32555. __decorate([
  32556. BABYLON.serializeAsTexture("refractionTexture")
  32557. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  32558. __decorate([
  32559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32560. ], StandardMaterial.prototype, "refractionTexture", void 0);
  32561. __decorate([
  32562. BABYLON.serializeAsColor3("ambient")
  32563. ], StandardMaterial.prototype, "ambientColor", void 0);
  32564. __decorate([
  32565. BABYLON.serializeAsColor3("diffuse")
  32566. ], StandardMaterial.prototype, "diffuseColor", void 0);
  32567. __decorate([
  32568. BABYLON.serializeAsColor3("specular")
  32569. ], StandardMaterial.prototype, "specularColor", void 0);
  32570. __decorate([
  32571. BABYLON.serializeAsColor3("emissive")
  32572. ], StandardMaterial.prototype, "emissiveColor", void 0);
  32573. __decorate([
  32574. BABYLON.serialize()
  32575. ], StandardMaterial.prototype, "specularPower", void 0);
  32576. __decorate([
  32577. BABYLON.serialize("useAlphaFromDiffuseTexture")
  32578. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  32579. __decorate([
  32580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32581. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  32582. __decorate([
  32583. BABYLON.serialize("useEmissiveAsIllumination")
  32584. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  32585. __decorate([
  32586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32587. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  32588. __decorate([
  32589. BABYLON.serialize("linkEmissiveWithDiffuse")
  32590. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  32591. __decorate([
  32592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32593. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  32594. __decorate([
  32595. BABYLON.serialize("useSpecularOverAlpha")
  32596. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  32597. __decorate([
  32598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32599. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  32600. __decorate([
  32601. BABYLON.serialize("useReflectionOverAlpha")
  32602. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  32603. __decorate([
  32604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32605. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  32606. __decorate([
  32607. BABYLON.serialize("disableLighting")
  32608. ], StandardMaterial.prototype, "_disableLighting", void 0);
  32609. __decorate([
  32610. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32611. ], StandardMaterial.prototype, "disableLighting", void 0);
  32612. __decorate([
  32613. BABYLON.serialize("useParallax")
  32614. ], StandardMaterial.prototype, "_useParallax", void 0);
  32615. __decorate([
  32616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32617. ], StandardMaterial.prototype, "useParallax", void 0);
  32618. __decorate([
  32619. BABYLON.serialize("useParallaxOcclusion")
  32620. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  32621. __decorate([
  32622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32623. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  32624. __decorate([
  32625. BABYLON.serialize()
  32626. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  32627. __decorate([
  32628. BABYLON.serialize("roughness")
  32629. ], StandardMaterial.prototype, "_roughness", void 0);
  32630. __decorate([
  32631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32632. ], StandardMaterial.prototype, "roughness", void 0);
  32633. __decorate([
  32634. BABYLON.serialize()
  32635. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  32636. __decorate([
  32637. BABYLON.serialize()
  32638. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  32639. __decorate([
  32640. BABYLON.serialize("useLightmapAsShadowmap")
  32641. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  32642. __decorate([
  32643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32644. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  32645. __decorate([
  32646. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  32647. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  32648. __decorate([
  32649. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32650. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  32651. __decorate([
  32652. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  32653. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  32654. __decorate([
  32655. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32656. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  32657. __decorate([
  32658. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  32659. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  32660. __decorate([
  32661. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32662. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  32663. __decorate([
  32664. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  32665. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  32666. __decorate([
  32667. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32668. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  32669. __decorate([
  32670. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  32671. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  32672. __decorate([
  32673. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32674. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  32675. __decorate([
  32676. BABYLON.serialize("useReflectionFresnelFromSpecular")
  32677. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  32678. __decorate([
  32679. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  32680. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  32681. __decorate([
  32682. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  32683. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  32684. __decorate([
  32685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32686. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  32687. __decorate([
  32688. BABYLON.serialize("maxSimultaneousLights")
  32689. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  32690. __decorate([
  32691. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32692. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  32693. __decorate([
  32694. BABYLON.serialize("invertNormalMapX")
  32695. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  32696. __decorate([
  32697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32698. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  32699. __decorate([
  32700. BABYLON.serialize("invertNormalMapY")
  32701. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  32702. __decorate([
  32703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32704. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  32705. __decorate([
  32706. BABYLON.serialize("twoSidedLighting")
  32707. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  32708. __decorate([
  32709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32710. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  32711. __decorate([
  32712. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  32713. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  32714. __decorate([
  32715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32716. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  32717. __decorate([
  32718. BABYLON.serializeAsColorCurves("cameraColorCurves")
  32719. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  32720. __decorate([
  32721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32722. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  32723. __decorate([
  32724. BABYLON.serialize()
  32725. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  32726. BABYLON.StandardMaterial = StandardMaterial;
  32727. })(BABYLON || (BABYLON = {}));
  32728. //# sourceMappingURL=babylon.standardMaterial.js.map
  32729. var BABYLON;
  32730. (function (BABYLON) {
  32731. var MultiMaterial = (function (_super) {
  32732. __extends(MultiMaterial, _super);
  32733. function MultiMaterial(name, scene) {
  32734. var _this = _super.call(this, name, scene, true) || this;
  32735. _this.subMaterials = new Array();
  32736. scene.multiMaterials.push(_this);
  32737. return _this;
  32738. }
  32739. // Properties
  32740. MultiMaterial.prototype.getSubMaterial = function (index) {
  32741. if (index < 0 || index >= this.subMaterials.length) {
  32742. return this.getScene().defaultMaterial;
  32743. }
  32744. return this.subMaterials[index];
  32745. };
  32746. // Methods
  32747. MultiMaterial.prototype.getClassName = function () {
  32748. return "MultiMaterial";
  32749. };
  32750. MultiMaterial.prototype.isReady = function (mesh) {
  32751. for (var index = 0; index < this.subMaterials.length; index++) {
  32752. var subMaterial = this.subMaterials[index];
  32753. if (subMaterial) {
  32754. if (!this.subMaterials[index].isReady(mesh)) {
  32755. return false;
  32756. }
  32757. }
  32758. }
  32759. return true;
  32760. };
  32761. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  32762. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  32763. for (var index = 0; index < this.subMaterials.length; index++) {
  32764. var subMaterial = null;
  32765. if (cloneChildren) {
  32766. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  32767. }
  32768. else {
  32769. subMaterial = this.subMaterials[index];
  32770. }
  32771. newMultiMaterial.subMaterials.push(subMaterial);
  32772. }
  32773. return newMultiMaterial;
  32774. };
  32775. MultiMaterial.prototype.serialize = function () {
  32776. var serializationObject = {};
  32777. serializationObject.name = this.name;
  32778. serializationObject.id = this.id;
  32779. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32780. serializationObject.materials = [];
  32781. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  32782. var subMat = this.subMaterials[matIndex];
  32783. if (subMat) {
  32784. serializationObject.materials.push(subMat.id);
  32785. }
  32786. else {
  32787. serializationObject.materials.push(null);
  32788. }
  32789. }
  32790. return serializationObject;
  32791. };
  32792. return MultiMaterial;
  32793. }(BABYLON.Material));
  32794. BABYLON.MultiMaterial = MultiMaterial;
  32795. })(BABYLON || (BABYLON = {}));
  32796. //# sourceMappingURL=babylon.multiMaterial.js.map
  32797. var BABYLON;
  32798. (function (BABYLON) {
  32799. var SceneLoader = (function () {
  32800. function SceneLoader() {
  32801. }
  32802. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  32803. get: function () {
  32804. return 0;
  32805. },
  32806. enumerable: true,
  32807. configurable: true
  32808. });
  32809. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  32810. get: function () {
  32811. return 1;
  32812. },
  32813. enumerable: true,
  32814. configurable: true
  32815. });
  32816. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  32817. get: function () {
  32818. return 2;
  32819. },
  32820. enumerable: true,
  32821. configurable: true
  32822. });
  32823. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  32824. get: function () {
  32825. return 3;
  32826. },
  32827. enumerable: true,
  32828. configurable: true
  32829. });
  32830. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  32831. get: function () {
  32832. return SceneLoader._ForceFullSceneLoadingForIncremental;
  32833. },
  32834. set: function (value) {
  32835. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  32841. get: function () {
  32842. return SceneLoader._ShowLoadingScreen;
  32843. },
  32844. set: function (value) {
  32845. SceneLoader._ShowLoadingScreen = value;
  32846. },
  32847. enumerable: true,
  32848. configurable: true
  32849. });
  32850. Object.defineProperty(SceneLoader, "loggingLevel", {
  32851. get: function () {
  32852. return SceneLoader._loggingLevel;
  32853. },
  32854. set: function (value) {
  32855. SceneLoader._loggingLevel = value;
  32856. },
  32857. enumerable: true,
  32858. configurable: true
  32859. });
  32860. SceneLoader._getDefaultPlugin = function () {
  32861. return SceneLoader._registeredPlugins[".babylon"];
  32862. };
  32863. SceneLoader._getPluginForExtension = function (extension) {
  32864. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  32865. if (registeredPlugin) {
  32866. return registeredPlugin;
  32867. }
  32868. return SceneLoader._getDefaultPlugin();
  32869. };
  32870. SceneLoader._getPluginForFilename = function (sceneFilename) {
  32871. if (sceneFilename.name) {
  32872. sceneFilename = sceneFilename.name;
  32873. }
  32874. var dotPosition = sceneFilename.lastIndexOf(".");
  32875. var queryStringPosition = sceneFilename.indexOf("?");
  32876. if (queryStringPosition === -1) {
  32877. queryStringPosition = sceneFilename.length;
  32878. }
  32879. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  32880. return SceneLoader._getPluginForExtension(extension);
  32881. };
  32882. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  32883. SceneLoader._getDirectLoad = function (sceneFilename) {
  32884. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  32885. return sceneFilename.substr(5);
  32886. }
  32887. return null;
  32888. };
  32889. // Public functions
  32890. SceneLoader.GetPluginForExtension = function (extension) {
  32891. return SceneLoader._getPluginForExtension(extension).plugin;
  32892. };
  32893. SceneLoader.RegisterPlugin = function (plugin) {
  32894. if (typeof plugin.extensions === "string") {
  32895. var extension = plugin.extensions;
  32896. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  32897. plugin: plugin,
  32898. isBinary: false
  32899. };
  32900. }
  32901. else {
  32902. var extensions = plugin.extensions;
  32903. Object.keys(extensions).forEach(function (extension) {
  32904. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  32905. plugin: plugin,
  32906. isBinary: extensions[extension].isBinary
  32907. };
  32908. });
  32909. }
  32910. };
  32911. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  32912. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32913. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32914. return;
  32915. }
  32916. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  32917. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  32918. return;
  32919. }
  32920. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  32921. var loadingToken = {};
  32922. scene._addPendingData(loadingToken);
  32923. var manifestChecked = function (success) {
  32924. scene.database = database;
  32925. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  32926. var plugin = registeredPlugin.plugin;
  32927. var useArrayBuffer = registeredPlugin.isBinary;
  32928. var importMeshFromData = function (data) {
  32929. var meshes = [];
  32930. var particleSystems = [];
  32931. var skeletons = [];
  32932. if (scene.isDisposed) {
  32933. if (onerror) {
  32934. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  32935. }
  32936. return;
  32937. }
  32938. try {
  32939. if (plugin.importMesh) {
  32940. var syncedPlugin = plugin;
  32941. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  32942. if (onerror) {
  32943. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  32944. }
  32945. scene._removePendingData(loadingToken);
  32946. return;
  32947. }
  32948. if (onsuccess) {
  32949. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  32950. onsuccess(meshes, particleSystems, skeletons);
  32951. scene._removePendingData(loadingToken);
  32952. }
  32953. }
  32954. else {
  32955. var asyncedPlugin = plugin;
  32956. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  32957. if (onsuccess) {
  32958. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  32959. onsuccess(meshes, particleSystems, skeletons);
  32960. scene._removePendingData(loadingToken);
  32961. }
  32962. }, function () {
  32963. if (onerror) {
  32964. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  32965. }
  32966. scene._removePendingData(loadingToken);
  32967. });
  32968. }
  32969. }
  32970. catch (e) {
  32971. if (onerror) {
  32972. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  32973. }
  32974. scene._removePendingData(loadingToken);
  32975. }
  32976. };
  32977. if (directLoad) {
  32978. importMeshFromData(directLoad);
  32979. return;
  32980. }
  32981. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  32982. importMeshFromData(data);
  32983. }, progressCallBack, database, useArrayBuffer, function () {
  32984. if (onerror) {
  32985. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  32986. }
  32987. });
  32988. };
  32989. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  32990. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  32991. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  32992. }
  32993. else {
  32994. // If the scene is a data stream or offline support is not enabled, it's a direct load
  32995. manifestChecked(true);
  32996. }
  32997. };
  32998. /**
  32999. * Load a scene
  33000. * @param rootUrl a string that defines the root url for scene and resources
  33001. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  33002. * @param engine is the instance of BABYLON.Engine to use to create the scene
  33003. */
  33004. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  33005. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  33006. };
  33007. /**
  33008. * Append a scene
  33009. * @param rootUrl a string that defines the root url for scene and resources
  33010. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  33011. * @param scene is the instance of BABYLON.Scene to append to
  33012. */
  33013. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  33014. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  33015. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  33016. return;
  33017. }
  33018. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  33019. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  33020. var plugin = registeredPlugin.plugin;
  33021. var useArrayBuffer = registeredPlugin.isBinary;
  33022. var database;
  33023. var loadingToken = {};
  33024. scene._addPendingData(loadingToken);
  33025. if (SceneLoader.ShowLoadingScreen) {
  33026. scene.getEngine().displayLoadingUI();
  33027. }
  33028. var loadSceneFromData = function (data) {
  33029. scene.database = database;
  33030. if (plugin.load) {
  33031. var syncedPlugin = plugin;
  33032. if (!syncedPlugin.load(scene, data, rootUrl)) {
  33033. if (onerror) {
  33034. onerror(scene);
  33035. }
  33036. scene._removePendingData(loadingToken);
  33037. scene.getEngine().hideLoadingUI();
  33038. return;
  33039. }
  33040. if (onsuccess) {
  33041. onsuccess(scene);
  33042. }
  33043. scene._removePendingData(loadingToken);
  33044. }
  33045. else {
  33046. var asyncedPlugin = plugin;
  33047. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  33048. if (onsuccess) {
  33049. onsuccess(scene);
  33050. }
  33051. scene._removePendingData(loadingToken);
  33052. }, function () {
  33053. if (onerror) {
  33054. onerror(scene);
  33055. }
  33056. scene._removePendingData(loadingToken);
  33057. scene.getEngine().hideLoadingUI();
  33058. });
  33059. }
  33060. if (SceneLoader.ShowLoadingScreen) {
  33061. scene.executeWhenReady(function () {
  33062. scene.getEngine().hideLoadingUI();
  33063. });
  33064. }
  33065. };
  33066. var manifestChecked = function (success) {
  33067. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  33068. };
  33069. if (directLoad) {
  33070. loadSceneFromData(directLoad);
  33071. return;
  33072. }
  33073. if (rootUrl.indexOf("file:") === -1) {
  33074. if (scene.getEngine().enableOfflineSupport) {
  33075. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  33076. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  33077. }
  33078. else {
  33079. manifestChecked(true);
  33080. }
  33081. }
  33082. else {
  33083. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  33084. }
  33085. };
  33086. return SceneLoader;
  33087. }());
  33088. // Flags
  33089. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  33090. SceneLoader._ShowLoadingScreen = true;
  33091. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  33092. // Members
  33093. SceneLoader._registeredPlugins = {};
  33094. BABYLON.SceneLoader = SceneLoader;
  33095. ;
  33096. })(BABYLON || (BABYLON = {}));
  33097. //# sourceMappingURL=babylon.sceneLoader.js.map
  33098. var BABYLON;
  33099. (function (BABYLON) {
  33100. var Internals;
  33101. (function (Internals) {
  33102. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  33103. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  33104. var parsedMaterial = parsedData.materials[index];
  33105. if (parsedMaterial.id === id) {
  33106. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  33107. }
  33108. }
  33109. return null;
  33110. };
  33111. var isDescendantOf = function (mesh, names, hierarchyIds) {
  33112. names = (names instanceof Array) ? names : [names];
  33113. for (var i in names) {
  33114. if (mesh.name === names[i]) {
  33115. hierarchyIds.push(mesh.id);
  33116. return true;
  33117. }
  33118. }
  33119. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  33120. hierarchyIds.push(mesh.id);
  33121. return true;
  33122. }
  33123. return false;
  33124. };
  33125. var logOperation = function (operation, producer) {
  33126. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  33127. };
  33128. BABYLON.SceneLoader.RegisterPlugin({
  33129. extensions: ".babylon",
  33130. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  33131. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  33132. // when SceneLoader.debugLogging = true (default), or exception encountered.
  33133. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  33134. // and avoid problems with multiple concurrent .babylon loads.
  33135. var log = "importMesh has failed JSON parse";
  33136. try {
  33137. var parsedData = JSON.parse(data);
  33138. log = "";
  33139. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  33140. var loadedSkeletonsIds = [];
  33141. var loadedMaterialsIds = [];
  33142. var hierarchyIds = [];
  33143. var index;
  33144. var cache;
  33145. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  33146. var parsedMesh = parsedData.meshes[index];
  33147. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  33148. if (meshesNames instanceof Array) {
  33149. // Remove found mesh name from list.
  33150. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  33151. }
  33152. //Geometry?
  33153. if (parsedMesh.geometryId) {
  33154. //does the file contain geometries?
  33155. if (parsedData.geometries) {
  33156. //find the correct geometry and add it to the scene
  33157. var found = false;
  33158. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  33159. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  33160. return;
  33161. }
  33162. else {
  33163. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  33164. if (parsedGeometryData.id === parsedMesh.geometryId) {
  33165. switch (geometryType) {
  33166. case "boxes":
  33167. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  33168. break;
  33169. case "spheres":
  33170. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  33171. break;
  33172. case "cylinders":
  33173. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  33174. break;
  33175. case "toruses":
  33176. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  33177. break;
  33178. case "grounds":
  33179. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  33180. break;
  33181. case "planes":
  33182. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  33183. break;
  33184. case "torusKnots":
  33185. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  33186. break;
  33187. case "vertexData":
  33188. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  33189. break;
  33190. }
  33191. found = true;
  33192. }
  33193. });
  33194. }
  33195. });
  33196. if (!found) {
  33197. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  33198. }
  33199. }
  33200. }
  33201. // Material ?
  33202. if (parsedMesh.materialId) {
  33203. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  33204. if (!materialFound && parsedData.multiMaterials) {
  33205. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  33206. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  33207. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  33208. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  33209. var subMatId = parsedMultiMaterial.materials[matIndex];
  33210. loadedMaterialsIds.push(subMatId);
  33211. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  33212. log += "\n\tMaterial " + mat.toString(fullDetails);
  33213. }
  33214. loadedMaterialsIds.push(parsedMultiMaterial.id);
  33215. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  33216. materialFound = true;
  33217. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  33218. break;
  33219. }
  33220. }
  33221. }
  33222. if (!materialFound) {
  33223. loadedMaterialsIds.push(parsedMesh.materialId);
  33224. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  33225. if (!mat) {
  33226. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  33227. }
  33228. else {
  33229. log += "\n\tMaterial " + mat.toString(fullDetails);
  33230. }
  33231. }
  33232. }
  33233. // Skeleton ?
  33234. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  33235. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  33236. if (!skeletonAlreadyLoaded) {
  33237. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  33238. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  33239. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  33240. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  33241. skeletons.push(skeleton);
  33242. loadedSkeletonsIds.push(parsedSkeleton.id);
  33243. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  33244. }
  33245. }
  33246. }
  33247. }
  33248. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  33249. meshes.push(mesh);
  33250. log += "\n\tMesh " + mesh.toString(fullDetails);
  33251. }
  33252. }
  33253. // Connecting parents
  33254. var currentMesh;
  33255. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  33256. currentMesh = scene.meshes[index];
  33257. if (currentMesh._waitingParentId) {
  33258. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  33259. currentMesh._waitingParentId = undefined;
  33260. }
  33261. }
  33262. // freeze and compute world matrix application
  33263. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  33264. currentMesh = scene.meshes[index];
  33265. if (currentMesh._waitingFreezeWorldMatrix) {
  33266. currentMesh.freezeWorldMatrix();
  33267. currentMesh._waitingFreezeWorldMatrix = undefined;
  33268. }
  33269. else {
  33270. currentMesh.computeWorldMatrix(true);
  33271. }
  33272. }
  33273. // Particles
  33274. if (parsedData.particleSystems) {
  33275. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  33276. var parsedParticleSystem = parsedData.particleSystems[index];
  33277. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  33278. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  33279. }
  33280. }
  33281. }
  33282. return true;
  33283. }
  33284. catch (err) {
  33285. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  33286. log = null;
  33287. throw err;
  33288. }
  33289. finally {
  33290. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  33291. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  33292. }
  33293. }
  33294. },
  33295. load: function (scene, data, rootUrl) {
  33296. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  33297. // when SceneLoader.debugLogging = true (default), or exception encountered.
  33298. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  33299. // and avoid problems with multiple concurrent .babylon loads.
  33300. var log = "importScene has failed JSON parse";
  33301. try {
  33302. var parsedData = JSON.parse(data);
  33303. log = "";
  33304. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  33305. // Scene
  33306. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  33307. scene.autoClear = parsedData.autoClear;
  33308. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  33309. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  33310. if (parsedData.gravity) {
  33311. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  33312. }
  33313. // Fog
  33314. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  33315. scene.fogMode = parsedData.fogMode;
  33316. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  33317. scene.fogStart = parsedData.fogStart;
  33318. scene.fogEnd = parsedData.fogEnd;
  33319. scene.fogDensity = parsedData.fogDensity;
  33320. log += "\tFog mode for scene: ";
  33321. switch (scene.fogMode) {
  33322. // getters not compiling, so using hardcoded
  33323. case 1:
  33324. log += "exp\n";
  33325. break;
  33326. case 2:
  33327. log += "exp2\n";
  33328. break;
  33329. case 3:
  33330. log += "linear\n";
  33331. break;
  33332. }
  33333. }
  33334. //Physics
  33335. if (parsedData.physicsEnabled) {
  33336. var physicsPlugin;
  33337. if (parsedData.physicsEngine === "cannon") {
  33338. physicsPlugin = new BABYLON.CannonJSPlugin();
  33339. }
  33340. else if (parsedData.physicsEngine === "oimo") {
  33341. physicsPlugin = new BABYLON.OimoJSPlugin();
  33342. }
  33343. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  33344. //else - default engine, which is currently oimo
  33345. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  33346. scene.enablePhysics(physicsGravity, physicsPlugin);
  33347. }
  33348. // Metadata
  33349. if (parsedData.metadata !== undefined) {
  33350. scene.metadata = parsedData.metadata;
  33351. }
  33352. //collisions, if defined. otherwise, default is true
  33353. if (parsedData.collisionsEnabled != undefined) {
  33354. scene.collisionsEnabled = parsedData.collisionsEnabled;
  33355. }
  33356. scene.workerCollisions = !!parsedData.workerCollisions;
  33357. var index;
  33358. var cache;
  33359. // Lights
  33360. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  33361. var parsedLight = parsedData.lights[index];
  33362. var light = BABYLON.Light.Parse(parsedLight, scene);
  33363. log += (index === 0 ? "\n\tLights:" : "");
  33364. log += "\n\t\t" + light.toString(fullDetails);
  33365. }
  33366. // Animations
  33367. if (parsedData.animations) {
  33368. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  33369. var parsedAnimation = parsedData.animations[index];
  33370. var animation = BABYLON.Animation.Parse(parsedAnimation);
  33371. scene.animations.push(animation);
  33372. log += (index === 0 ? "\n\tAnimations:" : "");
  33373. log += "\n\t\t" + animation.toString(fullDetails);
  33374. }
  33375. }
  33376. if (parsedData.autoAnimate) {
  33377. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  33378. }
  33379. // Materials
  33380. if (parsedData.materials) {
  33381. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  33382. var parsedMaterial = parsedData.materials[index];
  33383. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  33384. log += (index === 0 ? "\n\tMaterials:" : "");
  33385. log += "\n\t\t" + mat.toString(fullDetails);
  33386. }
  33387. }
  33388. if (parsedData.multiMaterials) {
  33389. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  33390. var parsedMultiMaterial = parsedData.multiMaterials[index];
  33391. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  33392. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  33393. log += "\n\t\t" + mmat.toString(fullDetails);
  33394. }
  33395. }
  33396. // Morph targets
  33397. if (parsedData.morphTargetManagers) {
  33398. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  33399. var managerData = _a[_i];
  33400. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  33401. }
  33402. }
  33403. // Skeletons
  33404. if (parsedData.skeletons) {
  33405. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  33406. var parsedSkeleton = parsedData.skeletons[index];
  33407. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  33408. log += (index === 0 ? "\n\tSkeletons:" : "");
  33409. log += "\n\t\t" + skeleton.toString(fullDetails);
  33410. }
  33411. }
  33412. // Geometries
  33413. var geometries = parsedData.geometries;
  33414. if (geometries) {
  33415. // Boxes
  33416. var boxes = geometries.boxes;
  33417. if (boxes) {
  33418. for (index = 0, cache = boxes.length; index < cache; index++) {
  33419. var parsedBox = boxes[index];
  33420. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  33421. }
  33422. }
  33423. // Spheres
  33424. var spheres = geometries.spheres;
  33425. if (spheres) {
  33426. for (index = 0, cache = spheres.length; index < cache; index++) {
  33427. var parsedSphere = spheres[index];
  33428. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  33429. }
  33430. }
  33431. // Cylinders
  33432. var cylinders = geometries.cylinders;
  33433. if (cylinders) {
  33434. for (index = 0, cache = cylinders.length; index < cache; index++) {
  33435. var parsedCylinder = cylinders[index];
  33436. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  33437. }
  33438. }
  33439. // Toruses
  33440. var toruses = geometries.toruses;
  33441. if (toruses) {
  33442. for (index = 0, cache = toruses.length; index < cache; index++) {
  33443. var parsedTorus = toruses[index];
  33444. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  33445. }
  33446. }
  33447. // Grounds
  33448. var grounds = geometries.grounds;
  33449. if (grounds) {
  33450. for (index = 0, cache = grounds.length; index < cache; index++) {
  33451. var parsedGround = grounds[index];
  33452. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  33453. }
  33454. }
  33455. // Planes
  33456. var planes = geometries.planes;
  33457. if (planes) {
  33458. for (index = 0, cache = planes.length; index < cache; index++) {
  33459. var parsedPlane = planes[index];
  33460. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  33461. }
  33462. }
  33463. // TorusKnots
  33464. var torusKnots = geometries.torusKnots;
  33465. if (torusKnots) {
  33466. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  33467. var parsedTorusKnot = torusKnots[index];
  33468. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  33469. }
  33470. }
  33471. // VertexData
  33472. var vertexData = geometries.vertexData;
  33473. if (vertexData) {
  33474. for (index = 0, cache = vertexData.length; index < cache; index++) {
  33475. var parsedVertexData = vertexData[index];
  33476. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  33477. }
  33478. }
  33479. }
  33480. // Meshes
  33481. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  33482. var parsedMesh = parsedData.meshes[index];
  33483. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  33484. log += (index === 0 ? "\n\tMeshes:" : "");
  33485. log += "\n\t\t" + mesh.toString(fullDetails);
  33486. }
  33487. // Cameras
  33488. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  33489. var parsedCamera = parsedData.cameras[index];
  33490. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  33491. log += (index === 0 ? "\n\tCameras:" : "");
  33492. log += "\n\t\t" + camera.toString(fullDetails);
  33493. }
  33494. if (parsedData.activeCameraID) {
  33495. scene.setActiveCameraByID(parsedData.activeCameraID);
  33496. }
  33497. // Browsing all the graph to connect the dots
  33498. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  33499. var camera = scene.cameras[index];
  33500. if (camera._waitingParentId) {
  33501. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  33502. camera._waitingParentId = undefined;
  33503. }
  33504. }
  33505. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  33506. var light = scene.lights[index];
  33507. if (light._waitingParentId) {
  33508. light.parent = scene.getLastEntryByID(light._waitingParentId);
  33509. light._waitingParentId = undefined;
  33510. }
  33511. }
  33512. // Sounds
  33513. var loadedSounds = [];
  33514. var loadedSound;
  33515. if (BABYLON.AudioEngine && parsedData.sounds) {
  33516. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  33517. var parsedSound = parsedData.sounds[index];
  33518. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33519. if (!parsedSound.url)
  33520. parsedSound.url = parsedSound.name;
  33521. if (!loadedSounds[parsedSound.url]) {
  33522. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  33523. loadedSounds[parsedSound.url] = loadedSound;
  33524. }
  33525. else {
  33526. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  33527. }
  33528. }
  33529. else {
  33530. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  33531. }
  33532. }
  33533. }
  33534. loadedSounds = [];
  33535. // Connect parents & children and parse actions
  33536. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  33537. var mesh = scene.meshes[index];
  33538. if (mesh._waitingParentId) {
  33539. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  33540. mesh._waitingParentId = undefined;
  33541. }
  33542. if (mesh._waitingActions) {
  33543. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  33544. mesh._waitingActions = undefined;
  33545. }
  33546. }
  33547. // freeze world matrix application
  33548. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  33549. var currentMesh = scene.meshes[index];
  33550. if (currentMesh._waitingFreezeWorldMatrix) {
  33551. currentMesh.freezeWorldMatrix();
  33552. currentMesh._waitingFreezeWorldMatrix = undefined;
  33553. }
  33554. else {
  33555. currentMesh.computeWorldMatrix(true);
  33556. }
  33557. }
  33558. // Particles Systems
  33559. if (parsedData.particleSystems) {
  33560. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  33561. var parsedParticleSystem = parsedData.particleSystems[index];
  33562. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  33563. }
  33564. }
  33565. // Lens flares
  33566. if (parsedData.lensFlareSystems) {
  33567. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  33568. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  33569. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  33570. }
  33571. }
  33572. // Shadows
  33573. if (parsedData.shadowGenerators) {
  33574. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  33575. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  33576. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  33577. }
  33578. }
  33579. // Lights exclusions / inclusions
  33580. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  33581. var light = scene.lights[index];
  33582. // Excluded check
  33583. if (light._excludedMeshesIds.length > 0) {
  33584. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  33585. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  33586. if (excludedMesh) {
  33587. light.excludedMeshes.push(excludedMesh);
  33588. }
  33589. }
  33590. light._excludedMeshesIds = [];
  33591. }
  33592. // Included check
  33593. if (light._includedOnlyMeshesIds.length > 0) {
  33594. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  33595. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  33596. if (includedOnlyMesh) {
  33597. light.includedOnlyMeshes.push(includedOnlyMesh);
  33598. }
  33599. }
  33600. light._includedOnlyMeshesIds = [];
  33601. }
  33602. }
  33603. // Actions (scene)
  33604. if (parsedData.actions) {
  33605. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  33606. }
  33607. // Finish
  33608. return true;
  33609. }
  33610. catch (err) {
  33611. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  33612. log = null;
  33613. throw err;
  33614. }
  33615. finally {
  33616. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  33617. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  33618. }
  33619. }
  33620. }
  33621. });
  33622. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33623. })(BABYLON || (BABYLON = {}));
  33624. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  33625. var BABYLON;
  33626. (function (BABYLON) {
  33627. var SpriteManager = (function () {
  33628. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  33629. if (epsilon === void 0) { epsilon = 0.01; }
  33630. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33631. this.name = name;
  33632. this.sprites = new Array();
  33633. this.renderingGroupId = 0;
  33634. this.layerMask = 0x0FFFFFFF;
  33635. this.fogEnabled = true;
  33636. this.isPickable = false;
  33637. /**
  33638. * An event triggered when the manager is disposed.
  33639. * @type {BABYLON.Observable}
  33640. */
  33641. this.onDisposeObservable = new BABYLON.Observable();
  33642. this._vertexBuffers = {};
  33643. this._capacity = capacity;
  33644. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  33645. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33646. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33647. if (cellSize.width && cellSize.height) {
  33648. this.cellWidth = cellSize.width;
  33649. this.cellHeight = cellSize.height;
  33650. }
  33651. else if (cellSize !== undefined) {
  33652. this.cellWidth = cellSize;
  33653. this.cellHeight = cellSize;
  33654. }
  33655. else {
  33656. return;
  33657. }
  33658. this._epsilon = epsilon;
  33659. this._scene = scene;
  33660. this._scene.spriteManagers.push(this);
  33661. var indices = [];
  33662. var index = 0;
  33663. for (var count = 0; count < capacity; count++) {
  33664. indices.push(index);
  33665. indices.push(index + 1);
  33666. indices.push(index + 2);
  33667. indices.push(index);
  33668. indices.push(index + 2);
  33669. indices.push(index + 3);
  33670. index += 4;
  33671. }
  33672. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33673. // VBO
  33674. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  33675. this._vertexData = new Float32Array(capacity * 16 * 4);
  33676. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  33677. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  33678. var options = this._buffer.createVertexBuffer("options", 4, 4);
  33679. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  33680. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  33681. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  33682. this._vertexBuffers["options"] = options;
  33683. this._vertexBuffers["cellInfo"] = cellInfo;
  33684. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  33685. // Effects
  33686. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  33687. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  33688. }
  33689. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  33690. set: function (callback) {
  33691. if (this._onDisposeObserver) {
  33692. this.onDisposeObservable.remove(this._onDisposeObserver);
  33693. }
  33694. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  33695. },
  33696. enumerable: true,
  33697. configurable: true
  33698. });
  33699. Object.defineProperty(SpriteManager.prototype, "texture", {
  33700. get: function () {
  33701. return this._spriteTexture;
  33702. },
  33703. set: function (value) {
  33704. this._spriteTexture = value;
  33705. },
  33706. enumerable: true,
  33707. configurable: true
  33708. });
  33709. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  33710. var arrayOffset = index * 16;
  33711. if (offsetX === 0)
  33712. offsetX = this._epsilon;
  33713. else if (offsetX === 1)
  33714. offsetX = 1 - this._epsilon;
  33715. if (offsetY === 0)
  33716. offsetY = this._epsilon;
  33717. else if (offsetY === 1)
  33718. offsetY = 1 - this._epsilon;
  33719. this._vertexData[arrayOffset] = sprite.position.x;
  33720. this._vertexData[arrayOffset + 1] = sprite.position.y;
  33721. this._vertexData[arrayOffset + 2] = sprite.position.z;
  33722. this._vertexData[arrayOffset + 3] = sprite.angle;
  33723. this._vertexData[arrayOffset + 4] = sprite.width;
  33724. this._vertexData[arrayOffset + 5] = sprite.height;
  33725. this._vertexData[arrayOffset + 6] = offsetX;
  33726. this._vertexData[arrayOffset + 7] = offsetY;
  33727. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  33728. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  33729. var offset = (sprite.cellIndex / rowSize) >> 0;
  33730. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  33731. this._vertexData[arrayOffset + 11] = offset;
  33732. // Color
  33733. this._vertexData[arrayOffset + 12] = sprite.color.r;
  33734. this._vertexData[arrayOffset + 13] = sprite.color.g;
  33735. this._vertexData[arrayOffset + 14] = sprite.color.b;
  33736. this._vertexData[arrayOffset + 15] = sprite.color.a;
  33737. };
  33738. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  33739. var count = Math.min(this._capacity, this.sprites.length);
  33740. var min = BABYLON.Vector3.Zero();
  33741. var max = BABYLON.Vector3.Zero();
  33742. var distance = Number.MAX_VALUE;
  33743. var currentSprite;
  33744. var cameraSpacePosition = BABYLON.Vector3.Zero();
  33745. var cameraView = camera.getViewMatrix();
  33746. for (var index = 0; index < count; index++) {
  33747. var sprite = this.sprites[index];
  33748. if (!sprite) {
  33749. continue;
  33750. }
  33751. if (predicate) {
  33752. if (!predicate(sprite)) {
  33753. continue;
  33754. }
  33755. }
  33756. else if (!sprite.isPickable) {
  33757. continue;
  33758. }
  33759. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  33760. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  33761. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  33762. if (ray.intersectsBoxMinMax(min, max)) {
  33763. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  33764. if (distance > currentDistance) {
  33765. distance = currentDistance;
  33766. currentSprite = sprite;
  33767. if (fastCheck) {
  33768. break;
  33769. }
  33770. }
  33771. }
  33772. }
  33773. if (currentSprite) {
  33774. var result = new BABYLON.PickingInfo();
  33775. result.hit = true;
  33776. result.pickedSprite = currentSprite;
  33777. result.distance = distance;
  33778. return result;
  33779. }
  33780. return null;
  33781. };
  33782. SpriteManager.prototype.render = function () {
  33783. // Check
  33784. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  33785. return;
  33786. var engine = this._scene.getEngine();
  33787. var baseSize = this._spriteTexture.getBaseSize();
  33788. // Sprites
  33789. var deltaTime = engine.getDeltaTime();
  33790. var max = Math.min(this._capacity, this.sprites.length);
  33791. var rowSize = baseSize.width / this.cellWidth;
  33792. var offset = 0;
  33793. for (var index = 0; index < max; index++) {
  33794. var sprite = this.sprites[index];
  33795. if (!sprite) {
  33796. continue;
  33797. }
  33798. sprite._animate(deltaTime);
  33799. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  33800. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  33801. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  33802. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  33803. }
  33804. this._buffer.update(this._vertexData);
  33805. // Render
  33806. var effect = this._effectBase;
  33807. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33808. effect = this._effectFog;
  33809. }
  33810. engine.enableEffect(effect);
  33811. var viewMatrix = this._scene.getViewMatrix();
  33812. effect.setTexture("diffuseSampler", this._spriteTexture);
  33813. effect.setMatrix("view", viewMatrix);
  33814. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  33815. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  33816. // Fog
  33817. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  33818. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  33819. effect.setColor3("vFogColor", this._scene.fogColor);
  33820. }
  33821. // VBOs
  33822. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33823. // Draw order
  33824. engine.setDepthFunctionToLessOrEqual();
  33825. effect.setBool("alphaTest", true);
  33826. engine.setColorWrite(false);
  33827. engine.draw(true, 0, max * 6);
  33828. engine.setColorWrite(true);
  33829. effect.setBool("alphaTest", false);
  33830. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33831. engine.draw(true, 0, max * 6);
  33832. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33833. };
  33834. SpriteManager.prototype.dispose = function () {
  33835. if (this._buffer) {
  33836. this._buffer.dispose();
  33837. this._buffer = null;
  33838. }
  33839. if (this._indexBuffer) {
  33840. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33841. this._indexBuffer = null;
  33842. }
  33843. if (this._spriteTexture) {
  33844. this._spriteTexture.dispose();
  33845. this._spriteTexture = null;
  33846. }
  33847. // Remove from scene
  33848. var index = this._scene.spriteManagers.indexOf(this);
  33849. this._scene.spriteManagers.splice(index, 1);
  33850. // Callback
  33851. this.onDisposeObservable.notifyObservers(this);
  33852. this.onDisposeObservable.clear();
  33853. };
  33854. return SpriteManager;
  33855. }());
  33856. BABYLON.SpriteManager = SpriteManager;
  33857. })(BABYLON || (BABYLON = {}));
  33858. //# sourceMappingURL=babylon.spriteManager.js.map
  33859. var BABYLON;
  33860. (function (BABYLON) {
  33861. var Sprite = (function () {
  33862. function Sprite(name, manager) {
  33863. this.name = name;
  33864. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  33865. this.width = 1.0;
  33866. this.height = 1.0;
  33867. this.angle = 0;
  33868. this.cellIndex = 0;
  33869. this.invertU = 0;
  33870. this.invertV = 0;
  33871. this.animations = new Array();
  33872. this.isPickable = false;
  33873. this._animationStarted = false;
  33874. this._loopAnimation = false;
  33875. this._fromIndex = 0;
  33876. this._toIndex = 0;
  33877. this._delay = 0;
  33878. this._direction = 1;
  33879. this._frameCount = 0;
  33880. this._time = 0;
  33881. this._manager = manager;
  33882. this._manager.sprites.push(this);
  33883. this.position = BABYLON.Vector3.Zero();
  33884. }
  33885. Object.defineProperty(Sprite.prototype, "size", {
  33886. get: function () {
  33887. return this.width;
  33888. },
  33889. set: function (value) {
  33890. this.width = value;
  33891. this.height = value;
  33892. },
  33893. enumerable: true,
  33894. configurable: true
  33895. });
  33896. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  33897. this._fromIndex = from;
  33898. this._toIndex = to;
  33899. this._loopAnimation = loop;
  33900. this._delay = delay;
  33901. this._animationStarted = true;
  33902. this._direction = from < to ? 1 : -1;
  33903. this.cellIndex = from;
  33904. this._time = 0;
  33905. this._onAnimationEnd = onAnimationEnd;
  33906. };
  33907. Sprite.prototype.stopAnimation = function () {
  33908. this._animationStarted = false;
  33909. };
  33910. Sprite.prototype._animate = function (deltaTime) {
  33911. if (!this._animationStarted)
  33912. return;
  33913. this._time += deltaTime;
  33914. if (this._time > this._delay) {
  33915. this._time = this._time % this._delay;
  33916. this.cellIndex += this._direction;
  33917. if (this.cellIndex === this._toIndex) {
  33918. if (this._loopAnimation) {
  33919. this.cellIndex = this._fromIndex;
  33920. }
  33921. else {
  33922. this._animationStarted = false;
  33923. if (this._onAnimationEnd) {
  33924. this._onAnimationEnd();
  33925. }
  33926. if (this.disposeWhenFinishedAnimating) {
  33927. this.dispose();
  33928. }
  33929. }
  33930. }
  33931. }
  33932. };
  33933. Sprite.prototype.dispose = function () {
  33934. for (var i = 0; i < this._manager.sprites.length; i++) {
  33935. if (this._manager.sprites[i] == this) {
  33936. this._manager.sprites.splice(i, 1);
  33937. }
  33938. }
  33939. };
  33940. return Sprite;
  33941. }());
  33942. BABYLON.Sprite = Sprite;
  33943. })(BABYLON || (BABYLON = {}));
  33944. //# sourceMappingURL=babylon.sprite.js.map
  33945. var BABYLON;
  33946. (function (BABYLON) {
  33947. var Layer = (function () {
  33948. function Layer(name, imgUrl, scene, isBackground, color) {
  33949. this.name = name;
  33950. this.scale = new BABYLON.Vector2(1, 1);
  33951. this.offset = new BABYLON.Vector2(0, 0);
  33952. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  33953. this._vertexBuffers = {};
  33954. // Events
  33955. /**
  33956. * An event triggered when the layer is disposed.
  33957. * @type {BABYLON.Observable}
  33958. */
  33959. this.onDisposeObservable = new BABYLON.Observable();
  33960. /**
  33961. * An event triggered before rendering the scene
  33962. * @type {BABYLON.Observable}
  33963. */
  33964. this.onBeforeRenderObservable = new BABYLON.Observable();
  33965. /**
  33966. * An event triggered after rendering the scene
  33967. * @type {BABYLON.Observable}
  33968. */
  33969. this.onAfterRenderObservable = new BABYLON.Observable();
  33970. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  33971. this.isBackground = isBackground === undefined ? true : isBackground;
  33972. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  33973. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33974. this._scene.layers.push(this);
  33975. var engine = scene.getEngine();
  33976. // VBO
  33977. var vertices = [];
  33978. vertices.push(1, 1);
  33979. vertices.push(-1, 1);
  33980. vertices.push(-1, -1);
  33981. vertices.push(1, -1);
  33982. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  33984. // Indices
  33985. var indices = [];
  33986. indices.push(0);
  33987. indices.push(1);
  33988. indices.push(2);
  33989. indices.push(0);
  33990. indices.push(2);
  33991. indices.push(3);
  33992. this._indexBuffer = engine.createIndexBuffer(indices);
  33993. // Effects
  33994. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  33995. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  33996. }
  33997. Object.defineProperty(Layer.prototype, "onDispose", {
  33998. set: function (callback) {
  33999. if (this._onDisposeObserver) {
  34000. this.onDisposeObservable.remove(this._onDisposeObserver);
  34001. }
  34002. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34003. },
  34004. enumerable: true,
  34005. configurable: true
  34006. });
  34007. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  34008. set: function (callback) {
  34009. if (this._onBeforeRenderObserver) {
  34010. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34011. }
  34012. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34013. },
  34014. enumerable: true,
  34015. configurable: true
  34016. });
  34017. Object.defineProperty(Layer.prototype, "onAfterRender", {
  34018. set: function (callback) {
  34019. if (this._onAfterRenderObserver) {
  34020. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34021. }
  34022. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34023. },
  34024. enumerable: true,
  34025. configurable: true
  34026. });
  34027. Layer.prototype.render = function () {
  34028. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  34029. // Check
  34030. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  34031. return;
  34032. var engine = this._scene.getEngine();
  34033. this.onBeforeRenderObservable.notifyObservers(this);
  34034. // Render
  34035. engine.enableEffect(currentEffect);
  34036. engine.setState(false);
  34037. // Texture
  34038. currentEffect.setTexture("textureSampler", this.texture);
  34039. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  34040. // Color
  34041. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  34042. // Scale / offset
  34043. currentEffect.setVector2("offset", this.offset);
  34044. currentEffect.setVector2("scale", this.scale);
  34045. // VBOs
  34046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  34047. // Draw order
  34048. if (!this.alphaTest) {
  34049. engine.setAlphaMode(this.alphaBlendingMode);
  34050. engine.draw(true, 0, 6);
  34051. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34052. }
  34053. else {
  34054. engine.draw(true, 0, 6);
  34055. }
  34056. this.onAfterRenderObservable.notifyObservers(this);
  34057. };
  34058. Layer.prototype.dispose = function () {
  34059. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34060. if (vertexBuffer) {
  34061. vertexBuffer.dispose();
  34062. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34063. }
  34064. if (this._indexBuffer) {
  34065. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34066. this._indexBuffer = null;
  34067. }
  34068. if (this.texture) {
  34069. this.texture.dispose();
  34070. this.texture = null;
  34071. }
  34072. // Remove from scene
  34073. var index = this._scene.layers.indexOf(this);
  34074. this._scene.layers.splice(index, 1);
  34075. // Callback
  34076. this.onDisposeObservable.notifyObservers(this);
  34077. this.onDisposeObservable.clear();
  34078. this.onAfterRenderObservable.clear();
  34079. this.onBeforeRenderObservable.clear();
  34080. };
  34081. return Layer;
  34082. }());
  34083. BABYLON.Layer = Layer;
  34084. })(BABYLON || (BABYLON = {}));
  34085. //# sourceMappingURL=babylon.layer.js.map
  34086. var BABYLON;
  34087. (function (BABYLON) {
  34088. var Particle = (function () {
  34089. function Particle() {
  34090. this.position = BABYLON.Vector3.Zero();
  34091. this.direction = BABYLON.Vector3.Zero();
  34092. this.color = new BABYLON.Color4(0, 0, 0, 0);
  34093. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  34094. this.lifeTime = 1.0;
  34095. this.age = 0;
  34096. this.size = 0;
  34097. this.angle = 0;
  34098. this.angularSpeed = 0;
  34099. }
  34100. Particle.prototype.copyTo = function (other) {
  34101. other.position.copyFrom(this.position);
  34102. other.direction.copyFrom(this.direction);
  34103. other.color.copyFrom(this.color);
  34104. other.colorStep.copyFrom(this.colorStep);
  34105. other.lifeTime = this.lifeTime;
  34106. other.age = this.age;
  34107. other.size = this.size;
  34108. other.angle = this.angle;
  34109. other.angularSpeed = this.angularSpeed;
  34110. };
  34111. return Particle;
  34112. }());
  34113. BABYLON.Particle = Particle;
  34114. })(BABYLON || (BABYLON = {}));
  34115. //# sourceMappingURL=babylon.particle.js.map
  34116. var BABYLON;
  34117. (function (BABYLON) {
  34118. var randomNumber = function (min, max) {
  34119. if (min === max) {
  34120. return (min);
  34121. }
  34122. var random = Math.random();
  34123. return ((random * (max - min)) + min);
  34124. };
  34125. var ParticleSystem = (function () {
  34126. function ParticleSystem(name, capacity, scene, customEffect) {
  34127. var _this = this;
  34128. this.name = name;
  34129. // Members
  34130. this.animations = [];
  34131. this.renderingGroupId = 0;
  34132. this.emitter = null;
  34133. this.emitRate = 10;
  34134. this.manualEmitCount = -1;
  34135. this.updateSpeed = 0.01;
  34136. this.targetStopDuration = 0;
  34137. this.disposeOnStop = false;
  34138. this.minEmitPower = 1;
  34139. this.maxEmitPower = 1;
  34140. this.minLifeTime = 1;
  34141. this.maxLifeTime = 1;
  34142. this.minSize = 1;
  34143. this.maxSize = 1;
  34144. this.minAngularSpeed = 0;
  34145. this.maxAngularSpeed = 0;
  34146. this.layerMask = 0x0FFFFFFF;
  34147. this.customShader = null;
  34148. this.preventAutoStart = false;
  34149. /**
  34150. * An event triggered when the system is disposed.
  34151. * @type {BABYLON.Observable}
  34152. */
  34153. this.onDisposeObservable = new BABYLON.Observable();
  34154. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  34155. this.forceDepthWrite = false;
  34156. this.gravity = BABYLON.Vector3.Zero();
  34157. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  34158. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  34159. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  34160. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  34161. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34162. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34163. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  34164. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34165. this.particles = new Array();
  34166. this._stockParticles = new Array();
  34167. this._newPartsExcess = 0;
  34168. this._vertexBuffers = {};
  34169. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  34170. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  34171. this._scaledDirection = BABYLON.Vector3.Zero();
  34172. this._scaledGravity = BABYLON.Vector3.Zero();
  34173. this._currentRenderId = -1;
  34174. this._started = false;
  34175. this._stopped = false;
  34176. this._actualFrame = 0;
  34177. this.id = name;
  34178. this._capacity = capacity;
  34179. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34180. this._customEffect = customEffect;
  34181. scene.particleSystems.push(this);
  34182. var indices = [];
  34183. var index = 0;
  34184. for (var count = 0; count < capacity; count++) {
  34185. indices.push(index);
  34186. indices.push(index + 1);
  34187. indices.push(index + 2);
  34188. indices.push(index);
  34189. indices.push(index + 2);
  34190. indices.push(index + 3);
  34191. index += 4;
  34192. }
  34193. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34194. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  34195. this._vertexData = new Float32Array(capacity * 11 * 4);
  34196. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  34197. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  34198. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  34199. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  34200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  34201. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  34202. this._vertexBuffers["options"] = options;
  34203. // Default behaviors
  34204. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  34205. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  34206. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  34207. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  34208. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  34209. };
  34210. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  34211. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  34212. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  34213. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  34214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  34215. };
  34216. this.updateFunction = function (particles) {
  34217. for (var index = 0; index < particles.length; index++) {
  34218. var particle = particles[index];
  34219. particle.age += _this._scaledUpdateSpeed;
  34220. if (particle.age >= particle.lifeTime) {
  34221. _this.recycleParticle(particle);
  34222. index--;
  34223. continue;
  34224. }
  34225. else {
  34226. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  34227. particle.color.addInPlace(_this._scaledColorStep);
  34228. if (particle.color.a < 0)
  34229. particle.color.a = 0;
  34230. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  34231. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  34232. particle.position.addInPlace(_this._scaledDirection);
  34233. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  34234. particle.direction.addInPlace(_this._scaledGravity);
  34235. }
  34236. }
  34237. };
  34238. }
  34239. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  34240. set: function (callback) {
  34241. if (this._onDisposeObserver) {
  34242. this.onDisposeObservable.remove(this._onDisposeObserver);
  34243. }
  34244. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34245. },
  34246. enumerable: true,
  34247. configurable: true
  34248. });
  34249. ParticleSystem.prototype.recycleParticle = function (particle) {
  34250. var lastParticle = this.particles.pop();
  34251. if (lastParticle !== particle) {
  34252. lastParticle.copyTo(particle);
  34253. this._stockParticles.push(lastParticle);
  34254. }
  34255. };
  34256. ParticleSystem.prototype.getCapacity = function () {
  34257. return this._capacity;
  34258. };
  34259. ParticleSystem.prototype.isAlive = function () {
  34260. return this._alive;
  34261. };
  34262. ParticleSystem.prototype.isStarted = function () {
  34263. return this._started;
  34264. };
  34265. ParticleSystem.prototype.start = function () {
  34266. this._started = true;
  34267. this._stopped = false;
  34268. this._actualFrame = 0;
  34269. };
  34270. ParticleSystem.prototype.stop = function () {
  34271. this._stopped = true;
  34272. };
  34273. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  34274. var offset = index * 11;
  34275. this._vertexData[offset] = particle.position.x;
  34276. this._vertexData[offset + 1] = particle.position.y;
  34277. this._vertexData[offset + 2] = particle.position.z;
  34278. this._vertexData[offset + 3] = particle.color.r;
  34279. this._vertexData[offset + 4] = particle.color.g;
  34280. this._vertexData[offset + 5] = particle.color.b;
  34281. this._vertexData[offset + 6] = particle.color.a;
  34282. this._vertexData[offset + 7] = particle.angle;
  34283. this._vertexData[offset + 8] = particle.size;
  34284. this._vertexData[offset + 9] = offsetX;
  34285. this._vertexData[offset + 10] = offsetY;
  34286. };
  34287. ParticleSystem.prototype._update = function (newParticles) {
  34288. // Update current
  34289. this._alive = this.particles.length > 0;
  34290. this.updateFunction(this.particles);
  34291. // Add new ones
  34292. var worldMatrix;
  34293. if (this.emitter.position) {
  34294. worldMatrix = this.emitter.getWorldMatrix();
  34295. }
  34296. else {
  34297. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  34298. }
  34299. var particle;
  34300. for (var index = 0; index < newParticles; index++) {
  34301. if (this.particles.length === this._capacity) {
  34302. break;
  34303. }
  34304. if (this._stockParticles.length !== 0) {
  34305. particle = this._stockParticles.pop();
  34306. particle.age = 0;
  34307. }
  34308. else {
  34309. particle = new BABYLON.Particle();
  34310. }
  34311. this.particles.push(particle);
  34312. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  34313. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  34314. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  34315. particle.size = randomNumber(this.minSize, this.maxSize);
  34316. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  34317. this.startPositionFunction(worldMatrix, particle.position, particle);
  34318. var step = randomNumber(0, 1.0);
  34319. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  34320. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  34321. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  34322. }
  34323. };
  34324. ParticleSystem.prototype._getEffect = function () {
  34325. if (this._customEffect) {
  34326. return this._customEffect;
  34327. }
  34328. ;
  34329. var defines = [];
  34330. if (this._scene.clipPlane) {
  34331. defines.push("#define CLIPPLANE");
  34332. }
  34333. // Effect
  34334. var join = defines.join("\n");
  34335. if (this._cachedDefines !== join) {
  34336. this._cachedDefines = join;
  34337. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  34338. }
  34339. return this._effect;
  34340. };
  34341. ParticleSystem.prototype.animate = function () {
  34342. if (!this._started)
  34343. return;
  34344. var effect = this._getEffect();
  34345. // Check
  34346. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  34347. return;
  34348. if (this._currentRenderId === this._scene.getRenderId()) {
  34349. return;
  34350. }
  34351. this._currentRenderId = this._scene.getRenderId();
  34352. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  34353. // determine the number of particles we need to create
  34354. var newParticles;
  34355. if (this.manualEmitCount > -1) {
  34356. newParticles = this.manualEmitCount;
  34357. this._newPartsExcess = 0;
  34358. this.manualEmitCount = 0;
  34359. }
  34360. else {
  34361. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  34362. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  34363. }
  34364. if (this._newPartsExcess > 1.0) {
  34365. newParticles += this._newPartsExcess >> 0;
  34366. this._newPartsExcess -= this._newPartsExcess >> 0;
  34367. }
  34368. this._alive = false;
  34369. if (!this._stopped) {
  34370. this._actualFrame += this._scaledUpdateSpeed;
  34371. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  34372. this.stop();
  34373. }
  34374. else {
  34375. newParticles = 0;
  34376. }
  34377. this._update(newParticles);
  34378. // Stopped?
  34379. if (this._stopped) {
  34380. if (!this._alive) {
  34381. this._started = false;
  34382. if (this.disposeOnStop) {
  34383. this._scene._toBeDisposed.push(this);
  34384. }
  34385. }
  34386. }
  34387. // Update VBO
  34388. var offset = 0;
  34389. for (var index = 0; index < this.particles.length; index++) {
  34390. var particle = this.particles[index];
  34391. this._appendParticleVertex(offset++, particle, 0, 0);
  34392. this._appendParticleVertex(offset++, particle, 1, 0);
  34393. this._appendParticleVertex(offset++, particle, 1, 1);
  34394. this._appendParticleVertex(offset++, particle, 0, 1);
  34395. }
  34396. this._vertexBuffer.update(this._vertexData);
  34397. };
  34398. ParticleSystem.prototype.render = function () {
  34399. var effect = this._getEffect();
  34400. // Check
  34401. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  34402. return 0;
  34403. var engine = this._scene.getEngine();
  34404. // Render
  34405. engine.enableEffect(effect);
  34406. engine.setState(false);
  34407. var viewMatrix = this._scene.getViewMatrix();
  34408. effect.setTexture("diffuseSampler", this.particleTexture);
  34409. effect.setMatrix("view", viewMatrix);
  34410. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  34411. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  34412. if (this._scene.clipPlane) {
  34413. var clipPlane = this._scene.clipPlane;
  34414. var invView = viewMatrix.clone();
  34415. invView.invert();
  34416. effect.setMatrix("invView", invView);
  34417. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34418. }
  34419. // VBOs
  34420. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34421. // Draw order
  34422. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  34423. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34424. }
  34425. else {
  34426. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34427. }
  34428. if (this.forceDepthWrite) {
  34429. engine.setDepthWrite(true);
  34430. }
  34431. engine.draw(true, 0, this.particles.length * 6);
  34432. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34433. return this.particles.length;
  34434. };
  34435. ParticleSystem.prototype.dispose = function () {
  34436. if (this._vertexBuffer) {
  34437. this._vertexBuffer.dispose();
  34438. this._vertexBuffer = null;
  34439. }
  34440. if (this._indexBuffer) {
  34441. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34442. this._indexBuffer = null;
  34443. }
  34444. if (this.particleTexture) {
  34445. this.particleTexture.dispose();
  34446. this.particleTexture = null;
  34447. }
  34448. // Remove from scene
  34449. var index = this._scene.particleSystems.indexOf(this);
  34450. this._scene.particleSystems.splice(index, 1);
  34451. // Callback
  34452. this.onDisposeObservable.notifyObservers(this);
  34453. this.onDisposeObservable.clear();
  34454. };
  34455. // Clone
  34456. ParticleSystem.prototype.clone = function (name, newEmitter) {
  34457. var custom = null;
  34458. var program = null;
  34459. if (this.customShader != null) {
  34460. program = this.customShader;
  34461. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  34462. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  34463. }
  34464. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  34465. result.customShader = program;
  34466. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  34467. if (newEmitter === undefined) {
  34468. newEmitter = this.emitter;
  34469. }
  34470. result.emitter = newEmitter;
  34471. if (this.particleTexture) {
  34472. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  34473. }
  34474. if (!this.preventAutoStart) {
  34475. result.start();
  34476. }
  34477. return result;
  34478. };
  34479. ParticleSystem.prototype.serialize = function () {
  34480. var serializationObject = {};
  34481. serializationObject.name = this.name;
  34482. serializationObject.id = this.id;
  34483. // Emitter
  34484. if (this.emitter.position) {
  34485. serializationObject.emitterId = this.emitter.id;
  34486. }
  34487. else {
  34488. serializationObject.emitter = this.emitter.asArray();
  34489. }
  34490. serializationObject.capacity = this.getCapacity();
  34491. if (this.particleTexture) {
  34492. serializationObject.textureName = this.particleTexture.name;
  34493. }
  34494. // Animations
  34495. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34496. // Particle system
  34497. serializationObject.minAngularSpeed = this.minAngularSpeed;
  34498. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  34499. serializationObject.minSize = this.minSize;
  34500. serializationObject.maxSize = this.maxSize;
  34501. serializationObject.minEmitPower = this.minEmitPower;
  34502. serializationObject.maxEmitPower = this.maxEmitPower;
  34503. serializationObject.minLifeTime = this.minLifeTime;
  34504. serializationObject.maxLifeTime = this.maxLifeTime;
  34505. serializationObject.emitRate = this.emitRate;
  34506. serializationObject.minEmitBox = this.minEmitBox.asArray();
  34507. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  34508. serializationObject.gravity = this.gravity.asArray();
  34509. serializationObject.direction1 = this.direction1.asArray();
  34510. serializationObject.direction2 = this.direction2.asArray();
  34511. serializationObject.color1 = this.color1.asArray();
  34512. serializationObject.color2 = this.color2.asArray();
  34513. serializationObject.colorDead = this.colorDead.asArray();
  34514. serializationObject.updateSpeed = this.updateSpeed;
  34515. serializationObject.targetStopDuration = this.targetStopDuration;
  34516. serializationObject.textureMask = this.textureMask.asArray();
  34517. serializationObject.blendMode = this.blendMode;
  34518. serializationObject.customShader = this.customShader;
  34519. serializationObject.preventAutoStart = this.preventAutoStart;
  34520. return serializationObject;
  34521. };
  34522. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  34523. var name = parsedParticleSystem.name;
  34524. var custom = null;
  34525. var program = null;
  34526. if (parsedParticleSystem.customShader) {
  34527. program = parsedParticleSystem.customShader;
  34528. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  34529. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  34530. }
  34531. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  34532. particleSystem.customShader = program;
  34533. if (parsedParticleSystem.id) {
  34534. particleSystem.id = parsedParticleSystem.id;
  34535. }
  34536. // Auto start
  34537. if (parsedParticleSystem.preventAutoStart) {
  34538. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  34539. }
  34540. // Texture
  34541. if (parsedParticleSystem.textureName) {
  34542. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  34543. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  34544. }
  34545. // Emitter
  34546. if (parsedParticleSystem.emitterId) {
  34547. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  34548. }
  34549. else {
  34550. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  34551. }
  34552. // Animations
  34553. if (parsedParticleSystem.animations) {
  34554. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  34555. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  34556. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34557. }
  34558. }
  34559. if (parsedParticleSystem.autoAnimate) {
  34560. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  34561. }
  34562. // Particle system
  34563. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  34564. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  34565. particleSystem.minSize = parsedParticleSystem.minSize;
  34566. particleSystem.maxSize = parsedParticleSystem.maxSize;
  34567. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  34568. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  34569. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  34570. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  34571. particleSystem.emitRate = parsedParticleSystem.emitRate;
  34572. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  34573. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  34574. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  34575. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  34576. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  34577. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  34578. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  34579. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  34580. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  34581. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  34582. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  34583. particleSystem.blendMode = parsedParticleSystem.blendMode;
  34584. if (!particleSystem.preventAutoStart) {
  34585. particleSystem.start();
  34586. }
  34587. return particleSystem;
  34588. };
  34589. return ParticleSystem;
  34590. }());
  34591. // Statics
  34592. ParticleSystem.BLENDMODE_ONEONE = 0;
  34593. ParticleSystem.BLENDMODE_STANDARD = 1;
  34594. BABYLON.ParticleSystem = ParticleSystem;
  34595. })(BABYLON || (BABYLON = {}));
  34596. //# sourceMappingURL=babylon.particleSystem.js.map
  34597. var BABYLON;
  34598. (function (BABYLON) {
  34599. var AnimationRange = (function () {
  34600. function AnimationRange(name, from, to) {
  34601. this.name = name;
  34602. this.from = from;
  34603. this.to = to;
  34604. }
  34605. AnimationRange.prototype.clone = function () {
  34606. return new AnimationRange(this.name, this.from, this.to);
  34607. };
  34608. return AnimationRange;
  34609. }());
  34610. BABYLON.AnimationRange = AnimationRange;
  34611. /**
  34612. * Composed of a frame, and an action function
  34613. */
  34614. var AnimationEvent = (function () {
  34615. function AnimationEvent(frame, action, onlyOnce) {
  34616. this.frame = frame;
  34617. this.action = action;
  34618. this.onlyOnce = onlyOnce;
  34619. this.isDone = false;
  34620. }
  34621. return AnimationEvent;
  34622. }());
  34623. BABYLON.AnimationEvent = AnimationEvent;
  34624. var PathCursor = (function () {
  34625. function PathCursor(path) {
  34626. this.path = path;
  34627. this._onchange = new Array();
  34628. this.value = 0;
  34629. this.animations = new Array();
  34630. }
  34631. PathCursor.prototype.getPoint = function () {
  34632. var point = this.path.getPointAtLengthPosition(this.value);
  34633. return new BABYLON.Vector3(point.x, 0, point.y);
  34634. };
  34635. PathCursor.prototype.moveAhead = function (step) {
  34636. if (step === void 0) { step = 0.002; }
  34637. this.move(step);
  34638. return this;
  34639. };
  34640. PathCursor.prototype.moveBack = function (step) {
  34641. if (step === void 0) { step = 0.002; }
  34642. this.move(-step);
  34643. return this;
  34644. };
  34645. PathCursor.prototype.move = function (step) {
  34646. if (Math.abs(step) > 1) {
  34647. throw "step size should be less than 1.";
  34648. }
  34649. this.value += step;
  34650. this.ensureLimits();
  34651. this.raiseOnChange();
  34652. return this;
  34653. };
  34654. PathCursor.prototype.ensureLimits = function () {
  34655. while (this.value > 1) {
  34656. this.value -= 1;
  34657. }
  34658. while (this.value < 0) {
  34659. this.value += 1;
  34660. }
  34661. return this;
  34662. };
  34663. // used by animation engine
  34664. PathCursor.prototype.markAsDirty = function (propertyName) {
  34665. this.ensureLimits();
  34666. this.raiseOnChange();
  34667. return this;
  34668. };
  34669. PathCursor.prototype.raiseOnChange = function () {
  34670. var _this = this;
  34671. this._onchange.forEach(function (f) { return f(_this); });
  34672. return this;
  34673. };
  34674. PathCursor.prototype.onchange = function (f) {
  34675. this._onchange.push(f);
  34676. return this;
  34677. };
  34678. return PathCursor;
  34679. }());
  34680. BABYLON.PathCursor = PathCursor;
  34681. var Animation = (function () {
  34682. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  34683. this.name = name;
  34684. this.targetProperty = targetProperty;
  34685. this.framePerSecond = framePerSecond;
  34686. this.dataType = dataType;
  34687. this.loopMode = loopMode;
  34688. this.enableBlending = enableBlending;
  34689. this._offsetsCache = {};
  34690. this._highLimitsCache = {};
  34691. this._stopped = false;
  34692. this._blendingFactor = 0;
  34693. // The set of event that will be linked to this animation
  34694. this._events = new Array();
  34695. this.allowMatricesInterpolation = false;
  34696. this.blendingSpeed = 0.01;
  34697. this._ranges = {};
  34698. this.targetPropertyPath = targetProperty.split(".");
  34699. this.dataType = dataType;
  34700. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  34701. }
  34702. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  34703. var dataType = undefined;
  34704. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  34705. dataType = Animation.ANIMATIONTYPE_FLOAT;
  34706. }
  34707. else if (from instanceof BABYLON.Quaternion) {
  34708. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  34709. }
  34710. else if (from instanceof BABYLON.Vector3) {
  34711. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  34712. }
  34713. else if (from instanceof BABYLON.Vector2) {
  34714. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  34715. }
  34716. else if (from instanceof BABYLON.Color3) {
  34717. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34718. }
  34719. else if (from instanceof BABYLON.Size) {
  34720. dataType = Animation.ANIMATIONTYPE_SIZE;
  34721. }
  34722. if (dataType == undefined) {
  34723. return null;
  34724. }
  34725. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34726. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34727. animation.setKeys(keys);
  34728. if (easingFunction !== undefined) {
  34729. animation.setEasingFunction(easingFunction);
  34730. }
  34731. return animation;
  34732. };
  34733. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34734. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34735. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34736. };
  34737. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34738. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34739. node.animations.push(animation);
  34740. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34741. };
  34742. // Methods
  34743. /**
  34744. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34745. */
  34746. Animation.prototype.toString = function (fullDetails) {
  34747. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34748. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34749. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34750. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34751. if (fullDetails) {
  34752. ret += ", Ranges: {";
  34753. var first = true;
  34754. for (var name in this._ranges) {
  34755. if (first) {
  34756. ret += ", ";
  34757. first = false;
  34758. }
  34759. ret += name;
  34760. }
  34761. ret += "}";
  34762. }
  34763. return ret;
  34764. };
  34765. /**
  34766. * Add an event to this animation.
  34767. */
  34768. Animation.prototype.addEvent = function (event) {
  34769. this._events.push(event);
  34770. };
  34771. /**
  34772. * Remove all events found at the given frame
  34773. * @param frame
  34774. */
  34775. Animation.prototype.removeEvents = function (frame) {
  34776. for (var index = 0; index < this._events.length; index++) {
  34777. if (this._events[index].frame === frame) {
  34778. this._events.splice(index, 1);
  34779. index--;
  34780. }
  34781. }
  34782. };
  34783. Animation.prototype.createRange = function (name, from, to) {
  34784. // check name not already in use; could happen for bones after serialized
  34785. if (!this._ranges[name]) {
  34786. this._ranges[name] = new AnimationRange(name, from, to);
  34787. }
  34788. };
  34789. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34790. if (deleteFrames === void 0) { deleteFrames = true; }
  34791. if (this._ranges[name]) {
  34792. if (deleteFrames) {
  34793. var from = this._ranges[name].from;
  34794. var to = this._ranges[name].to;
  34795. // this loop MUST go high to low for multiple splices to work
  34796. for (var key = this._keys.length - 1; key >= 0; key--) {
  34797. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34798. this._keys.splice(key, 1);
  34799. }
  34800. }
  34801. }
  34802. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34803. }
  34804. };
  34805. Animation.prototype.getRange = function (name) {
  34806. return this._ranges[name];
  34807. };
  34808. Animation.prototype.reset = function () {
  34809. this._offsetsCache = {};
  34810. this._highLimitsCache = {};
  34811. this.currentFrame = 0;
  34812. this._blendingFactor = 0;
  34813. this._originalBlendValue = null;
  34814. };
  34815. Animation.prototype.isStopped = function () {
  34816. return this._stopped;
  34817. };
  34818. Animation.prototype.getKeys = function () {
  34819. return this._keys;
  34820. };
  34821. Animation.prototype.getHighestFrame = function () {
  34822. var ret = 0;
  34823. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34824. if (ret < this._keys[key].frame) {
  34825. ret = this._keys[key].frame;
  34826. }
  34827. }
  34828. return ret;
  34829. };
  34830. Animation.prototype.getEasingFunction = function () {
  34831. return this._easingFunction;
  34832. };
  34833. Animation.prototype.setEasingFunction = function (easingFunction) {
  34834. this._easingFunction = easingFunction;
  34835. };
  34836. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34837. return startValue + (endValue - startValue) * gradient;
  34838. };
  34839. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34840. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34841. };
  34842. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34843. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34844. };
  34845. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34846. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34847. };
  34848. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34849. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34850. };
  34851. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34852. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34853. };
  34854. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34855. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34856. };
  34857. Animation.prototype.clone = function () {
  34858. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34859. clone.enableBlending = this.enableBlending;
  34860. clone.blendingSpeed = this.blendingSpeed;
  34861. if (this._keys) {
  34862. clone.setKeys(this._keys);
  34863. }
  34864. if (this._ranges) {
  34865. clone._ranges = {};
  34866. for (var name in this._ranges) {
  34867. clone._ranges[name] = this._ranges[name].clone();
  34868. }
  34869. }
  34870. return clone;
  34871. };
  34872. Animation.prototype.setKeys = function (values) {
  34873. this._keys = values.slice(0);
  34874. this._offsetsCache = {};
  34875. this._highLimitsCache = {};
  34876. };
  34877. Animation.prototype._getKeyValue = function (value) {
  34878. if (typeof value === "function") {
  34879. return value();
  34880. }
  34881. return value;
  34882. };
  34883. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34884. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34885. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34886. }
  34887. this.currentFrame = currentFrame;
  34888. // Try to get a hash to find the right key
  34889. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  34890. if (this._keys[startKey].frame >= currentFrame) {
  34891. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  34892. startKey--;
  34893. }
  34894. }
  34895. for (var key = startKey; key < this._keys.length; key++) {
  34896. if (this._keys[key + 1].frame >= currentFrame) {
  34897. var startValue = this._getKeyValue(this._keys[key].value);
  34898. var endValue = this._getKeyValue(this._keys[key + 1].value);
  34899. // gradient : percent of currentFrame between the frame inf and the frame sup
  34900. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  34901. // check for easingFunction and correction of gradient
  34902. if (this._easingFunction != null) {
  34903. gradient = this._easingFunction.ease(gradient);
  34904. }
  34905. switch (this.dataType) {
  34906. // Float
  34907. case Animation.ANIMATIONTYPE_FLOAT:
  34908. switch (loopMode) {
  34909. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34910. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34911. return this.floatInterpolateFunction(startValue, endValue, gradient);
  34912. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34913. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  34914. }
  34915. break;
  34916. // Quaternion
  34917. case Animation.ANIMATIONTYPE_QUATERNION:
  34918. var quaternion = null;
  34919. switch (loopMode) {
  34920. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34921. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34922. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34923. break;
  34924. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34925. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34926. break;
  34927. }
  34928. return quaternion;
  34929. // Vector3
  34930. case Animation.ANIMATIONTYPE_VECTOR3:
  34931. switch (loopMode) {
  34932. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34933. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34934. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  34935. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34936. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34937. }
  34938. // Vector2
  34939. case Animation.ANIMATIONTYPE_VECTOR2:
  34940. switch (loopMode) {
  34941. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34942. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34943. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  34944. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34945. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34946. }
  34947. // Size
  34948. case Animation.ANIMATIONTYPE_SIZE:
  34949. switch (loopMode) {
  34950. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34951. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34952. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34953. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34954. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34955. }
  34956. // Color3
  34957. case Animation.ANIMATIONTYPE_COLOR3:
  34958. switch (loopMode) {
  34959. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34960. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34961. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34962. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34963. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34964. }
  34965. // Matrix
  34966. case Animation.ANIMATIONTYPE_MATRIX:
  34967. switch (loopMode) {
  34968. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34969. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34970. if (this.allowMatricesInterpolation) {
  34971. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34972. }
  34973. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34974. return startValue;
  34975. }
  34976. default:
  34977. break;
  34978. }
  34979. break;
  34980. }
  34981. }
  34982. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34983. };
  34984. Animation.prototype.setValue = function (currentValue, blend) {
  34985. if (blend === void 0) { blend = false; }
  34986. // Set value
  34987. var path;
  34988. var destination;
  34989. if (this.targetPropertyPath.length > 1) {
  34990. var property = this._target[this.targetPropertyPath[0]];
  34991. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34992. property = property[this.targetPropertyPath[index]];
  34993. }
  34994. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34995. destination = property;
  34996. }
  34997. else {
  34998. path = this.targetPropertyPath[0];
  34999. destination = this._target;
  35000. }
  35001. // Blending
  35002. if (this.enableBlending && this._blendingFactor <= 1.0) {
  35003. if (!this._originalBlendValue) {
  35004. if (destination[path].clone) {
  35005. this._originalBlendValue = destination[path].clone();
  35006. }
  35007. else {
  35008. this._originalBlendValue = destination[path];
  35009. }
  35010. }
  35011. if (this._originalBlendValue.prototype) {
  35012. if (this._originalBlendValue.prototype.Lerp) {
  35013. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  35014. }
  35015. else {
  35016. destination[path] = currentValue;
  35017. }
  35018. }
  35019. else if (this._originalBlendValue.m) {
  35020. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  35021. }
  35022. else {
  35023. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  35024. }
  35025. this._blendingFactor += this.blendingSpeed;
  35026. }
  35027. else {
  35028. destination[path] = currentValue;
  35029. }
  35030. if (this._target.markAsDirty) {
  35031. this._target.markAsDirty(this.targetProperty);
  35032. }
  35033. };
  35034. Animation.prototype.goToFrame = function (frame) {
  35035. if (frame < this._keys[0].frame) {
  35036. frame = this._keys[0].frame;
  35037. }
  35038. else if (frame > this._keys[this._keys.length - 1].frame) {
  35039. frame = this._keys[this._keys.length - 1].frame;
  35040. }
  35041. var currentValue = this._interpolate(frame, 0, this.loopMode);
  35042. this.setValue(currentValue);
  35043. };
  35044. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  35045. if (blend === void 0) { blend = false; }
  35046. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  35047. this._stopped = true;
  35048. return false;
  35049. }
  35050. var returnValue = true;
  35051. // Adding a start key at frame 0 if missing
  35052. if (this._keys[0].frame !== 0) {
  35053. var newKey = { frame: 0, value: this._keys[0].value };
  35054. this._keys.splice(0, 0, newKey);
  35055. }
  35056. // Check limits
  35057. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  35058. from = this._keys[0].frame;
  35059. }
  35060. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  35061. to = this._keys[this._keys.length - 1].frame;
  35062. }
  35063. //to and from cannot be the same key
  35064. if (from === to) {
  35065. from++;
  35066. }
  35067. // Compute ratio
  35068. var range = to - from;
  35069. var offsetValue;
  35070. // ratio represents the frame delta between from and to
  35071. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  35072. var highLimitValue = 0;
  35073. if (ratio > range && !loop) {
  35074. returnValue = false;
  35075. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  35076. }
  35077. else {
  35078. // Get max value if required
  35079. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  35080. var keyOffset = to.toString() + from.toString();
  35081. if (!this._offsetsCache[keyOffset]) {
  35082. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  35083. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  35084. switch (this.dataType) {
  35085. // Float
  35086. case Animation.ANIMATIONTYPE_FLOAT:
  35087. this._offsetsCache[keyOffset] = toValue - fromValue;
  35088. break;
  35089. // Quaternion
  35090. case Animation.ANIMATIONTYPE_QUATERNION:
  35091. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35092. break;
  35093. // Vector3
  35094. case Animation.ANIMATIONTYPE_VECTOR3:
  35095. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35096. // Vector2
  35097. case Animation.ANIMATIONTYPE_VECTOR2:
  35098. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35099. // Size
  35100. case Animation.ANIMATIONTYPE_SIZE:
  35101. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35102. // Color3
  35103. case Animation.ANIMATIONTYPE_COLOR3:
  35104. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  35105. default:
  35106. break;
  35107. }
  35108. this._highLimitsCache[keyOffset] = toValue;
  35109. }
  35110. highLimitValue = this._highLimitsCache[keyOffset];
  35111. offsetValue = this._offsetsCache[keyOffset];
  35112. }
  35113. }
  35114. if (offsetValue === undefined) {
  35115. switch (this.dataType) {
  35116. // Float
  35117. case Animation.ANIMATIONTYPE_FLOAT:
  35118. offsetValue = 0;
  35119. break;
  35120. // Quaternion
  35121. case Animation.ANIMATIONTYPE_QUATERNION:
  35122. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  35123. break;
  35124. // Vector3
  35125. case Animation.ANIMATIONTYPE_VECTOR3:
  35126. offsetValue = BABYLON.Vector3.Zero();
  35127. break;
  35128. // Vector2
  35129. case Animation.ANIMATIONTYPE_VECTOR2:
  35130. offsetValue = BABYLON.Vector2.Zero();
  35131. break;
  35132. // Size
  35133. case Animation.ANIMATIONTYPE_SIZE:
  35134. offsetValue = BABYLON.Size.Zero();
  35135. break;
  35136. // Color3
  35137. case Animation.ANIMATIONTYPE_COLOR3:
  35138. offsetValue = BABYLON.Color3.Black();
  35139. }
  35140. }
  35141. // Compute value
  35142. var repeatCount = (ratio / range) >> 0;
  35143. var currentFrame = returnValue ? from + ratio % range : to;
  35144. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  35145. // Set value
  35146. this.setValue(currentValue);
  35147. // Check events
  35148. for (var index = 0; index < this._events.length; index++) {
  35149. if (currentFrame >= this._events[index].frame) {
  35150. var event = this._events[index];
  35151. if (!event.isDone) {
  35152. // If event should be done only once, remove it.
  35153. if (event.onlyOnce) {
  35154. this._events.splice(index, 1);
  35155. index--;
  35156. }
  35157. event.isDone = true;
  35158. event.action();
  35159. } // Don't do anything if the event has already be done.
  35160. }
  35161. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  35162. // reset event, the animation is looping
  35163. this._events[index].isDone = false;
  35164. }
  35165. }
  35166. if (!returnValue) {
  35167. this._stopped = true;
  35168. }
  35169. return returnValue;
  35170. };
  35171. Animation.prototype.serialize = function () {
  35172. var serializationObject = {};
  35173. serializationObject.name = this.name;
  35174. serializationObject.property = this.targetProperty;
  35175. serializationObject.framePerSecond = this.framePerSecond;
  35176. serializationObject.dataType = this.dataType;
  35177. serializationObject.loopBehavior = this.loopMode;
  35178. serializationObject.enableBlending = this.enableBlending;
  35179. serializationObject.blendingSpeed = this.blendingSpeed;
  35180. var dataType = this.dataType;
  35181. serializationObject.keys = [];
  35182. var keys = this.getKeys();
  35183. for (var index = 0; index < keys.length; index++) {
  35184. var animationKey = keys[index];
  35185. var key = {};
  35186. key.frame = animationKey.frame;
  35187. switch (dataType) {
  35188. case Animation.ANIMATIONTYPE_FLOAT:
  35189. key.values = [animationKey.value];
  35190. break;
  35191. case Animation.ANIMATIONTYPE_QUATERNION:
  35192. case Animation.ANIMATIONTYPE_MATRIX:
  35193. case Animation.ANIMATIONTYPE_VECTOR3:
  35194. case Animation.ANIMATIONTYPE_COLOR3:
  35195. key.values = animationKey.value.asArray();
  35196. break;
  35197. }
  35198. serializationObject.keys.push(key);
  35199. }
  35200. serializationObject.ranges = [];
  35201. for (var name in this._ranges) {
  35202. var range = {};
  35203. range.name = name;
  35204. range.from = this._ranges[name].from;
  35205. range.to = this._ranges[name].to;
  35206. serializationObject.ranges.push(range);
  35207. }
  35208. return serializationObject;
  35209. };
  35210. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  35211. get: function () {
  35212. return Animation._ANIMATIONTYPE_FLOAT;
  35213. },
  35214. enumerable: true,
  35215. configurable: true
  35216. });
  35217. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  35218. get: function () {
  35219. return Animation._ANIMATIONTYPE_VECTOR3;
  35220. },
  35221. enumerable: true,
  35222. configurable: true
  35223. });
  35224. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  35225. get: function () {
  35226. return Animation._ANIMATIONTYPE_VECTOR2;
  35227. },
  35228. enumerable: true,
  35229. configurable: true
  35230. });
  35231. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  35232. get: function () {
  35233. return Animation._ANIMATIONTYPE_SIZE;
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  35239. get: function () {
  35240. return Animation._ANIMATIONTYPE_QUATERNION;
  35241. },
  35242. enumerable: true,
  35243. configurable: true
  35244. });
  35245. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  35246. get: function () {
  35247. return Animation._ANIMATIONTYPE_MATRIX;
  35248. },
  35249. enumerable: true,
  35250. configurable: true
  35251. });
  35252. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  35253. get: function () {
  35254. return Animation._ANIMATIONTYPE_COLOR3;
  35255. },
  35256. enumerable: true,
  35257. configurable: true
  35258. });
  35259. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  35260. get: function () {
  35261. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  35267. get: function () {
  35268. return Animation._ANIMATIONLOOPMODE_CYCLE;
  35269. },
  35270. enumerable: true,
  35271. configurable: true
  35272. });
  35273. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  35274. get: function () {
  35275. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. Animation.Parse = function (parsedAnimation) {
  35281. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  35282. var dataType = parsedAnimation.dataType;
  35283. var keys = [];
  35284. var data;
  35285. var index;
  35286. if (parsedAnimation.enableBlending) {
  35287. animation.enableBlending = parsedAnimation.enableBlending;
  35288. }
  35289. if (parsedAnimation.blendingSpeed) {
  35290. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  35291. }
  35292. for (index = 0; index < parsedAnimation.keys.length; index++) {
  35293. var key = parsedAnimation.keys[index];
  35294. switch (dataType) {
  35295. case Animation.ANIMATIONTYPE_FLOAT:
  35296. data = key.values[0];
  35297. break;
  35298. case Animation.ANIMATIONTYPE_QUATERNION:
  35299. data = BABYLON.Quaternion.FromArray(key.values);
  35300. break;
  35301. case Animation.ANIMATIONTYPE_MATRIX:
  35302. data = BABYLON.Matrix.FromArray(key.values);
  35303. break;
  35304. case Animation.ANIMATIONTYPE_COLOR3:
  35305. data = BABYLON.Color3.FromArray(key.values);
  35306. break;
  35307. case Animation.ANIMATIONTYPE_VECTOR3:
  35308. default:
  35309. data = BABYLON.Vector3.FromArray(key.values);
  35310. break;
  35311. }
  35312. keys.push({
  35313. frame: key.frame,
  35314. value: data
  35315. });
  35316. }
  35317. animation.setKeys(keys);
  35318. if (parsedAnimation.ranges) {
  35319. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  35320. data = parsedAnimation.ranges[index];
  35321. animation.createRange(data.name, data.from, data.to);
  35322. }
  35323. }
  35324. return animation;
  35325. };
  35326. Animation.AppendSerializedAnimations = function (source, destination) {
  35327. if (source.animations) {
  35328. destination.animations = [];
  35329. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  35330. var animation = source.animations[animationIndex];
  35331. destination.animations.push(animation.serialize());
  35332. }
  35333. }
  35334. };
  35335. return Animation;
  35336. }());
  35337. // Statics
  35338. Animation._ANIMATIONTYPE_FLOAT = 0;
  35339. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  35340. Animation._ANIMATIONTYPE_QUATERNION = 2;
  35341. Animation._ANIMATIONTYPE_MATRIX = 3;
  35342. Animation._ANIMATIONTYPE_COLOR3 = 4;
  35343. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  35344. Animation._ANIMATIONTYPE_SIZE = 6;
  35345. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  35346. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  35347. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  35348. BABYLON.Animation = Animation;
  35349. })(BABYLON || (BABYLON = {}));
  35350. //# sourceMappingURL=babylon.animation.js.map
  35351. var BABYLON;
  35352. (function (BABYLON) {
  35353. var Animatable = (function () {
  35354. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  35355. if (fromFrame === void 0) { fromFrame = 0; }
  35356. if (toFrame === void 0) { toFrame = 100; }
  35357. if (loopAnimation === void 0) { loopAnimation = false; }
  35358. if (speedRatio === void 0) { speedRatio = 1.0; }
  35359. this.target = target;
  35360. this.fromFrame = fromFrame;
  35361. this.toFrame = toFrame;
  35362. this.loopAnimation = loopAnimation;
  35363. this.speedRatio = speedRatio;
  35364. this.onAnimationEnd = onAnimationEnd;
  35365. this._animations = new Array();
  35366. this._paused = false;
  35367. this.animationStarted = false;
  35368. if (animations) {
  35369. this.appendAnimations(target, animations);
  35370. }
  35371. this._scene = scene;
  35372. scene._activeAnimatables.push(this);
  35373. }
  35374. // Methods
  35375. Animatable.prototype.getAnimations = function () {
  35376. return this._animations;
  35377. };
  35378. Animatable.prototype.appendAnimations = function (target, animations) {
  35379. for (var index = 0; index < animations.length; index++) {
  35380. var animation = animations[index];
  35381. animation._target = target;
  35382. this._animations.push(animation);
  35383. }
  35384. };
  35385. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  35386. var animations = this._animations;
  35387. for (var index = 0; index < animations.length; index++) {
  35388. if (animations[index].targetProperty === property) {
  35389. return animations[index];
  35390. }
  35391. }
  35392. return null;
  35393. };
  35394. Animatable.prototype.reset = function () {
  35395. var animations = this._animations;
  35396. for (var index = 0; index < animations.length; index++) {
  35397. animations[index].reset();
  35398. }
  35399. this._localDelayOffset = null;
  35400. this._pausedDelay = null;
  35401. };
  35402. Animatable.prototype.enableBlending = function (blendingSpeed) {
  35403. var animations = this._animations;
  35404. for (var index = 0; index < animations.length; index++) {
  35405. animations[index].enableBlending = true;
  35406. animations[index].blendingSpeed = blendingSpeed;
  35407. }
  35408. };
  35409. Animatable.prototype.disableBlending = function () {
  35410. var animations = this._animations;
  35411. for (var index = 0; index < animations.length; index++) {
  35412. animations[index].enableBlending = false;
  35413. }
  35414. };
  35415. Animatable.prototype.goToFrame = function (frame) {
  35416. var animations = this._animations;
  35417. if (animations[0]) {
  35418. var fps = animations[0].framePerSecond;
  35419. var currentFrame = animations[0].currentFrame;
  35420. var adjustTime = frame - currentFrame;
  35421. var delay = adjustTime * 1000 / fps;
  35422. this._localDelayOffset -= delay;
  35423. }
  35424. for (var index = 0; index < animations.length; index++) {
  35425. animations[index].goToFrame(frame);
  35426. }
  35427. };
  35428. Animatable.prototype.pause = function () {
  35429. if (this._paused) {
  35430. return;
  35431. }
  35432. this._paused = true;
  35433. };
  35434. Animatable.prototype.restart = function () {
  35435. this._paused = false;
  35436. };
  35437. Animatable.prototype.stop = function (animationName) {
  35438. if (animationName) {
  35439. var idx = this._scene._activeAnimatables.indexOf(this);
  35440. if (idx > -1) {
  35441. var animations = this._animations;
  35442. for (var index = animations.length - 1; index >= 0; index--) {
  35443. if (typeof animationName === "string" && animations[index].name != animationName) {
  35444. continue;
  35445. }
  35446. animations[index].reset();
  35447. animations.splice(index, 1);
  35448. }
  35449. if (animations.length == 0) {
  35450. this._scene._activeAnimatables.splice(idx, 1);
  35451. if (this.onAnimationEnd) {
  35452. this.onAnimationEnd();
  35453. }
  35454. }
  35455. }
  35456. }
  35457. else {
  35458. var index = this._scene._activeAnimatables.indexOf(this);
  35459. if (index > -1) {
  35460. this._scene._activeAnimatables.splice(index, 1);
  35461. var animations = this._animations;
  35462. for (var index = 0; index < animations.length; index++) {
  35463. animations[index].reset();
  35464. }
  35465. if (this.onAnimationEnd) {
  35466. this.onAnimationEnd();
  35467. }
  35468. }
  35469. }
  35470. };
  35471. Animatable.prototype._animate = function (delay) {
  35472. if (this._paused) {
  35473. this.animationStarted = false;
  35474. if (!this._pausedDelay) {
  35475. this._pausedDelay = delay;
  35476. }
  35477. return true;
  35478. }
  35479. if (!this._localDelayOffset) {
  35480. this._localDelayOffset = delay;
  35481. }
  35482. else if (this._pausedDelay) {
  35483. this._localDelayOffset += delay - this._pausedDelay;
  35484. this._pausedDelay = null;
  35485. }
  35486. // Animating
  35487. var running = false;
  35488. var animations = this._animations;
  35489. var index;
  35490. for (index = 0; index < animations.length; index++) {
  35491. var animation = animations[index];
  35492. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  35493. running = running || isRunning;
  35494. }
  35495. this.animationStarted = running;
  35496. if (!running) {
  35497. // Remove from active animatables
  35498. index = this._scene._activeAnimatables.indexOf(this);
  35499. this._scene._activeAnimatables.splice(index, 1);
  35500. }
  35501. if (!running && this.onAnimationEnd) {
  35502. this.onAnimationEnd();
  35503. this.onAnimationEnd = null;
  35504. }
  35505. return running;
  35506. };
  35507. return Animatable;
  35508. }());
  35509. BABYLON.Animatable = Animatable;
  35510. })(BABYLON || (BABYLON = {}));
  35511. //# sourceMappingURL=babylon.animatable.js.map
  35512. var BABYLON;
  35513. (function (BABYLON) {
  35514. var EasingFunction = (function () {
  35515. function EasingFunction() {
  35516. // Properties
  35517. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  35518. }
  35519. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  35520. get: function () {
  35521. return EasingFunction._EASINGMODE_EASEIN;
  35522. },
  35523. enumerable: true,
  35524. configurable: true
  35525. });
  35526. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  35527. get: function () {
  35528. return EasingFunction._EASINGMODE_EASEOUT;
  35529. },
  35530. enumerable: true,
  35531. configurable: true
  35532. });
  35533. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  35534. get: function () {
  35535. return EasingFunction._EASINGMODE_EASEINOUT;
  35536. },
  35537. enumerable: true,
  35538. configurable: true
  35539. });
  35540. EasingFunction.prototype.setEasingMode = function (easingMode) {
  35541. var n = Math.min(Math.max(easingMode, 0), 2);
  35542. this._easingMode = n;
  35543. };
  35544. EasingFunction.prototype.getEasingMode = function () {
  35545. return this._easingMode;
  35546. };
  35547. EasingFunction.prototype.easeInCore = function (gradient) {
  35548. throw new Error('You must implement this method');
  35549. };
  35550. EasingFunction.prototype.ease = function (gradient) {
  35551. switch (this._easingMode) {
  35552. case EasingFunction.EASINGMODE_EASEIN:
  35553. return this.easeInCore(gradient);
  35554. case EasingFunction.EASINGMODE_EASEOUT:
  35555. return (1 - this.easeInCore(1 - gradient));
  35556. }
  35557. if (gradient >= 0.5) {
  35558. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  35559. }
  35560. return (this.easeInCore(gradient * 2) * 0.5);
  35561. };
  35562. return EasingFunction;
  35563. }());
  35564. //Statics
  35565. EasingFunction._EASINGMODE_EASEIN = 0;
  35566. EasingFunction._EASINGMODE_EASEOUT = 1;
  35567. EasingFunction._EASINGMODE_EASEINOUT = 2;
  35568. BABYLON.EasingFunction = EasingFunction;
  35569. var CircleEase = (function (_super) {
  35570. __extends(CircleEase, _super);
  35571. function CircleEase() {
  35572. return _super !== null && _super.apply(this, arguments) || this;
  35573. }
  35574. CircleEase.prototype.easeInCore = function (gradient) {
  35575. gradient = Math.max(0, Math.min(1, gradient));
  35576. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  35577. };
  35578. return CircleEase;
  35579. }(EasingFunction));
  35580. BABYLON.CircleEase = CircleEase;
  35581. var BackEase = (function (_super) {
  35582. __extends(BackEase, _super);
  35583. function BackEase(amplitude) {
  35584. if (amplitude === void 0) { amplitude = 1; }
  35585. var _this = _super.call(this) || this;
  35586. _this.amplitude = amplitude;
  35587. return _this;
  35588. }
  35589. BackEase.prototype.easeInCore = function (gradient) {
  35590. var num = Math.max(0, this.amplitude);
  35591. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  35592. };
  35593. return BackEase;
  35594. }(EasingFunction));
  35595. BABYLON.BackEase = BackEase;
  35596. var BounceEase = (function (_super) {
  35597. __extends(BounceEase, _super);
  35598. function BounceEase(bounces, bounciness) {
  35599. if (bounces === void 0) { bounces = 3; }
  35600. if (bounciness === void 0) { bounciness = 2; }
  35601. var _this = _super.call(this) || this;
  35602. _this.bounces = bounces;
  35603. _this.bounciness = bounciness;
  35604. return _this;
  35605. }
  35606. BounceEase.prototype.easeInCore = function (gradient) {
  35607. var y = Math.max(0.0, this.bounces);
  35608. var bounciness = this.bounciness;
  35609. if (bounciness <= 1.0) {
  35610. bounciness = 1.001;
  35611. }
  35612. var num9 = Math.pow(bounciness, y);
  35613. var num5 = 1.0 - bounciness;
  35614. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  35615. var num15 = gradient * num4;
  35616. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  35617. var num3 = Math.floor(num65);
  35618. var num13 = num3 + 1.0;
  35619. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  35620. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  35621. var num7 = (num8 + num12) * 0.5;
  35622. var num6 = gradient - num7;
  35623. var num2 = num7 - num8;
  35624. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  35625. };
  35626. return BounceEase;
  35627. }(EasingFunction));
  35628. BABYLON.BounceEase = BounceEase;
  35629. var CubicEase = (function (_super) {
  35630. __extends(CubicEase, _super);
  35631. function CubicEase() {
  35632. return _super !== null && _super.apply(this, arguments) || this;
  35633. }
  35634. CubicEase.prototype.easeInCore = function (gradient) {
  35635. return (gradient * gradient * gradient);
  35636. };
  35637. return CubicEase;
  35638. }(EasingFunction));
  35639. BABYLON.CubicEase = CubicEase;
  35640. var ElasticEase = (function (_super) {
  35641. __extends(ElasticEase, _super);
  35642. function ElasticEase(oscillations, springiness) {
  35643. if (oscillations === void 0) { oscillations = 3; }
  35644. if (springiness === void 0) { springiness = 3; }
  35645. var _this = _super.call(this) || this;
  35646. _this.oscillations = oscillations;
  35647. _this.springiness = springiness;
  35648. return _this;
  35649. }
  35650. ElasticEase.prototype.easeInCore = function (gradient) {
  35651. var num2;
  35652. var num3 = Math.max(0.0, this.oscillations);
  35653. var num = Math.max(0.0, this.springiness);
  35654. if (num == 0) {
  35655. num2 = gradient;
  35656. }
  35657. else {
  35658. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  35659. }
  35660. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  35661. };
  35662. return ElasticEase;
  35663. }(EasingFunction));
  35664. BABYLON.ElasticEase = ElasticEase;
  35665. var ExponentialEase = (function (_super) {
  35666. __extends(ExponentialEase, _super);
  35667. function ExponentialEase(exponent) {
  35668. if (exponent === void 0) { exponent = 2; }
  35669. var _this = _super.call(this) || this;
  35670. _this.exponent = exponent;
  35671. return _this;
  35672. }
  35673. ExponentialEase.prototype.easeInCore = function (gradient) {
  35674. if (this.exponent <= 0) {
  35675. return gradient;
  35676. }
  35677. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  35678. };
  35679. return ExponentialEase;
  35680. }(EasingFunction));
  35681. BABYLON.ExponentialEase = ExponentialEase;
  35682. var PowerEase = (function (_super) {
  35683. __extends(PowerEase, _super);
  35684. function PowerEase(power) {
  35685. if (power === void 0) { power = 2; }
  35686. var _this = _super.call(this) || this;
  35687. _this.power = power;
  35688. return _this;
  35689. }
  35690. PowerEase.prototype.easeInCore = function (gradient) {
  35691. var y = Math.max(0.0, this.power);
  35692. return Math.pow(gradient, y);
  35693. };
  35694. return PowerEase;
  35695. }(EasingFunction));
  35696. BABYLON.PowerEase = PowerEase;
  35697. var QuadraticEase = (function (_super) {
  35698. __extends(QuadraticEase, _super);
  35699. function QuadraticEase() {
  35700. return _super !== null && _super.apply(this, arguments) || this;
  35701. }
  35702. QuadraticEase.prototype.easeInCore = function (gradient) {
  35703. return (gradient * gradient);
  35704. };
  35705. return QuadraticEase;
  35706. }(EasingFunction));
  35707. BABYLON.QuadraticEase = QuadraticEase;
  35708. var QuarticEase = (function (_super) {
  35709. __extends(QuarticEase, _super);
  35710. function QuarticEase() {
  35711. return _super !== null && _super.apply(this, arguments) || this;
  35712. }
  35713. QuarticEase.prototype.easeInCore = function (gradient) {
  35714. return (gradient * gradient * gradient * gradient);
  35715. };
  35716. return QuarticEase;
  35717. }(EasingFunction));
  35718. BABYLON.QuarticEase = QuarticEase;
  35719. var QuinticEase = (function (_super) {
  35720. __extends(QuinticEase, _super);
  35721. function QuinticEase() {
  35722. return _super !== null && _super.apply(this, arguments) || this;
  35723. }
  35724. QuinticEase.prototype.easeInCore = function (gradient) {
  35725. return (gradient * gradient * gradient * gradient * gradient);
  35726. };
  35727. return QuinticEase;
  35728. }(EasingFunction));
  35729. BABYLON.QuinticEase = QuinticEase;
  35730. var SineEase = (function (_super) {
  35731. __extends(SineEase, _super);
  35732. function SineEase() {
  35733. return _super !== null && _super.apply(this, arguments) || this;
  35734. }
  35735. SineEase.prototype.easeInCore = function (gradient) {
  35736. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35737. };
  35738. return SineEase;
  35739. }(EasingFunction));
  35740. BABYLON.SineEase = SineEase;
  35741. var BezierCurveEase = (function (_super) {
  35742. __extends(BezierCurveEase, _super);
  35743. function BezierCurveEase(x1, y1, x2, y2) {
  35744. if (x1 === void 0) { x1 = 0; }
  35745. if (y1 === void 0) { y1 = 0; }
  35746. if (x2 === void 0) { x2 = 1; }
  35747. if (y2 === void 0) { y2 = 1; }
  35748. var _this = _super.call(this) || this;
  35749. _this.x1 = x1;
  35750. _this.y1 = y1;
  35751. _this.x2 = x2;
  35752. _this.y2 = y2;
  35753. return _this;
  35754. }
  35755. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35756. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35757. };
  35758. return BezierCurveEase;
  35759. }(EasingFunction));
  35760. BABYLON.BezierCurveEase = BezierCurveEase;
  35761. })(BABYLON || (BABYLON = {}));
  35762. //# sourceMappingURL=babylon.easing.js.map
  35763. /// <reference path="..\babylon.node.ts" />
  35764. var BABYLON;
  35765. (function (BABYLON) {
  35766. var Bone = (function (_super) {
  35767. __extends(Bone, _super);
  35768. function Bone(name, skeleton, parentBone, matrix, restPose) {
  35769. var _this = _super.call(this, name, skeleton.getScene()) || this;
  35770. _this.name = name;
  35771. _this.children = new Array();
  35772. _this.animations = new Array();
  35773. _this._worldTransform = new BABYLON.Matrix();
  35774. _this._absoluteTransform = new BABYLON.Matrix();
  35775. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  35776. _this._scaleMatrix = BABYLON.Matrix.Identity();
  35777. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  35778. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  35779. _this._scalingDeterminant = 1;
  35780. _this._skeleton = skeleton;
  35781. _this._localMatrix = matrix;
  35782. _this._baseMatrix = matrix.clone();
  35783. _this._restPose = restPose ? restPose : matrix.clone();
  35784. skeleton.bones.push(_this);
  35785. if (parentBone) {
  35786. _this._parent = parentBone;
  35787. parentBone.children.push(_this);
  35788. }
  35789. else {
  35790. _this._parent = null;
  35791. }
  35792. _this._updateDifferenceMatrix();
  35793. if (_this.getAbsoluteTransform().determinant() < 0) {
  35794. _this._scalingDeterminant *= -1;
  35795. }
  35796. return _this;
  35797. }
  35798. Object.defineProperty(Bone.prototype, "_matrix", {
  35799. get: function () {
  35800. return this._localMatrix;
  35801. },
  35802. set: function (val) {
  35803. if (this._localMatrix) {
  35804. this._localMatrix.copyFrom(val);
  35805. }
  35806. else {
  35807. this._localMatrix = val;
  35808. }
  35809. },
  35810. enumerable: true,
  35811. configurable: true
  35812. });
  35813. // Members
  35814. Bone.prototype.getParent = function () {
  35815. return this._parent;
  35816. };
  35817. Bone.prototype.getLocalMatrix = function () {
  35818. return this._localMatrix;
  35819. };
  35820. Bone.prototype.getBaseMatrix = function () {
  35821. return this._baseMatrix;
  35822. };
  35823. Bone.prototype.getRestPose = function () {
  35824. return this._restPose;
  35825. };
  35826. Bone.prototype.returnToRest = function () {
  35827. this.updateMatrix(this._restPose.clone());
  35828. };
  35829. Bone.prototype.getWorldMatrix = function () {
  35830. return this._worldTransform;
  35831. };
  35832. Bone.prototype.getInvertedAbsoluteTransform = function () {
  35833. return this._invertedAbsoluteTransform;
  35834. };
  35835. Bone.prototype.getAbsoluteTransform = function () {
  35836. return this._absoluteTransform;
  35837. };
  35838. // Methods
  35839. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  35840. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  35841. this._baseMatrix = matrix.clone();
  35842. this._localMatrix = matrix.clone();
  35843. this._skeleton._markAsDirty();
  35844. if (updateDifferenceMatrix) {
  35845. this._updateDifferenceMatrix();
  35846. }
  35847. };
  35848. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  35849. if (!rootMatrix) {
  35850. rootMatrix = this._baseMatrix;
  35851. }
  35852. if (this._parent) {
  35853. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  35854. }
  35855. else {
  35856. this._absoluteTransform.copyFrom(rootMatrix);
  35857. }
  35858. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  35859. for (var index = 0; index < this.children.length; index++) {
  35860. this.children[index]._updateDifferenceMatrix();
  35861. }
  35862. };
  35863. Bone.prototype.markAsDirty = function () {
  35864. this._currentRenderId++;
  35865. this._skeleton._markAsDirty();
  35866. };
  35867. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  35868. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35869. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  35870. // all animation may be coming from a library skeleton, so may need to create animation
  35871. if (this.animations.length === 0) {
  35872. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  35873. this.animations[0].setKeys([]);
  35874. }
  35875. // get animation info / verify there is such a range from the source bone
  35876. var sourceRange = source.animations[0].getRange(rangeName);
  35877. if (!sourceRange) {
  35878. return false;
  35879. }
  35880. var from = sourceRange.from;
  35881. var to = sourceRange.to;
  35882. var sourceKeys = source.animations[0].getKeys();
  35883. // rescaling prep
  35884. var sourceBoneLength = source.length;
  35885. var sourceParent = source.getParent();
  35886. var parent = this.getParent();
  35887. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  35888. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  35889. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  35890. var destKeys = this.animations[0].getKeys();
  35891. // loop vars declaration
  35892. var orig;
  35893. var origTranslation;
  35894. var mat;
  35895. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  35896. orig = sourceKeys[key];
  35897. if (orig.frame >= from && orig.frame <= to) {
  35898. if (rescaleAsRequired) {
  35899. mat = orig.value.clone();
  35900. // scale based on parent ratio, when bone has parent
  35901. if (parentScalingReqd) {
  35902. origTranslation = mat.getTranslation();
  35903. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  35904. // scale based on skeleton dimension ratio when root bone, and value is passed
  35905. }
  35906. else if (dimensionsScalingReqd) {
  35907. origTranslation = mat.getTranslation();
  35908. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  35909. // use original when root bone, and no data for skelDimensionsRatio
  35910. }
  35911. else {
  35912. mat = orig.value;
  35913. }
  35914. }
  35915. else {
  35916. mat = orig.value;
  35917. }
  35918. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  35919. }
  35920. }
  35921. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  35922. return true;
  35923. };
  35924. /**
  35925. * Translate the bone in local or world space.
  35926. * @param vec The amount to translate the bone.
  35927. * @param space The space that the translation is in.
  35928. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35929. */
  35930. Bone.prototype.translate = function (vec, space, mesh) {
  35931. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35932. var lm = this.getLocalMatrix();
  35933. if (space == BABYLON.Space.LOCAL) {
  35934. lm.m[12] += vec.x;
  35935. lm.m[13] += vec.y;
  35936. lm.m[14] += vec.z;
  35937. }
  35938. else {
  35939. var wm;
  35940. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35941. if (mesh) {
  35942. wm = mesh.getWorldMatrix();
  35943. }
  35944. this._skeleton.computeAbsoluteTransforms();
  35945. var tmat = Bone._tmpMats[0];
  35946. var tvec = Bone._tmpVecs[0];
  35947. if (mesh) {
  35948. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35949. tmat.multiplyToRef(wm, tmat);
  35950. }
  35951. else {
  35952. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35953. }
  35954. tmat.m[12] = 0;
  35955. tmat.m[13] = 0;
  35956. tmat.m[14] = 0;
  35957. tmat.invert();
  35958. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  35959. lm.m[12] += tvec.x;
  35960. lm.m[13] += tvec.y;
  35961. lm.m[14] += tvec.z;
  35962. }
  35963. this.markAsDirty();
  35964. };
  35965. /**
  35966. * Set the postion of the bone in local or world space.
  35967. * @param position The position to set the bone.
  35968. * @param space The space that the position is in.
  35969. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  35970. */
  35971. Bone.prototype.setPosition = function (position, space, mesh) {
  35972. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  35973. var lm = this.getLocalMatrix();
  35974. if (space == BABYLON.Space.LOCAL) {
  35975. lm.m[12] = position.x;
  35976. lm.m[13] = position.y;
  35977. lm.m[14] = position.z;
  35978. }
  35979. else {
  35980. var wm;
  35981. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  35982. if (mesh) {
  35983. wm = mesh.getWorldMatrix();
  35984. }
  35985. this._skeleton.computeAbsoluteTransforms();
  35986. var tmat = Bone._tmpMats[0];
  35987. var vec = Bone._tmpVecs[0];
  35988. if (mesh) {
  35989. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35990. tmat.multiplyToRef(wm, tmat);
  35991. }
  35992. else {
  35993. tmat.copyFrom(this._parent.getAbsoluteTransform());
  35994. }
  35995. tmat.invert();
  35996. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  35997. lm.m[12] = vec.x;
  35998. lm.m[13] = vec.y;
  35999. lm.m[14] = vec.z;
  36000. }
  36001. this.markAsDirty();
  36002. };
  36003. /**
  36004. * Set the absolute postion of the bone (world space).
  36005. * @param position The position to set the bone.
  36006. * @param mesh The mesh that this bone is attached to.
  36007. */
  36008. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  36009. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  36010. };
  36011. /**
  36012. * Set the scale of the bone on the x, y and z axes.
  36013. * @param x The scale of the bone on the x axis.
  36014. * @param x The scale of the bone on the y axis.
  36015. * @param z The scale of the bone on the z axis.
  36016. * @param scaleChildren Set this to true if children of the bone should be scaled.
  36017. */
  36018. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  36019. if (scaleChildren === void 0) { scaleChildren = false; }
  36020. if (this.animations[0] && !this.animations[0].isStopped()) {
  36021. if (!scaleChildren) {
  36022. this._negateScaleChildren.x = 1 / x;
  36023. this._negateScaleChildren.y = 1 / y;
  36024. this._negateScaleChildren.z = 1 / z;
  36025. }
  36026. this._syncScaleVector();
  36027. }
  36028. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  36029. };
  36030. /**
  36031. * Scale the bone on the x, y and z axes.
  36032. * @param x The amount to scale the bone on the x axis.
  36033. * @param x The amount to scale the bone on the y axis.
  36034. * @param z The amount to scale the bone on the z axis.
  36035. * @param scaleChildren Set this to true if children of the bone should be scaled.
  36036. */
  36037. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  36038. if (scaleChildren === void 0) { scaleChildren = false; }
  36039. var locMat = this.getLocalMatrix();
  36040. var origLocMat = Bone._tmpMats[0];
  36041. origLocMat.copyFrom(locMat);
  36042. var origLocMatInv = Bone._tmpMats[1];
  36043. origLocMatInv.copyFrom(origLocMat);
  36044. origLocMatInv.invert();
  36045. var scaleMat = Bone._tmpMats[2];
  36046. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  36047. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  36048. this._scaleVector.x *= x;
  36049. this._scaleVector.y *= y;
  36050. this._scaleVector.z *= z;
  36051. locMat.multiplyToRef(origLocMatInv, locMat);
  36052. locMat.multiplyToRef(scaleMat, locMat);
  36053. locMat.multiplyToRef(origLocMat, locMat);
  36054. var parent = this.getParent();
  36055. if (parent) {
  36056. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  36057. }
  36058. else {
  36059. this.getAbsoluteTransform().copyFrom(locMat);
  36060. }
  36061. var len = this.children.length;
  36062. scaleMat.invert();
  36063. for (var i = 0; i < len; i++) {
  36064. var child = this.children[i];
  36065. var cm = child.getLocalMatrix();
  36066. cm.multiplyToRef(scaleMat, cm);
  36067. var lm = child.getLocalMatrix();
  36068. lm.m[12] *= x;
  36069. lm.m[13] *= y;
  36070. lm.m[14] *= z;
  36071. }
  36072. this.computeAbsoluteTransforms();
  36073. if (scaleChildren) {
  36074. for (var i = 0; i < len; i++) {
  36075. this.children[i].scale(x, y, z, scaleChildren);
  36076. }
  36077. }
  36078. this.markAsDirty();
  36079. };
  36080. /**
  36081. * Set the yaw, pitch, and roll of the bone in local or world space.
  36082. * @param yaw The rotation of the bone on the y axis.
  36083. * @param pitch The rotation of the bone on the x axis.
  36084. * @param roll The rotation of the bone on the z axis.
  36085. * @param space The space that the axes of rotation are in.
  36086. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36087. */
  36088. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  36089. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36090. var rotMat = Bone._tmpMats[0];
  36091. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  36092. var rotMatInv = Bone._tmpMats[1];
  36093. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  36094. rotMatInv.multiplyToRef(rotMat, rotMat);
  36095. this._rotateWithMatrix(rotMat, space, mesh);
  36096. };
  36097. /**
  36098. * Rotate the bone on an axis in local or world space.
  36099. * @param axis The axis to rotate the bone on.
  36100. * @param amount The amount to rotate the bone.
  36101. * @param space The space that the axis is in.
  36102. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36103. */
  36104. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  36105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36106. var rmat = Bone._tmpMats[0];
  36107. rmat.m[12] = 0;
  36108. rmat.m[13] = 0;
  36109. rmat.m[14] = 0;
  36110. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  36111. this._rotateWithMatrix(rmat, space, mesh);
  36112. };
  36113. /**
  36114. * Set the rotation of the bone to a particular axis angle in local or world space.
  36115. * @param axis The axis to rotate the bone on.
  36116. * @param angle The angle that the bone should be rotated to.
  36117. * @param space The space that the axis is in.
  36118. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36119. */
  36120. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  36121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36122. var rotMat = Bone._tmpMats[0];
  36123. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  36124. var rotMatInv = Bone._tmpMats[1];
  36125. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  36126. rotMatInv.multiplyToRef(rotMat, rotMat);
  36127. this._rotateWithMatrix(rotMat, space, mesh);
  36128. };
  36129. /**
  36130. * Set the euler rotation of the bone in local of world space.
  36131. * @param rotation The euler rotation that the bone should be set to.
  36132. * @param space The space that the rotation is in.
  36133. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36134. */
  36135. Bone.prototype.setRotation = function (rotation, space, mesh) {
  36136. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36137. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  36138. };
  36139. /**
  36140. * Set the quaternion rotation of the bone in local of world space.
  36141. * @param quat The quaternion rotation that the bone should be set to.
  36142. * @param space The space that the rotation is in.
  36143. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36144. */
  36145. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  36146. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36147. var rotMatInv = Bone._tmpMats[0];
  36148. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  36149. var rotMat = Bone._tmpMats[1];
  36150. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  36151. rotMatInv.multiplyToRef(rotMat, rotMat);
  36152. this._rotateWithMatrix(rotMat, space, mesh);
  36153. };
  36154. /**
  36155. * Set the rotation matrix of the bone in local of world space.
  36156. * @param rotMat The rotation matrix that the bone should be set to.
  36157. * @param space The space that the rotation is in.
  36158. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36159. */
  36160. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  36161. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36162. var rotMatInv = Bone._tmpMats[0];
  36163. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  36164. var rotMat2 = Bone._tmpMats[1];
  36165. rotMat2.copyFrom(rotMat);
  36166. rotMatInv.multiplyToRef(rotMat, rotMat2);
  36167. this._rotateWithMatrix(rotMat2, space, mesh);
  36168. };
  36169. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  36170. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36171. var lmat = this.getLocalMatrix();
  36172. var lx = lmat.m[12];
  36173. var ly = lmat.m[13];
  36174. var lz = lmat.m[14];
  36175. var parent = this.getParent();
  36176. var parentScale = Bone._tmpMats[3];
  36177. var parentScaleInv = Bone._tmpMats[4];
  36178. if (parent) {
  36179. if (space == BABYLON.Space.WORLD) {
  36180. if (mesh) {
  36181. parentScale.copyFrom(mesh.getWorldMatrix());
  36182. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  36183. }
  36184. else {
  36185. parentScale.copyFrom(parent.getAbsoluteTransform());
  36186. }
  36187. }
  36188. else {
  36189. parentScale = parent._scaleMatrix;
  36190. }
  36191. parentScaleInv.copyFrom(parentScale);
  36192. parentScaleInv.invert();
  36193. lmat.multiplyToRef(parentScale, lmat);
  36194. lmat.multiplyToRef(rmat, lmat);
  36195. lmat.multiplyToRef(parentScaleInv, lmat);
  36196. }
  36197. else {
  36198. if (space == BABYLON.Space.WORLD && mesh) {
  36199. parentScale.copyFrom(mesh.getWorldMatrix());
  36200. parentScaleInv.copyFrom(parentScale);
  36201. parentScaleInv.invert();
  36202. lmat.multiplyToRef(parentScale, lmat);
  36203. lmat.multiplyToRef(rmat, lmat);
  36204. lmat.multiplyToRef(parentScaleInv, lmat);
  36205. }
  36206. else {
  36207. lmat.multiplyToRef(rmat, lmat);
  36208. }
  36209. }
  36210. lmat.m[12] = lx;
  36211. lmat.m[13] = ly;
  36212. lmat.m[14] = lz;
  36213. this.computeAbsoluteTransforms();
  36214. this.markAsDirty();
  36215. };
  36216. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  36217. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36218. if (space == BABYLON.Space.WORLD) {
  36219. var scaleMatrix = Bone._tmpMats[2];
  36220. scaleMatrix.copyFrom(this._scaleMatrix);
  36221. rotMatInv.copyFrom(this.getAbsoluteTransform());
  36222. if (mesh) {
  36223. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  36224. var meshScale = Bone._tmpMats[3];
  36225. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  36226. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  36227. }
  36228. rotMatInv.invert();
  36229. scaleMatrix.m[0] *= this._scalingDeterminant;
  36230. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  36231. }
  36232. else {
  36233. rotMatInv.copyFrom(this.getLocalMatrix());
  36234. rotMatInv.invert();
  36235. var scaleMatrix = Bone._tmpMats[2];
  36236. scaleMatrix.copyFrom(this._scaleMatrix);
  36237. if (this._parent) {
  36238. var pscaleMatrix = Bone._tmpMats[3];
  36239. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  36240. pscaleMatrix.invert();
  36241. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  36242. }
  36243. else {
  36244. scaleMatrix.m[0] *= this._scalingDeterminant;
  36245. }
  36246. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  36247. }
  36248. };
  36249. /**
  36250. * Get the scale of the bone
  36251. * @returns the scale of the bone
  36252. */
  36253. Bone.prototype.getScale = function () {
  36254. return this._scaleVector.clone();
  36255. };
  36256. /**
  36257. * Copy the scale of the bone to a vector3.
  36258. * @param result The vector3 to copy the scale to
  36259. */
  36260. Bone.prototype.getScaleToRef = function (result) {
  36261. result.copyFrom(this._scaleVector);
  36262. };
  36263. /**
  36264. * Get the position of the bone in local or world space.
  36265. * @param space The space that the returned position is in.
  36266. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36267. * @returns The position of the bone
  36268. */
  36269. Bone.prototype.getPosition = function (space, mesh) {
  36270. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36271. var pos = BABYLON.Vector3.Zero();
  36272. this.getPositionToRef(space, mesh, pos);
  36273. return pos;
  36274. };
  36275. /**
  36276. * Copy the position of the bone to a vector3 in local or world space.
  36277. * @param space The space that the returned position is in.
  36278. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36279. * @param result The vector3 to copy the position to.
  36280. */
  36281. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  36282. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36283. if (space == BABYLON.Space.LOCAL) {
  36284. var lm = this.getLocalMatrix();
  36285. result.x = lm.m[12];
  36286. result.y = lm.m[13];
  36287. result.z = lm.m[14];
  36288. }
  36289. else {
  36290. var wm;
  36291. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  36292. if (mesh) {
  36293. wm = mesh.getWorldMatrix();
  36294. }
  36295. this._skeleton.computeAbsoluteTransforms();
  36296. var tmat = Bone._tmpMats[0];
  36297. if (mesh) {
  36298. tmat.copyFrom(this.getAbsoluteTransform());
  36299. tmat.multiplyToRef(wm, tmat);
  36300. }
  36301. else {
  36302. tmat = this.getAbsoluteTransform();
  36303. }
  36304. result.x = tmat.m[12];
  36305. result.y = tmat.m[13];
  36306. result.z = tmat.m[14];
  36307. }
  36308. };
  36309. /**
  36310. * Get the absolute position of the bone (world space).
  36311. * @param mesh The mesh that this bone is attached to.
  36312. * @returns The absolute position of the bone
  36313. */
  36314. Bone.prototype.getAbsolutePosition = function (mesh) {
  36315. var pos = BABYLON.Vector3.Zero();
  36316. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  36317. return pos;
  36318. };
  36319. /**
  36320. * Copy the absolute position of the bone (world space) to the result param.
  36321. * @param mesh The mesh that this bone is attached to.
  36322. * @param result The vector3 to copy the absolute position to.
  36323. */
  36324. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  36325. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  36326. };
  36327. /**
  36328. * Compute the absolute transforms of this bone and its children.
  36329. */
  36330. Bone.prototype.computeAbsoluteTransforms = function () {
  36331. if (this._parent) {
  36332. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  36333. }
  36334. else {
  36335. this._absoluteTransform.copyFrom(this._localMatrix);
  36336. var poseMatrix = this._skeleton.getPoseMatrix();
  36337. if (poseMatrix) {
  36338. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  36339. }
  36340. }
  36341. var children = this.children;
  36342. var len = children.length;
  36343. for (var i = 0; i < len; i++) {
  36344. children[i].computeAbsoluteTransforms();
  36345. }
  36346. };
  36347. Bone.prototype._syncScaleVector = function () {
  36348. var lm = this.getLocalMatrix();
  36349. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  36350. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  36351. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  36352. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  36353. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  36354. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  36355. this._scaleVector.x = xs * Math.sqrt(xsq);
  36356. this._scaleVector.y = ys * Math.sqrt(ysq);
  36357. this._scaleVector.z = zs * Math.sqrt(zsq);
  36358. if (this._parent) {
  36359. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  36360. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  36361. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  36362. }
  36363. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  36364. };
  36365. /**
  36366. * Get the world direction from an axis that is in the local space of the bone.
  36367. * @param localAxis The local direction that is used to compute the world direction.
  36368. * @param mesh The mesh that this bone is attached to.
  36369. * @returns The world direction
  36370. */
  36371. Bone.prototype.getDirection = function (localAxis, mesh) {
  36372. var result = BABYLON.Vector3.Zero();
  36373. this.getDirectionToRef(localAxis, mesh, result);
  36374. return result;
  36375. };
  36376. /**
  36377. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  36378. * @param localAxis The local direction that is used to compute the world direction.
  36379. * @param mesh The mesh that this bone is attached to.
  36380. * @param result The vector3 that the world direction will be copied to.
  36381. */
  36382. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  36383. var wm;
  36384. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  36385. if (mesh) {
  36386. wm = mesh.getWorldMatrix();
  36387. }
  36388. this._skeleton.computeAbsoluteTransforms();
  36389. var mat = Bone._tmpMats[0];
  36390. mat.copyFrom(this.getAbsoluteTransform());
  36391. if (mesh) {
  36392. mat.multiplyToRef(wm, mat);
  36393. }
  36394. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  36395. result.normalize();
  36396. };
  36397. /**
  36398. * Get the euler rotation of the bone in local or world space.
  36399. * @param space The space that the rotation should be in.
  36400. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36401. * @returns The euler rotation
  36402. */
  36403. Bone.prototype.getRotation = function (space, mesh) {
  36404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36405. var result = BABYLON.Vector3.Zero();
  36406. this.getRotationToRef(space, mesh, result);
  36407. return result;
  36408. };
  36409. /**
  36410. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  36411. * @param space The space that the rotation should be in.
  36412. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36413. * @param result The vector3 that the rotation should be copied to.
  36414. */
  36415. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  36416. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36417. var quat = Bone._tmpQuat;
  36418. this.getRotationQuaternionToRef(space, mesh, quat);
  36419. quat.toEulerAnglesToRef(result);
  36420. };
  36421. /**
  36422. * Get the quaternion rotation of the bone in either local or world space.
  36423. * @param space The space that the rotation should be in.
  36424. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36425. * @returns The quaternion rotation
  36426. */
  36427. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  36428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36429. var result = BABYLON.Quaternion.Identity();
  36430. this.getRotationQuaternionToRef(space, mesh, result);
  36431. return result;
  36432. };
  36433. /**
  36434. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  36435. * @param space The space that the rotation should be in.
  36436. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36437. * @param result The quaternion that the rotation should be copied to.
  36438. */
  36439. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  36440. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36441. if (space == BABYLON.Space.LOCAL) {
  36442. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  36443. }
  36444. else {
  36445. var mat = Bone._tmpMats[0];
  36446. var amat = this.getAbsoluteTransform();
  36447. if (mesh) {
  36448. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  36449. }
  36450. else {
  36451. mat.copyFrom(amat);
  36452. }
  36453. mat.m[0] *= this._scalingDeterminant;
  36454. mat.m[1] *= this._scalingDeterminant;
  36455. mat.m[2] *= this._scalingDeterminant;
  36456. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  36457. }
  36458. };
  36459. /**
  36460. * Get the rotation matrix of the bone in local or world space.
  36461. * @param space The space that the rotation should be in.
  36462. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36463. * @returns The rotation matrix
  36464. */
  36465. Bone.prototype.getRotationMatrix = function (space, mesh) {
  36466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36467. var result = BABYLON.Matrix.Identity();
  36468. this.getRotationMatrixToRef(space, mesh, result);
  36469. return result;
  36470. };
  36471. /**
  36472. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  36473. * @param space The space that the rotation should be in.
  36474. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  36475. * @param result The quaternion that the rotation should be copied to.
  36476. */
  36477. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  36478. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  36479. if (space == BABYLON.Space.LOCAL) {
  36480. this.getLocalMatrix().getRotationMatrixToRef(result);
  36481. }
  36482. else {
  36483. var mat = Bone._tmpMats[0];
  36484. var amat = this.getAbsoluteTransform();
  36485. if (mesh) {
  36486. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  36487. }
  36488. else {
  36489. mat.copyFrom(amat);
  36490. }
  36491. mat.m[0] *= this._scalingDeterminant;
  36492. mat.m[1] *= this._scalingDeterminant;
  36493. mat.m[2] *= this._scalingDeterminant;
  36494. mat.getRotationMatrixToRef(result);
  36495. }
  36496. };
  36497. /**
  36498. * Get the world position of a point that is in the local space of the bone.
  36499. * @param position The local position
  36500. * @param mesh The mesh that this bone is attached to.
  36501. * @returns The world position
  36502. */
  36503. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  36504. var result = BABYLON.Vector3.Zero();
  36505. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  36506. return result;
  36507. };
  36508. /**
  36509. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  36510. * @param position The local position
  36511. * @param mesh The mesh that this bone is attached to.
  36512. * @param result The vector3 that the world position should be copied to.
  36513. */
  36514. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  36515. var wm;
  36516. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  36517. if (mesh) {
  36518. wm = mesh.getWorldMatrix();
  36519. }
  36520. this._skeleton.computeAbsoluteTransforms();
  36521. var tmat = Bone._tmpMats[0];
  36522. if (mesh) {
  36523. tmat.copyFrom(this.getAbsoluteTransform());
  36524. tmat.multiplyToRef(wm, tmat);
  36525. }
  36526. else {
  36527. tmat = this.getAbsoluteTransform();
  36528. }
  36529. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  36530. };
  36531. /**
  36532. * Get the local position of a point that is in world space.
  36533. * @param position The world position
  36534. * @param mesh The mesh that this bone is attached to.
  36535. * @returns The local position
  36536. */
  36537. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  36538. var result = BABYLON.Vector3.Zero();
  36539. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  36540. return result;
  36541. };
  36542. /**
  36543. * Get the local position of a point that is in world space and copy it to the result param.
  36544. * @param position The world position
  36545. * @param mesh The mesh that this bone is attached to.
  36546. * @param result The vector3 that the local position should be copied to.
  36547. */
  36548. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  36549. var wm;
  36550. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  36551. if (mesh) {
  36552. wm = mesh.getWorldMatrix();
  36553. }
  36554. this._skeleton.computeAbsoluteTransforms();
  36555. var tmat = Bone._tmpMats[0];
  36556. tmat.copyFrom(this.getAbsoluteTransform());
  36557. if (mesh) {
  36558. tmat.multiplyToRef(wm, tmat);
  36559. }
  36560. tmat.invert();
  36561. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  36562. };
  36563. return Bone;
  36564. }(BABYLON.Node));
  36565. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  36566. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  36567. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  36568. BABYLON.Bone = Bone;
  36569. })(BABYLON || (BABYLON = {}));
  36570. //# sourceMappingURL=babylon.bone.js.map
  36571. var BABYLON;
  36572. (function (BABYLON) {
  36573. var BoneIKController = (function () {
  36574. function BoneIKController(mesh, bone, options) {
  36575. this.targetPosition = BABYLON.Vector3.Zero();
  36576. this.poleTargetPosition = BABYLON.Vector3.Zero();
  36577. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  36578. this.poleAngle = 0;
  36579. this.slerpAmount = 1;
  36580. this._bone1Quat = BABYLON.Quaternion.Identity();
  36581. this._bone1Mat = BABYLON.Matrix.Identity();
  36582. this._bone2Ang = Math.PI;
  36583. this._maxAngle = Math.PI;
  36584. this._rightHandedSystem = false;
  36585. this._bendAxis = BABYLON.Vector3.Right();
  36586. this._slerping = false;
  36587. this._adjustRoll = 0;
  36588. this._bone2 = bone;
  36589. this._bone1 = bone.getParent();
  36590. this.mesh = mesh;
  36591. var bonePos = bone.getPosition();
  36592. if (bone.getAbsoluteTransform().determinant() > 0) {
  36593. this._rightHandedSystem = true;
  36594. this._bendAxis.x = 0;
  36595. this._bendAxis.y = 0;
  36596. this._bendAxis.z = -1;
  36597. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  36598. this._adjustRoll = Math.PI * .5;
  36599. this._bendAxis.z = 1;
  36600. }
  36601. }
  36602. if (this._bone1.length) {
  36603. var boneScale1 = this._bone1.getScale();
  36604. var boneScale2 = this._bone2.getScale();
  36605. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  36606. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  36607. }
  36608. else if (this._bone1.children[0]) {
  36609. mesh.computeWorldMatrix(true);
  36610. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  36611. var pos2 = this._bone2.getAbsolutePosition(mesh);
  36612. var pos3 = this._bone1.getAbsolutePosition(mesh);
  36613. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  36614. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  36615. }
  36616. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  36617. this.maxAngle = Math.PI;
  36618. if (options) {
  36619. if (options.targetMesh) {
  36620. this.targetMesh = options.targetMesh;
  36621. this.targetMesh.computeWorldMatrix(true);
  36622. }
  36623. if (options.poleTargetMesh) {
  36624. this.poleTargetMesh = options.poleTargetMesh;
  36625. this.poleTargetMesh.computeWorldMatrix(true);
  36626. }
  36627. else if (options.poleTargetBone) {
  36628. this.poleTargetBone = options.poleTargetBone;
  36629. }
  36630. else if (this._bone1.getParent()) {
  36631. this.poleTargetBone = this._bone1.getParent();
  36632. }
  36633. if (options.poleTargetLocalOffset) {
  36634. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  36635. }
  36636. if (options.poleAngle) {
  36637. this.poleAngle = options.poleAngle;
  36638. }
  36639. if (options.bendAxis) {
  36640. this._bendAxis.copyFrom(options.bendAxis);
  36641. }
  36642. if (options.maxAngle) {
  36643. this.maxAngle = options.maxAngle;
  36644. }
  36645. if (options.slerpAmount) {
  36646. this.slerpAmount = options.slerpAmount;
  36647. }
  36648. }
  36649. }
  36650. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  36651. get: function () {
  36652. return this._maxAngle;
  36653. },
  36654. set: function (value) {
  36655. this._setMaxAngle(value);
  36656. },
  36657. enumerable: true,
  36658. configurable: true
  36659. });
  36660. BoneIKController.prototype._setMaxAngle = function (ang) {
  36661. if (ang < 0) {
  36662. ang = 0;
  36663. }
  36664. if (ang > Math.PI || ang == undefined) {
  36665. ang = Math.PI;
  36666. }
  36667. this._maxAngle = ang;
  36668. var a = this._bone1Length;
  36669. var b = this._bone2Length;
  36670. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  36671. };
  36672. BoneIKController.prototype.update = function () {
  36673. var bone1 = this._bone1;
  36674. var target = this.targetPosition;
  36675. var poleTarget = this.poleTargetPosition;
  36676. var mat1 = BoneIKController._tmpMats[0];
  36677. var mat2 = BoneIKController._tmpMats[1];
  36678. if (this.targetMesh) {
  36679. target.copyFrom(this.targetMesh.getAbsolutePosition());
  36680. }
  36681. if (this.poleTargetBone) {
  36682. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  36683. }
  36684. else if (this.poleTargetMesh) {
  36685. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  36686. }
  36687. var bonePos = BoneIKController._tmpVecs[0];
  36688. var zaxis = BoneIKController._tmpVecs[1];
  36689. var xaxis = BoneIKController._tmpVecs[2];
  36690. var yaxis = BoneIKController._tmpVecs[3];
  36691. var upAxis = BoneIKController._tmpVecs[4];
  36692. var _tmpQuat = BoneIKController._tmpQuat;
  36693. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  36694. poleTarget.subtractToRef(bonePos, upAxis);
  36695. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  36696. upAxis.y = 1;
  36697. }
  36698. else {
  36699. upAxis.normalize();
  36700. }
  36701. target.subtractToRef(bonePos, yaxis);
  36702. yaxis.normalize();
  36703. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  36704. zaxis.normalize();
  36705. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  36706. xaxis.normalize();
  36707. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  36708. var a = this._bone1Length;
  36709. var b = this._bone2Length;
  36710. var c = BABYLON.Vector3.Distance(bonePos, target);
  36711. if (this._maxReach > 0) {
  36712. c = Math.min(this._maxReach, c);
  36713. }
  36714. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  36715. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  36716. if (acosa > 1) {
  36717. acosa = 1;
  36718. }
  36719. if (acosb > 1) {
  36720. acosb = 1;
  36721. }
  36722. if (acosa < -1) {
  36723. acosa = -1;
  36724. }
  36725. if (acosb < -1) {
  36726. acosb = -1;
  36727. }
  36728. var angA = Math.acos(acosa);
  36729. var angB = Math.acos(acosb);
  36730. var angC = -angA - angB;
  36731. if (this._rightHandedSystem) {
  36732. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  36733. mat2.multiplyToRef(mat1, mat1);
  36734. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  36735. mat2.multiplyToRef(mat1, mat1);
  36736. }
  36737. else {
  36738. var _tmpVec = BoneIKController._tmpVecs[5];
  36739. _tmpVec.copyFrom(this._bendAxis);
  36740. _tmpVec.x *= -1;
  36741. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  36742. mat2.multiplyToRef(mat1, mat1);
  36743. }
  36744. if (this.poleAngle) {
  36745. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  36746. mat1.multiplyToRef(mat2, mat1);
  36747. }
  36748. if (this.slerpAmount < 1) {
  36749. if (!this._slerping) {
  36750. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  36751. }
  36752. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  36753. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  36754. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  36755. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  36756. this._slerping = true;
  36757. }
  36758. else {
  36759. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  36760. this._bone1Mat.copyFrom(mat1);
  36761. this._slerping = false;
  36762. }
  36763. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  36764. this._bone2Ang = angC;
  36765. };
  36766. return BoneIKController;
  36767. }());
  36768. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  36769. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  36770. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  36771. BABYLON.BoneIKController = BoneIKController;
  36772. })(BABYLON || (BABYLON = {}));
  36773. //# sourceMappingURL=babylon.boneIKController.js.map
  36774. var BABYLON;
  36775. (function (BABYLON) {
  36776. var BoneLookController = (function () {
  36777. /**
  36778. * Create a BoneLookController
  36779. * @param mesh the mesh that the bone belongs to
  36780. * @param bone the bone that will be looking to the target
  36781. * @param target the target Vector3 to look at
  36782. * @param settings optional settings:
  36783. * - maxYaw: the maximum angle the bone will yaw to
  36784. * - minYaw: the minimum angle the bone will yaw to
  36785. * - maxPitch: the maximum angle the bone will pitch to
  36786. * - minPitch: the minimum angle the bone will yaw to
  36787. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  36788. * - upAxis: the up axis of the coordinate system
  36789. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  36790. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  36791. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  36792. * - adjustYaw: used to make an adjustment to the yaw of the bone
  36793. * - adjustPitch: used to make an adjustment to the pitch of the bone
  36794. * - adjustRoll: used to make an adjustment to the roll of the bone
  36795. **/
  36796. function BoneLookController(mesh, bone, target, options) {
  36797. /**
  36798. * The up axis of the coordinate system that is used when the bone is rotated.
  36799. */
  36800. this.upAxis = BABYLON.Vector3.Up();
  36801. /**
  36802. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  36803. */
  36804. this.upAxisSpace = BABYLON.Space.LOCAL;
  36805. /**
  36806. * Used to make an adjustment to the yaw of the bone.
  36807. */
  36808. this.adjustYaw = 0;
  36809. /**
  36810. * Used to make an adjustment to the pitch of the bone.
  36811. */
  36812. this.adjustPitch = 0;
  36813. /**
  36814. * Used to make an adjustment to the roll of the bone.
  36815. */
  36816. this.adjustRoll = 0;
  36817. /**
  36818. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  36819. */
  36820. this.slerpAmount = 1;
  36821. this._boneQuat = BABYLON.Quaternion.Identity();
  36822. this._slerping = false;
  36823. this._firstFrameSkipped = false;
  36824. this._fowardAxis = BABYLON.Vector3.Forward();
  36825. this.mesh = mesh;
  36826. this.bone = bone;
  36827. this.target = target;
  36828. if (options) {
  36829. if (options.adjustYaw) {
  36830. this.adjustYaw = options.adjustYaw;
  36831. }
  36832. if (options.adjustPitch) {
  36833. this.adjustPitch = options.adjustPitch;
  36834. }
  36835. if (options.adjustRoll) {
  36836. this.adjustRoll = options.adjustRoll;
  36837. }
  36838. if (options.maxYaw != null) {
  36839. this.maxYaw = options.maxYaw;
  36840. }
  36841. else {
  36842. this.maxYaw = Math.PI;
  36843. }
  36844. if (options.minYaw != null) {
  36845. this.minYaw = options.minYaw;
  36846. }
  36847. else {
  36848. this.minYaw = -Math.PI;
  36849. }
  36850. if (options.maxPitch != null) {
  36851. this.maxPitch = options.maxPitch;
  36852. }
  36853. else {
  36854. this.maxPitch = Math.PI;
  36855. }
  36856. if (options.minPitch != null) {
  36857. this.minPitch = options.minPitch;
  36858. }
  36859. else {
  36860. this.minPitch = -Math.PI;
  36861. }
  36862. if (options.slerpAmount != null) {
  36863. this.slerpAmount = options.slerpAmount;
  36864. }
  36865. if (options.upAxis != null) {
  36866. this.upAxis = options.upAxis;
  36867. }
  36868. if (options.upAxisSpace != null) {
  36869. this.upAxisSpace = options.upAxisSpace;
  36870. }
  36871. if (options.yawAxis != null || options.pitchAxis != null) {
  36872. var newYawAxis = BABYLON.Axis.Y;
  36873. var newPitchAxis = BABYLON.Axis.X;
  36874. if (options.yawAxis != null) {
  36875. newYawAxis = options.yawAxis.clone();
  36876. newYawAxis.normalize();
  36877. }
  36878. if (options.pitchAxis != null) {
  36879. newPitchAxis = options.pitchAxis.clone();
  36880. newPitchAxis.normalize();
  36881. }
  36882. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  36883. this._transformYawPitch = BABYLON.Matrix.Identity();
  36884. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  36885. this._transformYawPitchInv = this._transformYawPitch.clone();
  36886. this._transformYawPitch.invert();
  36887. }
  36888. }
  36889. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  36890. this.upAxisSpace = BABYLON.Space.LOCAL;
  36891. }
  36892. }
  36893. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  36894. /**
  36895. * Get/set the minimum yaw angle that the bone can look to.
  36896. */
  36897. get: function () {
  36898. return this._minYaw;
  36899. },
  36900. set: function (value) {
  36901. this._minYaw = value;
  36902. this._minYawSin = Math.sin(value);
  36903. this._minYawCos = Math.cos(value);
  36904. if (this._maxYaw != null) {
  36905. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  36906. this._yawRange = this._maxYaw - this._minYaw;
  36907. }
  36908. },
  36909. enumerable: true,
  36910. configurable: true
  36911. });
  36912. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  36913. /**
  36914. * Get/set the maximum yaw angle that the bone can look to.
  36915. */
  36916. get: function () {
  36917. return this._maxYaw;
  36918. },
  36919. set: function (value) {
  36920. this._maxYaw = value;
  36921. this._maxYawSin = Math.sin(value);
  36922. this._maxYawCos = Math.cos(value);
  36923. if (this._minYaw != null) {
  36924. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  36925. this._yawRange = this._maxYaw - this._minYaw;
  36926. }
  36927. },
  36928. enumerable: true,
  36929. configurable: true
  36930. });
  36931. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  36932. /**
  36933. * Get/set the minimum pitch angle that the bone can look to.
  36934. */
  36935. get: function () {
  36936. return this._minPitch;
  36937. },
  36938. set: function (value) {
  36939. this._minPitch = value;
  36940. this._minPitchTan = Math.tan(value);
  36941. },
  36942. enumerable: true,
  36943. configurable: true
  36944. });
  36945. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  36946. /**
  36947. * Get/set the maximum pitch angle that the bone can look to.
  36948. */
  36949. get: function () {
  36950. return this._maxPitch;
  36951. },
  36952. set: function (value) {
  36953. this._maxPitch = value;
  36954. this._maxPitchTan = Math.tan(value);
  36955. },
  36956. enumerable: true,
  36957. configurable: true
  36958. });
  36959. /**
  36960. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  36961. */
  36962. BoneLookController.prototype.update = function () {
  36963. //skip the first frame when slerping so that the mesh rotation is correct
  36964. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  36965. this._firstFrameSkipped = true;
  36966. return;
  36967. }
  36968. var bone = this.bone;
  36969. var bonePos = BoneLookController._tmpVecs[0];
  36970. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  36971. var target = this.target;
  36972. var _tmpMat1 = BoneLookController._tmpMats[0];
  36973. var _tmpMat2 = BoneLookController._tmpMats[1];
  36974. var mesh = this.mesh;
  36975. var parentBone = bone.getParent();
  36976. var upAxis = BoneLookController._tmpVecs[1];
  36977. upAxis.copyFrom(this.upAxis);
  36978. if (this.upAxisSpace == BABYLON.Space.BONE) {
  36979. if (this._transformYawPitch) {
  36980. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  36981. }
  36982. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  36983. }
  36984. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  36985. mesh.getDirectionToRef(upAxis, upAxis);
  36986. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  36987. upAxis.normalize();
  36988. }
  36989. }
  36990. var checkYaw = false;
  36991. var checkPitch = false;
  36992. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  36993. checkYaw = true;
  36994. }
  36995. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  36996. checkPitch = true;
  36997. }
  36998. if (checkYaw || checkPitch) {
  36999. var spaceMat = BoneLookController._tmpMats[2];
  37000. var spaceMatInv = BoneLookController._tmpMats[3];
  37001. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  37002. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  37003. }
  37004. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  37005. spaceMat.copyFrom(mesh.getWorldMatrix());
  37006. }
  37007. else {
  37008. var forwardAxis = BoneLookController._tmpVecs[2];
  37009. forwardAxis.copyFrom(this._fowardAxis);
  37010. if (this._transformYawPitch) {
  37011. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  37012. }
  37013. if (parentBone) {
  37014. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  37015. }
  37016. else {
  37017. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  37018. }
  37019. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  37020. rightAxis.normalize();
  37021. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  37022. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  37023. }
  37024. spaceMat.invertToRef(spaceMatInv);
  37025. var xzlen;
  37026. if (checkPitch) {
  37027. var localTarget = BoneLookController._tmpVecs[3];
  37028. target.subtractToRef(bonePos, localTarget);
  37029. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  37030. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  37031. var pitch = Math.atan2(localTarget.y, xzlen);
  37032. var newPitch = pitch;
  37033. if (pitch > this._maxPitch) {
  37034. localTarget.y = this._maxPitchTan * xzlen;
  37035. newPitch = this._maxPitch;
  37036. }
  37037. else if (pitch < this._minPitch) {
  37038. localTarget.y = this._minPitchTan * xzlen;
  37039. newPitch = this._minPitch;
  37040. }
  37041. if (pitch != newPitch) {
  37042. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  37043. localTarget.addInPlace(bonePos);
  37044. target = localTarget;
  37045. }
  37046. }
  37047. if (checkYaw) {
  37048. var localTarget = BoneLookController._tmpVecs[4];
  37049. target.subtractToRef(bonePos, localTarget);
  37050. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  37051. var yaw = Math.atan2(localTarget.x, localTarget.z);
  37052. var newYaw = yaw;
  37053. if (yaw > this._maxYaw || yaw < this._minYaw) {
  37054. if (xzlen == null) {
  37055. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  37056. }
  37057. if (this._yawRange > Math.PI) {
  37058. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  37059. localTarget.z = this._maxYawCos * xzlen;
  37060. localTarget.x = this._maxYawSin * xzlen;
  37061. newYaw = this._maxYaw;
  37062. }
  37063. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  37064. localTarget.z = this._minYawCos * xzlen;
  37065. localTarget.x = this._minYawSin * xzlen;
  37066. newYaw = this._minYaw;
  37067. }
  37068. }
  37069. else {
  37070. if (yaw > this._maxYaw) {
  37071. localTarget.z = this._maxYawCos * xzlen;
  37072. localTarget.x = this._maxYawSin * xzlen;
  37073. newYaw = this._maxYaw;
  37074. }
  37075. else if (yaw < this._minYaw) {
  37076. localTarget.z = this._minYawCos * xzlen;
  37077. localTarget.x = this._minYawSin * xzlen;
  37078. newYaw = this._minYaw;
  37079. }
  37080. }
  37081. }
  37082. if (this._slerping && this._yawRange > Math.PI) {
  37083. //are we going to be crossing into the min/max region?
  37084. var boneFwd = BoneLookController._tmpVecs[8];
  37085. boneFwd.copyFrom(BABYLON.Axis.Z);
  37086. if (this._transformYawPitch) {
  37087. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  37088. }
  37089. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  37090. this._boneQuat.toRotationMatrix(boneRotMat);
  37091. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  37092. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  37093. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  37094. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  37095. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  37096. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  37097. if (angBtwTar > angBtwMidYaw) {
  37098. if (xzlen == null) {
  37099. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  37100. }
  37101. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  37102. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  37103. if (angBtwMin < angBtwMax) {
  37104. newYaw = boneYaw + Math.PI * .75;
  37105. localTarget.z = Math.cos(newYaw) * xzlen;
  37106. localTarget.x = Math.sin(newYaw) * xzlen;
  37107. }
  37108. else {
  37109. newYaw = boneYaw - Math.PI * .75;
  37110. localTarget.z = Math.cos(newYaw) * xzlen;
  37111. localTarget.x = Math.sin(newYaw) * xzlen;
  37112. }
  37113. }
  37114. }
  37115. if (yaw != newYaw) {
  37116. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  37117. localTarget.addInPlace(bonePos);
  37118. target = localTarget;
  37119. }
  37120. }
  37121. }
  37122. var zaxis = BoneLookController._tmpVecs[5];
  37123. var xaxis = BoneLookController._tmpVecs[6];
  37124. var yaxis = BoneLookController._tmpVecs[7];
  37125. var _tmpQuat = BoneLookController._tmpQuat;
  37126. target.subtractToRef(bonePos, zaxis);
  37127. zaxis.normalize();
  37128. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  37129. xaxis.normalize();
  37130. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  37131. yaxis.normalize();
  37132. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  37133. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  37134. return;
  37135. }
  37136. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  37137. return;
  37138. }
  37139. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  37140. return;
  37141. }
  37142. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  37143. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  37144. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  37145. }
  37146. if (this.slerpAmount < 1) {
  37147. if (!this._slerping) {
  37148. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  37149. }
  37150. if (this._transformYawPitch) {
  37151. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  37152. }
  37153. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  37154. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  37155. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  37156. this._slerping = true;
  37157. }
  37158. else {
  37159. if (this._transformYawPitch) {
  37160. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  37161. }
  37162. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  37163. this._slerping = false;
  37164. }
  37165. };
  37166. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  37167. var angDiff = ang2 - ang1;
  37168. angDiff %= Math.PI * 2;
  37169. if (angDiff > Math.PI) {
  37170. angDiff -= Math.PI * 2;
  37171. }
  37172. else if (angDiff < -Math.PI) {
  37173. angDiff += Math.PI * 2;
  37174. }
  37175. return angDiff;
  37176. };
  37177. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  37178. ang1 %= (2 * Math.PI);
  37179. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  37180. ang2 %= (2 * Math.PI);
  37181. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  37182. var ab = 0;
  37183. if (ang1 < ang2) {
  37184. ab = ang2 - ang1;
  37185. }
  37186. else {
  37187. ab = ang1 - ang2;
  37188. }
  37189. if (ab > Math.PI) {
  37190. ab = Math.PI * 2 - ab;
  37191. }
  37192. return ab;
  37193. };
  37194. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  37195. ang %= (2 * Math.PI);
  37196. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  37197. ang1 %= (2 * Math.PI);
  37198. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  37199. ang2 %= (2 * Math.PI);
  37200. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  37201. if (ang1 < ang2) {
  37202. if (ang > ang1 && ang < ang2) {
  37203. return true;
  37204. }
  37205. }
  37206. else {
  37207. if (ang > ang2 && ang < ang1) {
  37208. return true;
  37209. }
  37210. }
  37211. return false;
  37212. };
  37213. return BoneLookController;
  37214. }());
  37215. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37216. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  37217. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  37218. BABYLON.BoneLookController = BoneLookController;
  37219. })(BABYLON || (BABYLON = {}));
  37220. //# sourceMappingURL=babylon.boneLookController.js.map
  37221. var BABYLON;
  37222. (function (BABYLON) {
  37223. var Skeleton = (function () {
  37224. function Skeleton(name, id, scene) {
  37225. this.name = name;
  37226. this.id = id;
  37227. this.bones = new Array();
  37228. this.needInitialSkinMatrix = false;
  37229. this._isDirty = true;
  37230. this._meshesWithPoseMatrix = new Array();
  37231. this._identity = BABYLON.Matrix.Identity();
  37232. this._ranges = {};
  37233. this._lastAbsoluteTransformsUpdateId = -1;
  37234. // Events
  37235. /**
  37236. * An event triggered before computing the skeleton's matrices
  37237. * @type {BABYLON.Observable}
  37238. */
  37239. this.onBeforeComputeObservable = new BABYLON.Observable();
  37240. this.bones = [];
  37241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37242. scene.skeletons.push(this);
  37243. //make sure it will recalculate the matrix next time prepare is called.
  37244. this._isDirty = true;
  37245. }
  37246. // Members
  37247. Skeleton.prototype.getTransformMatrices = function (mesh) {
  37248. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  37249. return mesh._bonesTransformMatrices;
  37250. }
  37251. if (!this._transformMatrices) {
  37252. this.prepare();
  37253. }
  37254. return this._transformMatrices;
  37255. };
  37256. Skeleton.prototype.getScene = function () {
  37257. return this._scene;
  37258. };
  37259. // Methods
  37260. /**
  37261. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  37262. */
  37263. Skeleton.prototype.toString = function (fullDetails) {
  37264. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  37265. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  37266. if (fullDetails) {
  37267. ret += ", Ranges: {";
  37268. var first = true;
  37269. for (var name_1 in this._ranges) {
  37270. if (first) {
  37271. ret += ", ";
  37272. first = false;
  37273. }
  37274. ret += name_1;
  37275. }
  37276. ret += "}";
  37277. }
  37278. return ret;
  37279. };
  37280. /**
  37281. * Get bone's index searching by name
  37282. * @param {string} name is bone's name to search for
  37283. * @return {number} Indice of the bone. Returns -1 if not found
  37284. */
  37285. Skeleton.prototype.getBoneIndexByName = function (name) {
  37286. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  37287. if (this.bones[boneIndex].name === name) {
  37288. return boneIndex;
  37289. }
  37290. }
  37291. return -1;
  37292. };
  37293. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  37294. // check name not already in use
  37295. if (!this._ranges[name]) {
  37296. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  37297. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  37298. if (this.bones[i].animations[0]) {
  37299. this.bones[i].animations[0].createRange(name, from, to);
  37300. }
  37301. }
  37302. }
  37303. };
  37304. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  37305. if (deleteFrames === void 0) { deleteFrames = true; }
  37306. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  37307. if (this.bones[i].animations[0]) {
  37308. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  37309. }
  37310. }
  37311. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37312. };
  37313. Skeleton.prototype.getAnimationRange = function (name) {
  37314. return this._ranges[name];
  37315. };
  37316. /**
  37317. * Returns as an Array, all AnimationRanges defined on this skeleton
  37318. */
  37319. Skeleton.prototype.getAnimationRanges = function () {
  37320. var animationRanges = [];
  37321. var name;
  37322. var i = 0;
  37323. for (name in this._ranges) {
  37324. animationRanges[i] = this._ranges[name];
  37325. i++;
  37326. }
  37327. return animationRanges;
  37328. };
  37329. /**
  37330. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  37331. */
  37332. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  37333. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  37334. if (this._ranges[name] || !source.getAnimationRange(name)) {
  37335. return false;
  37336. }
  37337. var ret = true;
  37338. var frameOffset = this._getHighestAnimationFrame() + 1;
  37339. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  37340. var boneDict = {};
  37341. var sourceBones = source.bones;
  37342. var nBones;
  37343. var i;
  37344. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  37345. boneDict[sourceBones[i].name] = sourceBones[i];
  37346. }
  37347. if (this.bones.length !== sourceBones.length) {
  37348. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  37349. ret = false;
  37350. }
  37351. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  37352. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  37353. var boneName = this.bones[i].name;
  37354. var sourceBone = boneDict[boneName];
  37355. if (sourceBone) {
  37356. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  37357. }
  37358. else {
  37359. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  37360. ret = false;
  37361. }
  37362. }
  37363. // do not call createAnimationRange(), since it also is done to bones, which was already done
  37364. var range = source.getAnimationRange(name);
  37365. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  37366. return ret;
  37367. };
  37368. Skeleton.prototype.returnToRest = function () {
  37369. for (var index = 0; index < this.bones.length; index++) {
  37370. this.bones[index].returnToRest();
  37371. }
  37372. };
  37373. Skeleton.prototype._getHighestAnimationFrame = function () {
  37374. var ret = 0;
  37375. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  37376. if (this.bones[i].animations[0]) {
  37377. var highest = this.bones[i].animations[0].getHighestFrame();
  37378. if (ret < highest) {
  37379. ret = highest;
  37380. }
  37381. }
  37382. }
  37383. return ret;
  37384. };
  37385. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  37386. var range = this.getAnimationRange(name);
  37387. if (!range) {
  37388. return null;
  37389. }
  37390. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  37391. };
  37392. Skeleton.prototype._markAsDirty = function () {
  37393. this._isDirty = true;
  37394. };
  37395. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  37396. this._meshesWithPoseMatrix.push(mesh);
  37397. };
  37398. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  37399. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  37400. if (index > -1) {
  37401. this._meshesWithPoseMatrix.splice(index, 1);
  37402. }
  37403. };
  37404. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  37405. this.onBeforeComputeObservable.notifyObservers(this);
  37406. for (var index = 0; index < this.bones.length; index++) {
  37407. var bone = this.bones[index];
  37408. var parentBone = bone.getParent();
  37409. if (parentBone) {
  37410. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  37411. }
  37412. else {
  37413. if (initialSkinMatrix) {
  37414. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  37415. }
  37416. else {
  37417. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  37418. }
  37419. }
  37420. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  37421. }
  37422. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  37423. };
  37424. Skeleton.prototype.prepare = function () {
  37425. if (!this._isDirty) {
  37426. return;
  37427. }
  37428. if (this.needInitialSkinMatrix) {
  37429. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  37430. var mesh = this._meshesWithPoseMatrix[index];
  37431. var poseMatrix = mesh.getPoseMatrix();
  37432. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  37433. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  37434. }
  37435. if (this._synchronizedWithMesh !== mesh) {
  37436. this._synchronizedWithMesh = mesh;
  37437. // Prepare bones
  37438. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  37439. var bone = this.bones[boneIndex];
  37440. if (!bone.getParent()) {
  37441. var matrix = bone.getBaseMatrix();
  37442. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  37443. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  37444. }
  37445. }
  37446. }
  37447. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  37448. }
  37449. }
  37450. else {
  37451. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  37452. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  37453. }
  37454. this._computeTransformMatrices(this._transformMatrices, null);
  37455. }
  37456. this._isDirty = false;
  37457. this._scene._activeBones.addCount(this.bones.length, false);
  37458. };
  37459. Skeleton.prototype.getAnimatables = function () {
  37460. if (!this._animatables || this._animatables.length !== this.bones.length) {
  37461. this._animatables = [];
  37462. for (var index = 0; index < this.bones.length; index++) {
  37463. this._animatables.push(this.bones[index]);
  37464. }
  37465. }
  37466. return this._animatables;
  37467. };
  37468. Skeleton.prototype.clone = function (name, id) {
  37469. var result = new Skeleton(name, id || name, this._scene);
  37470. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  37471. for (var index = 0; index < this.bones.length; index++) {
  37472. var source = this.bones[index];
  37473. var parentBone = null;
  37474. if (source.getParent()) {
  37475. var parentIndex = this.bones.indexOf(source.getParent());
  37476. parentBone = result.bones[parentIndex];
  37477. }
  37478. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  37479. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  37480. }
  37481. if (this._ranges) {
  37482. result._ranges = {};
  37483. for (var rangeName in this._ranges) {
  37484. result._ranges[rangeName] = this._ranges[rangeName].clone();
  37485. }
  37486. }
  37487. this._isDirty = true;
  37488. return result;
  37489. };
  37490. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  37491. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  37492. this.bones.forEach(function (bone) {
  37493. bone.animations.forEach(function (animation) {
  37494. animation.enableBlending = true;
  37495. animation.blendingSpeed = blendingSpeed;
  37496. });
  37497. });
  37498. };
  37499. Skeleton.prototype.dispose = function () {
  37500. this._meshesWithPoseMatrix = [];
  37501. // Animations
  37502. this.getScene().stopAnimation(this);
  37503. // Remove from scene
  37504. this.getScene().removeSkeleton(this);
  37505. };
  37506. Skeleton.prototype.serialize = function () {
  37507. var serializationObject = {};
  37508. serializationObject.name = this.name;
  37509. serializationObject.id = this.id;
  37510. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  37511. serializationObject.bones = [];
  37512. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  37513. for (var index = 0; index < this.bones.length; index++) {
  37514. var bone = this.bones[index];
  37515. var serializedBone = {
  37516. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  37517. name: bone.name,
  37518. matrix: bone.getBaseMatrix().toArray(),
  37519. rest: bone.getRestPose().toArray()
  37520. };
  37521. serializationObject.bones.push(serializedBone);
  37522. if (bone.length) {
  37523. serializedBone.length = bone.length;
  37524. }
  37525. if (bone.animations && bone.animations.length > 0) {
  37526. serializedBone.animation = bone.animations[0].serialize();
  37527. }
  37528. serializationObject.ranges = [];
  37529. for (var name in this._ranges) {
  37530. var range = {};
  37531. range.name = name;
  37532. range.from = this._ranges[name].from;
  37533. range.to = this._ranges[name].to;
  37534. serializationObject.ranges.push(range);
  37535. }
  37536. }
  37537. return serializationObject;
  37538. };
  37539. Skeleton.Parse = function (parsedSkeleton, scene) {
  37540. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  37541. if (parsedSkeleton.dimensionsAtRest) {
  37542. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  37543. }
  37544. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  37545. var index;
  37546. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  37547. var parsedBone = parsedSkeleton.bones[index];
  37548. var parentBone = null;
  37549. if (parsedBone.parentBoneIndex > -1) {
  37550. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  37551. }
  37552. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  37553. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  37554. if (parsedBone.length) {
  37555. bone.length = parsedBone.length;
  37556. }
  37557. if (parsedBone.animation) {
  37558. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  37559. }
  37560. }
  37561. // placed after bones, so createAnimationRange can cascade down
  37562. if (parsedSkeleton.ranges) {
  37563. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  37564. var data = parsedSkeleton.ranges[index];
  37565. skeleton.createAnimationRange(data.name, data.from, data.to);
  37566. }
  37567. }
  37568. return skeleton;
  37569. };
  37570. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  37571. if (forceUpdate === void 0) { forceUpdate = false; }
  37572. var renderId = this._scene.getRenderId();
  37573. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  37574. this.bones[0].computeAbsoluteTransforms();
  37575. this._lastAbsoluteTransformsUpdateId = renderId;
  37576. }
  37577. };
  37578. Skeleton.prototype.getPoseMatrix = function () {
  37579. var poseMatrix;
  37580. if (this._meshesWithPoseMatrix.length > 0) {
  37581. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  37582. }
  37583. return poseMatrix;
  37584. };
  37585. return Skeleton;
  37586. }());
  37587. BABYLON.Skeleton = Skeleton;
  37588. })(BABYLON || (BABYLON = {}));
  37589. //# sourceMappingURL=babylon.skeleton.js.map
  37590. var BABYLON;
  37591. (function (BABYLON) {
  37592. var PostProcess = (function () {
  37593. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  37594. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  37595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37596. this.name = name;
  37597. this.width = -1;
  37598. this.height = -1;
  37599. /*
  37600. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  37601. Can only be used on a single postprocess or on the last one of a chain.
  37602. */
  37603. this.enablePixelPerfectMode = false;
  37604. this.samples = 1;
  37605. this._reusable = false;
  37606. this._textures = new BABYLON.SmartArray(2);
  37607. this._currentRenderTextureInd = 0;
  37608. this._scaleRatio = new BABYLON.Vector2(1, 1);
  37609. // Events
  37610. /**
  37611. * An event triggered when the postprocess is activated.
  37612. * @type {BABYLON.Observable}
  37613. */
  37614. this.onActivateObservable = new BABYLON.Observable();
  37615. /**
  37616. * An event triggered when the postprocess changes its size.
  37617. * @type {BABYLON.Observable}
  37618. */
  37619. this.onSizeChangedObservable = new BABYLON.Observable();
  37620. /**
  37621. * An event triggered when the postprocess applies its effect.
  37622. * @type {BABYLON.Observable}
  37623. */
  37624. this.onApplyObservable = new BABYLON.Observable();
  37625. /**
  37626. * An event triggered before rendering the postprocess
  37627. * @type {BABYLON.Observable}
  37628. */
  37629. this.onBeforeRenderObservable = new BABYLON.Observable();
  37630. /**
  37631. * An event triggered after rendering the postprocess
  37632. * @type {BABYLON.Observable}
  37633. */
  37634. this.onAfterRenderObservable = new BABYLON.Observable();
  37635. if (camera != null) {
  37636. this._camera = camera;
  37637. this._scene = camera.getScene();
  37638. camera.attachPostProcess(this);
  37639. this._engine = this._scene.getEngine();
  37640. }
  37641. else {
  37642. this._engine = engine;
  37643. }
  37644. this._options = options;
  37645. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  37646. this._reusable = reusable || false;
  37647. this._textureType = textureType;
  37648. this._samplers = samplers || [];
  37649. this._samplers.push("textureSampler");
  37650. this._fragmentUrl = fragmentUrl;
  37651. this._parameters = parameters || [];
  37652. this._parameters.push("scale");
  37653. this.updateEffect(defines);
  37654. }
  37655. Object.defineProperty(PostProcess.prototype, "onActivate", {
  37656. set: function (callback) {
  37657. if (this._onActivateObserver) {
  37658. this.onActivateObservable.remove(this._onActivateObserver);
  37659. }
  37660. this._onActivateObserver = this.onActivateObservable.add(callback);
  37661. },
  37662. enumerable: true,
  37663. configurable: true
  37664. });
  37665. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  37666. set: function (callback) {
  37667. if (this._onSizeChangedObserver) {
  37668. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  37669. }
  37670. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  37671. },
  37672. enumerable: true,
  37673. configurable: true
  37674. });
  37675. Object.defineProperty(PostProcess.prototype, "onApply", {
  37676. set: function (callback) {
  37677. if (this._onApplyObserver) {
  37678. this.onApplyObservable.remove(this._onApplyObserver);
  37679. }
  37680. this._onApplyObserver = this.onApplyObservable.add(callback);
  37681. },
  37682. enumerable: true,
  37683. configurable: true
  37684. });
  37685. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  37686. set: function (callback) {
  37687. if (this._onBeforeRenderObserver) {
  37688. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  37689. }
  37690. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  37691. },
  37692. enumerable: true,
  37693. configurable: true
  37694. });
  37695. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  37696. set: function (callback) {
  37697. if (this._onAfterRenderObserver) {
  37698. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  37699. }
  37700. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  37701. },
  37702. enumerable: true,
  37703. configurable: true
  37704. });
  37705. PostProcess.prototype.updateEffect = function (defines) {
  37706. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  37707. };
  37708. PostProcess.prototype.isReusable = function () {
  37709. return this._reusable;
  37710. };
  37711. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  37712. PostProcess.prototype.markTextureDirty = function () {
  37713. this.width = -1;
  37714. };
  37715. PostProcess.prototype.activate = function (camera, sourceTexture) {
  37716. var _this = this;
  37717. camera = camera || this._camera;
  37718. var scene = camera.getScene();
  37719. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  37720. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  37721. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  37722. var desiredWidth = this._options.width || requiredWidth;
  37723. var desiredHeight = this._options.height || requiredHeight;
  37724. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  37725. if (!this._options.width) {
  37726. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  37727. }
  37728. if (!this._options.height) {
  37729. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  37730. }
  37731. }
  37732. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  37733. if (this._textures.length > 0) {
  37734. for (var i = 0; i < this._textures.length; i++) {
  37735. this._engine._releaseTexture(this._textures.data[i]);
  37736. }
  37737. this._textures.reset();
  37738. }
  37739. this.width = desiredWidth;
  37740. this.height = desiredHeight;
  37741. var textureSize = { width: this.width, height: this.height };
  37742. var textureOptions = {
  37743. generateMipMaps: false,
  37744. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  37745. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  37746. samplingMode: this.renderTargetSamplingMode,
  37747. type: this._textureType
  37748. };
  37749. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  37750. if (this._reusable) {
  37751. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  37752. }
  37753. this.onSizeChangedObservable.notifyObservers(this);
  37754. }
  37755. this._textures.forEach(function (texture) {
  37756. if (texture.samples !== _this.samples) {
  37757. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  37758. }
  37759. });
  37760. if (this.enablePixelPerfectMode) {
  37761. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  37762. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  37763. }
  37764. else {
  37765. this._scaleRatio.copyFromFloats(1, 1);
  37766. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  37767. }
  37768. this.onActivateObservable.notifyObservers(camera);
  37769. // Clear
  37770. if (this.clearColor) {
  37771. this._engine.clear(this.clearColor, true, true, true);
  37772. }
  37773. else {
  37774. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  37775. }
  37776. if (this._reusable) {
  37777. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  37778. }
  37779. };
  37780. Object.defineProperty(PostProcess.prototype, "isSupported", {
  37781. get: function () {
  37782. return this._effect.isSupported;
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. PostProcess.prototype.apply = function () {
  37788. // Check
  37789. if (!this._effect.isReady())
  37790. return null;
  37791. // States
  37792. this._engine.enableEffect(this._effect);
  37793. this._engine.setState(false);
  37794. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37795. this._engine.setDepthBuffer(false);
  37796. this._engine.setDepthWrite(false);
  37797. // Texture
  37798. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  37799. // Parameters
  37800. this._effect.setVector2("scale", this._scaleRatio);
  37801. this.onApplyObservable.notifyObservers(this._effect);
  37802. return this._effect;
  37803. };
  37804. PostProcess.prototype.dispose = function (camera) {
  37805. camera = camera || this._camera;
  37806. if (this._textures.length > 0) {
  37807. for (var i = 0; i < this._textures.length; i++) {
  37808. this._engine._releaseTexture(this._textures.data[i]);
  37809. }
  37810. }
  37811. this._textures.dispose();
  37812. if (!camera) {
  37813. return;
  37814. }
  37815. camera.detachPostProcess(this);
  37816. var index = camera._postProcesses.indexOf(this);
  37817. if (index === 0 && camera._postProcesses.length > 0) {
  37818. this._camera._postProcesses[0].markTextureDirty();
  37819. }
  37820. this.onActivateObservable.clear();
  37821. this.onAfterRenderObservable.clear();
  37822. this.onApplyObservable.clear();
  37823. this.onBeforeRenderObservable.clear();
  37824. this.onSizeChangedObservable.clear();
  37825. };
  37826. return PostProcess;
  37827. }());
  37828. BABYLON.PostProcess = PostProcess;
  37829. })(BABYLON || (BABYLON = {}));
  37830. //# sourceMappingURL=babylon.postProcess.js.map
  37831. var BABYLON;
  37832. (function (BABYLON) {
  37833. var PassPostProcess = (function (_super) {
  37834. __extends(PassPostProcess, _super);
  37835. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  37836. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37837. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  37838. }
  37839. return PassPostProcess;
  37840. }(BABYLON.PostProcess));
  37841. BABYLON.PassPostProcess = PassPostProcess;
  37842. })(BABYLON || (BABYLON = {}));
  37843. //# sourceMappingURL=babylon.passPostProcess.js.map
  37844. var BABYLON;
  37845. (function (BABYLON) {
  37846. /**
  37847. * This is a holder class for the physics joint created by the physics plugin.
  37848. * It holds a set of functions to control the underlying joint.
  37849. */
  37850. var PhysicsJoint = (function () {
  37851. function PhysicsJoint(type, jointData) {
  37852. this.type = type;
  37853. this.jointData = jointData;
  37854. jointData.nativeParams = jointData.nativeParams || {};
  37855. }
  37856. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  37857. get: function () {
  37858. return this._physicsJoint;
  37859. },
  37860. set: function (newJoint) {
  37861. if (this._physicsJoint) {
  37862. //remove from the wolrd
  37863. }
  37864. this._physicsJoint = newJoint;
  37865. },
  37866. enumerable: true,
  37867. configurable: true
  37868. });
  37869. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  37870. set: function (physicsPlugin) {
  37871. this._physicsPlugin = physicsPlugin;
  37872. },
  37873. enumerable: true,
  37874. configurable: true
  37875. });
  37876. /**
  37877. * Execute a function that is physics-plugin specific.
  37878. * @param {Function} func the function that will be executed.
  37879. * It accepts two parameters: the physics world and the physics joint.
  37880. */
  37881. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  37882. func(this._physicsPlugin.world, this._physicsJoint);
  37883. };
  37884. return PhysicsJoint;
  37885. }());
  37886. //TODO check if the native joints are the same
  37887. //Joint Types
  37888. PhysicsJoint.DistanceJoint = 0;
  37889. PhysicsJoint.HingeJoint = 1;
  37890. PhysicsJoint.BallAndSocketJoint = 2;
  37891. PhysicsJoint.WheelJoint = 3;
  37892. PhysicsJoint.SliderJoint = 4;
  37893. //OIMO
  37894. PhysicsJoint.PrismaticJoint = 5;
  37895. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  37896. PhysicsJoint.UniversalJoint = 6;
  37897. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  37898. //Cannon
  37899. //Similar to a Ball-Joint. Different in params
  37900. PhysicsJoint.PointToPointJoint = 8;
  37901. //Cannon only at the moment
  37902. PhysicsJoint.SpringJoint = 9;
  37903. PhysicsJoint.LockJoint = 10;
  37904. BABYLON.PhysicsJoint = PhysicsJoint;
  37905. /**
  37906. * A class representing a physics distance joint.
  37907. */
  37908. var DistanceJoint = (function (_super) {
  37909. __extends(DistanceJoint, _super);
  37910. function DistanceJoint(jointData) {
  37911. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  37912. }
  37913. /**
  37914. * Update the predefined distance.
  37915. */
  37916. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  37917. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  37918. };
  37919. return DistanceJoint;
  37920. }(PhysicsJoint));
  37921. BABYLON.DistanceJoint = DistanceJoint;
  37922. var MotorEnabledJoint = (function (_super) {
  37923. __extends(MotorEnabledJoint, _super);
  37924. function MotorEnabledJoint(type, jointData) {
  37925. return _super.call(this, type, jointData) || this;
  37926. }
  37927. /**
  37928. * Set the motor values.
  37929. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37930. * @param {number} force the force to apply
  37931. * @param {number} maxForce max force for this motor.
  37932. */
  37933. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  37934. this._physicsPlugin.setMotor(this, force, maxForce);
  37935. };
  37936. /**
  37937. * Set the motor's limits.
  37938. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37939. */
  37940. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  37941. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  37942. };
  37943. return MotorEnabledJoint;
  37944. }(PhysicsJoint));
  37945. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  37946. /**
  37947. * This class represents a single hinge physics joint
  37948. */
  37949. var HingeJoint = (function (_super) {
  37950. __extends(HingeJoint, _super);
  37951. function HingeJoint(jointData) {
  37952. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  37953. }
  37954. /**
  37955. * Set the motor values.
  37956. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37957. * @param {number} force the force to apply
  37958. * @param {number} maxForce max force for this motor.
  37959. */
  37960. HingeJoint.prototype.setMotor = function (force, maxForce) {
  37961. this._physicsPlugin.setMotor(this, force, maxForce);
  37962. };
  37963. /**
  37964. * Set the motor's limits.
  37965. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37966. */
  37967. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  37968. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  37969. };
  37970. return HingeJoint;
  37971. }(MotorEnabledJoint));
  37972. BABYLON.HingeJoint = HingeJoint;
  37973. /**
  37974. * This class represents a dual hinge physics joint (same as wheel joint)
  37975. */
  37976. var Hinge2Joint = (function (_super) {
  37977. __extends(Hinge2Joint, _super);
  37978. function Hinge2Joint(jointData) {
  37979. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  37980. }
  37981. /**
  37982. * Set the motor values.
  37983. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37984. * @param {number} force the force to apply
  37985. * @param {number} maxForce max force for this motor.
  37986. * @param {motorIndex} the motor's index, 0 or 1.
  37987. */
  37988. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  37989. if (motorIndex === void 0) { motorIndex = 0; }
  37990. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  37991. };
  37992. /**
  37993. * Set the motor limits.
  37994. * Attention, this function is plugin specific. Engines won't react 100% the same.
  37995. * @param {number} upperLimit the upper limit
  37996. * @param {number} lowerLimit lower limit
  37997. * @param {motorIndex} the motor's index, 0 or 1.
  37998. */
  37999. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  38000. if (motorIndex === void 0) { motorIndex = 0; }
  38001. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  38002. };
  38003. return Hinge2Joint;
  38004. }(MotorEnabledJoint));
  38005. BABYLON.Hinge2Joint = Hinge2Joint;
  38006. })(BABYLON || (BABYLON = {}));
  38007. //# sourceMappingURL=babylon.physicsJoint.js.map
  38008. var BABYLON;
  38009. (function (BABYLON) {
  38010. var PhysicsImpostor = (function () {
  38011. function PhysicsImpostor(object, type, _options, _scene) {
  38012. if (_options === void 0) { _options = { mass: 0 }; }
  38013. var _this = this;
  38014. this.object = object;
  38015. this.type = type;
  38016. this._options = _options;
  38017. this._scene = _scene;
  38018. this._bodyUpdateRequired = false;
  38019. this._onBeforePhysicsStepCallbacks = new Array();
  38020. this._onAfterPhysicsStepCallbacks = new Array();
  38021. this._onPhysicsCollideCallbacks = [];
  38022. this._deltaPosition = BABYLON.Vector3.Zero();
  38023. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  38024. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  38025. /**
  38026. * this function is executed by the physics engine.
  38027. */
  38028. this.beforeStep = function () {
  38029. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  38030. //conjugate deltaRotation
  38031. if (_this._deltaRotationConjugated) {
  38032. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  38033. }
  38034. else {
  38035. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  38036. }
  38037. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  38038. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  38039. func(_this);
  38040. });
  38041. };
  38042. /**
  38043. * this function is executed by the physics engine.
  38044. */
  38045. this.afterStep = function () {
  38046. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  38047. func(_this);
  38048. });
  38049. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  38050. _this.object.position.addInPlace(_this._deltaPosition);
  38051. if (_this._deltaRotation) {
  38052. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  38053. }
  38054. };
  38055. /**
  38056. * Legacy collision detection event support
  38057. */
  38058. this.onCollideEvent = null;
  38059. //event and body object due to cannon's event-based architecture.
  38060. this.onCollide = function (e) {
  38061. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  38062. return;
  38063. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  38064. if (otherImpostor) {
  38065. // Legacy collision detection event support
  38066. if (_this.onCollideEvent) {
  38067. _this.onCollideEvent(_this, otherImpostor);
  38068. }
  38069. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  38070. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  38071. }).forEach(function (obj) {
  38072. obj.callback(_this, otherImpostor);
  38073. });
  38074. }
  38075. };
  38076. //sanity check!
  38077. if (!this.object) {
  38078. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  38079. return;
  38080. }
  38081. //legacy support for old syntax.
  38082. if (!this._scene && object.getScene) {
  38083. this._scene = object.getScene();
  38084. }
  38085. this._physicsEngine = this._scene.getPhysicsEngine();
  38086. if (!this._physicsEngine) {
  38087. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  38088. }
  38089. else {
  38090. //set the object's quaternion, if not set
  38091. if (!this.object.rotationQuaternion) {
  38092. if (this.object.rotation) {
  38093. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  38094. }
  38095. else {
  38096. this.object.rotationQuaternion = new BABYLON.Quaternion();
  38097. }
  38098. }
  38099. //default options params
  38100. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  38101. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  38102. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  38103. this._joints = [];
  38104. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  38105. if (!this.object.parent) {
  38106. this._init();
  38107. }
  38108. }
  38109. }
  38110. /**
  38111. * This function will completly initialize this impostor.
  38112. * It will create a new body - but only if this mesh has no parent.
  38113. * If it has, this impostor will not be used other than to define the impostor
  38114. * of the child mesh.
  38115. */
  38116. PhysicsImpostor.prototype._init = function () {
  38117. this._physicsEngine.removeImpostor(this);
  38118. this.physicsBody = null;
  38119. this._parent = this._parent || this._getPhysicsParent();
  38120. if (!this.parent) {
  38121. this._physicsEngine.addImpostor(this);
  38122. }
  38123. };
  38124. PhysicsImpostor.prototype._getPhysicsParent = function () {
  38125. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  38126. var parentMesh = this.object.parent;
  38127. return parentMesh.physicsImpostor;
  38128. }
  38129. return;
  38130. };
  38131. /**
  38132. * Should a new body be generated.
  38133. */
  38134. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  38135. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  38136. };
  38137. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  38138. this.forceUpdate();
  38139. };
  38140. /**
  38141. * Force a regeneration of this or the parent's impostor's body.
  38142. * Use under cautious - This will remove all joints already implemented.
  38143. */
  38144. PhysicsImpostor.prototype.forceUpdate = function () {
  38145. this._init();
  38146. if (this.parent) {
  38147. this.parent.forceUpdate();
  38148. }
  38149. };
  38150. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  38151. /*public get mesh(): AbstractMesh {
  38152. return this._mesh;
  38153. }*/
  38154. /**
  38155. * Gets the body that holds this impostor. Either its own, or its parent.
  38156. */
  38157. get: function () {
  38158. return this._parent ? this._parent.physicsBody : this._physicsBody;
  38159. },
  38160. /**
  38161. * Set the physics body. Used mainly by the physics engine/plugin
  38162. */
  38163. set: function (physicsBody) {
  38164. if (this._physicsBody) {
  38165. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  38166. }
  38167. this._physicsBody = physicsBody;
  38168. this.resetUpdateFlags();
  38169. },
  38170. enumerable: true,
  38171. configurable: true
  38172. });
  38173. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  38174. get: function () {
  38175. return this._parent;
  38176. },
  38177. set: function (value) {
  38178. this._parent = value;
  38179. },
  38180. enumerable: true,
  38181. configurable: true
  38182. });
  38183. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  38184. this._bodyUpdateRequired = false;
  38185. };
  38186. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  38187. if (this.object.getBoundingInfo) {
  38188. var q = this.object.rotationQuaternion;
  38189. //reset rotation
  38190. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  38191. //calculate the world matrix with no rotation
  38192. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  38193. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  38194. //bring back the rotation
  38195. this.object.rotationQuaternion = q;
  38196. //calculate the world matrix with the new rotation
  38197. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  38198. return size;
  38199. }
  38200. else {
  38201. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  38202. }
  38203. };
  38204. PhysicsImpostor.prototype.getObjectCenter = function () {
  38205. if (this.object.getBoundingInfo) {
  38206. return this.object.getBoundingInfo().boundingBox.centerWorld;
  38207. }
  38208. else {
  38209. return this.object.position;
  38210. }
  38211. };
  38212. /**
  38213. * Get a specific parametes from the options parameter.
  38214. */
  38215. PhysicsImpostor.prototype.getParam = function (paramName) {
  38216. return this._options[paramName];
  38217. };
  38218. /**
  38219. * Sets a specific parameter in the options given to the physics plugin
  38220. */
  38221. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  38222. this._options[paramName] = value;
  38223. this._bodyUpdateRequired = true;
  38224. };
  38225. /**
  38226. * Specifically change the body's mass option. Won't recreate the physics body object
  38227. */
  38228. PhysicsImpostor.prototype.setMass = function (mass) {
  38229. if (this.getParam("mass") !== mass) {
  38230. this.setParam("mass", mass);
  38231. }
  38232. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  38233. };
  38234. PhysicsImpostor.prototype.getLinearVelocity = function () {
  38235. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  38236. };
  38237. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  38238. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  38239. };
  38240. PhysicsImpostor.prototype.getAngularVelocity = function () {
  38241. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  38242. };
  38243. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  38244. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  38245. };
  38246. /**
  38247. * Execute a function with the physics plugin native code.
  38248. * Provide a function the will have two variables - the world object and the physics body object.
  38249. */
  38250. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  38251. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  38252. };
  38253. /**
  38254. * Register a function that will be executed before the physics world is stepping forward.
  38255. */
  38256. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  38257. this._onBeforePhysicsStepCallbacks.push(func);
  38258. };
  38259. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  38260. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  38261. if (index > -1) {
  38262. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  38263. }
  38264. else {
  38265. BABYLON.Tools.Warn("Function to remove was not found");
  38266. }
  38267. };
  38268. /**
  38269. * Register a function that will be executed after the physics step
  38270. */
  38271. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  38272. this._onAfterPhysicsStepCallbacks.push(func);
  38273. };
  38274. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  38275. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  38276. if (index > -1) {
  38277. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  38278. }
  38279. else {
  38280. BABYLON.Tools.Warn("Function to remove was not found");
  38281. }
  38282. };
  38283. /**
  38284. * register a function that will be executed when this impostor collides against a different body.
  38285. */
  38286. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  38287. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  38288. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  38289. };
  38290. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  38291. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  38292. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  38293. if (index > -1) {
  38294. this._onPhysicsCollideCallbacks.splice(index, 1);
  38295. }
  38296. else {
  38297. BABYLON.Tools.Warn("Function to remove was not found");
  38298. }
  38299. };
  38300. /**
  38301. * Apply a force
  38302. */
  38303. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  38304. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  38305. };
  38306. /**
  38307. * Apply an impulse
  38308. */
  38309. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  38310. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  38311. };
  38312. /**
  38313. * A help function to create a joint.
  38314. */
  38315. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  38316. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  38317. this.addJoint(otherImpostor, joint);
  38318. };
  38319. /**
  38320. * Add a joint to this impostor with a different impostor.
  38321. */
  38322. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  38323. this._joints.push({
  38324. otherImpostor: otherImpostor,
  38325. joint: joint
  38326. });
  38327. this._physicsEngine.addJoint(this, otherImpostor, joint);
  38328. };
  38329. /**
  38330. * Will keep this body still, in a sleep mode.
  38331. */
  38332. PhysicsImpostor.prototype.sleep = function () {
  38333. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  38334. };
  38335. /**
  38336. * Wake the body up.
  38337. */
  38338. PhysicsImpostor.prototype.wakeUp = function () {
  38339. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  38340. };
  38341. PhysicsImpostor.prototype.clone = function (newObject) {
  38342. if (!newObject)
  38343. return null;
  38344. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  38345. };
  38346. PhysicsImpostor.prototype.dispose = function () {
  38347. var _this = this;
  38348. //no dispose if no physics engine is available.
  38349. if (!this._physicsEngine) {
  38350. return;
  38351. }
  38352. this._joints.forEach(function (j) {
  38353. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  38354. });
  38355. //dispose the physics body
  38356. this._physicsEngine.removeImpostor(this);
  38357. if (this.parent) {
  38358. this.parent.forceUpdate();
  38359. }
  38360. else {
  38361. /*this._object.getChildMeshes().forEach(function(mesh) {
  38362. if (mesh.physicsImpostor) {
  38363. if (disposeChildren) {
  38364. mesh.physicsImpostor.dispose();
  38365. mesh.physicsImpostor = null;
  38366. }
  38367. }
  38368. })*/
  38369. }
  38370. };
  38371. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  38372. this._deltaPosition.copyFrom(position);
  38373. };
  38374. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  38375. if (!this._deltaRotation) {
  38376. this._deltaRotation = new BABYLON.Quaternion();
  38377. }
  38378. this._deltaRotation.copyFrom(rotation);
  38379. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  38380. };
  38381. return PhysicsImpostor;
  38382. }());
  38383. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  38384. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  38385. //Impostor types
  38386. PhysicsImpostor.NoImpostor = 0;
  38387. PhysicsImpostor.SphereImpostor = 1;
  38388. PhysicsImpostor.BoxImpostor = 2;
  38389. PhysicsImpostor.PlaneImpostor = 3;
  38390. PhysicsImpostor.MeshImpostor = 4;
  38391. PhysicsImpostor.CylinderImpostor = 7;
  38392. PhysicsImpostor.ParticleImpostor = 8;
  38393. PhysicsImpostor.HeightmapImpostor = 9;
  38394. BABYLON.PhysicsImpostor = PhysicsImpostor;
  38395. })(BABYLON || (BABYLON = {}));
  38396. //# sourceMappingURL=babylon.physicsImpostor.js.map
  38397. var BABYLON;
  38398. (function (BABYLON) {
  38399. var PhysicsEngine = (function () {
  38400. function PhysicsEngine(gravity, _physicsPlugin) {
  38401. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  38402. this._physicsPlugin = _physicsPlugin;
  38403. //new methods and parameters
  38404. this._impostors = [];
  38405. this._joints = [];
  38406. if (!this._physicsPlugin.isSupported()) {
  38407. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  38408. + "Please make sure it is included.");
  38409. }
  38410. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  38411. this.setGravity(gravity);
  38412. this.setTimeStep();
  38413. }
  38414. PhysicsEngine.prototype.setGravity = function (gravity) {
  38415. this.gravity = gravity;
  38416. this._physicsPlugin.setGravity(this.gravity);
  38417. };
  38418. /**
  38419. * Set the time step of the physics engine.
  38420. * default is 1/60.
  38421. * To slow it down, enter 1/600 for example.
  38422. * To speed it up, 1/30
  38423. * @param {number} newTimeStep the new timestep to apply to this world.
  38424. */
  38425. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  38426. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  38427. this._physicsPlugin.setTimeStep(newTimeStep);
  38428. };
  38429. PhysicsEngine.prototype.dispose = function () {
  38430. this._impostors.forEach(function (impostor) {
  38431. impostor.dispose();
  38432. });
  38433. this._physicsPlugin.dispose();
  38434. };
  38435. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  38436. return this._physicsPlugin.name;
  38437. };
  38438. /**
  38439. * Adding a new impostor for the impostor tracking.
  38440. * This will be done by the impostor itself.
  38441. * @param {PhysicsImpostor} impostor the impostor to add
  38442. */
  38443. PhysicsEngine.prototype.addImpostor = function (impostor) {
  38444. impostor.uniqueId = this._impostors.push(impostor);
  38445. //if no parent, generate the body
  38446. if (!impostor.parent) {
  38447. this._physicsPlugin.generatePhysicsBody(impostor);
  38448. }
  38449. };
  38450. /**
  38451. * Remove an impostor from the engine.
  38452. * This impostor and its mesh will not longer be updated by the physics engine.
  38453. * @param {PhysicsImpostor} impostor the impostor to remove
  38454. */
  38455. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  38456. var index = this._impostors.indexOf(impostor);
  38457. if (index > -1) {
  38458. var removed = this._impostors.splice(index, 1);
  38459. //Is it needed?
  38460. if (removed.length) {
  38461. //this will also remove it from the world.
  38462. removed[0].physicsBody = null;
  38463. }
  38464. }
  38465. };
  38466. /**
  38467. * Add a joint to the physics engine
  38468. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  38469. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  38470. * @param {PhysicsJoint} the joint that will connect both impostors.
  38471. */
  38472. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  38473. var impostorJoint = {
  38474. mainImpostor: mainImpostor,
  38475. connectedImpostor: connectedImpostor,
  38476. joint: joint
  38477. };
  38478. joint.physicsPlugin = this._physicsPlugin;
  38479. this._joints.push(impostorJoint);
  38480. this._physicsPlugin.generateJoint(impostorJoint);
  38481. };
  38482. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  38483. var matchingJoints = this._joints.filter(function (impostorJoint) {
  38484. return (impostorJoint.connectedImpostor === connectedImpostor
  38485. && impostorJoint.joint === joint
  38486. && impostorJoint.mainImpostor === mainImpostor);
  38487. });
  38488. if (matchingJoints.length) {
  38489. this._physicsPlugin.removeJoint(matchingJoints[0]);
  38490. //TODO remove it from the list as well
  38491. }
  38492. };
  38493. /**
  38494. * Called by the scene. no need to call it.
  38495. */
  38496. PhysicsEngine.prototype._step = function (delta) {
  38497. var _this = this;
  38498. //check if any mesh has no body / requires an update
  38499. this._impostors.forEach(function (impostor) {
  38500. if (impostor.isBodyInitRequired()) {
  38501. _this._physicsPlugin.generatePhysicsBody(impostor);
  38502. }
  38503. });
  38504. if (delta > 0.1) {
  38505. delta = 0.1;
  38506. }
  38507. else if (delta <= 0) {
  38508. delta = 1.0 / 60.0;
  38509. }
  38510. this._physicsPlugin.executeStep(delta, this._impostors);
  38511. };
  38512. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  38513. return this._physicsPlugin;
  38514. };
  38515. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  38516. for (var i = 0; i < this._impostors.length; ++i) {
  38517. if (this._impostors[i].object === object) {
  38518. return this._impostors[i];
  38519. }
  38520. }
  38521. };
  38522. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  38523. for (var i = 0; i < this._impostors.length; ++i) {
  38524. if (this._impostors[i].physicsBody === body) {
  38525. return this._impostors[i];
  38526. }
  38527. }
  38528. };
  38529. return PhysicsEngine;
  38530. }());
  38531. // Statics
  38532. PhysicsEngine.Epsilon = 0.001;
  38533. BABYLON.PhysicsEngine = PhysicsEngine;
  38534. })(BABYLON || (BABYLON = {}));
  38535. //# sourceMappingURL=babylon.physicsEngine.js.map
  38536. var BABYLON;
  38537. (function (BABYLON) {
  38538. var VertexData = (function () {
  38539. function VertexData() {
  38540. }
  38541. VertexData.prototype.set = function (data, kind) {
  38542. switch (kind) {
  38543. case BABYLON.VertexBuffer.PositionKind:
  38544. this.positions = data;
  38545. break;
  38546. case BABYLON.VertexBuffer.NormalKind:
  38547. this.normals = data;
  38548. break;
  38549. case BABYLON.VertexBuffer.TangentKind:
  38550. this.tangents = data;
  38551. break;
  38552. case BABYLON.VertexBuffer.UVKind:
  38553. this.uvs = data;
  38554. break;
  38555. case BABYLON.VertexBuffer.UV2Kind:
  38556. this.uvs2 = data;
  38557. break;
  38558. case BABYLON.VertexBuffer.UV3Kind:
  38559. this.uvs3 = data;
  38560. break;
  38561. case BABYLON.VertexBuffer.UV4Kind:
  38562. this.uvs4 = data;
  38563. break;
  38564. case BABYLON.VertexBuffer.UV5Kind:
  38565. this.uvs5 = data;
  38566. break;
  38567. case BABYLON.VertexBuffer.UV6Kind:
  38568. this.uvs6 = data;
  38569. break;
  38570. case BABYLON.VertexBuffer.ColorKind:
  38571. this.colors = data;
  38572. break;
  38573. case BABYLON.VertexBuffer.MatricesIndicesKind:
  38574. this.matricesIndices = data;
  38575. break;
  38576. case BABYLON.VertexBuffer.MatricesWeightsKind:
  38577. this.matricesWeights = data;
  38578. break;
  38579. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  38580. this.matricesIndicesExtra = data;
  38581. break;
  38582. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  38583. this.matricesWeightsExtra = data;
  38584. break;
  38585. }
  38586. };
  38587. /**
  38588. * Associates the vertexData to the passed Mesh.
  38589. * Sets it as updatable or not (default `false`).
  38590. * Returns the VertexData.
  38591. */
  38592. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  38593. this._applyTo(mesh, updatable);
  38594. return this;
  38595. };
  38596. /**
  38597. * Associates the vertexData to the passed Geometry.
  38598. * Sets it as updatable or not (default `false`).
  38599. * Returns the VertexData.
  38600. */
  38601. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38602. this._applyTo(geometry, updatable);
  38603. return this;
  38604. };
  38605. /**
  38606. * Updates the associated mesh.
  38607. * Returns the VertexData.
  38608. */
  38609. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38610. this._update(mesh);
  38611. return this;
  38612. };
  38613. /**
  38614. * Updates the associated geometry.
  38615. * Returns the VertexData.
  38616. */
  38617. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38618. this._update(geometry);
  38619. return this;
  38620. };
  38621. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38622. if (this.positions) {
  38623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38624. }
  38625. if (this.normals) {
  38626. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38627. }
  38628. if (this.tangents) {
  38629. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38630. }
  38631. if (this.uvs) {
  38632. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38633. }
  38634. if (this.uvs2) {
  38635. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38636. }
  38637. if (this.uvs3) {
  38638. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38639. }
  38640. if (this.uvs4) {
  38641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38642. }
  38643. if (this.uvs5) {
  38644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38645. }
  38646. if (this.uvs6) {
  38647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38648. }
  38649. if (this.colors) {
  38650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38651. }
  38652. if (this.matricesIndices) {
  38653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38654. }
  38655. if (this.matricesWeights) {
  38656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38657. }
  38658. if (this.matricesIndicesExtra) {
  38659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38660. }
  38661. if (this.matricesWeightsExtra) {
  38662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38663. }
  38664. if (this.indices) {
  38665. meshOrGeometry.setIndices(this.indices);
  38666. }
  38667. return this;
  38668. };
  38669. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38670. if (this.positions) {
  38671. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38672. }
  38673. if (this.normals) {
  38674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38675. }
  38676. if (this.tangents) {
  38677. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38678. }
  38679. if (this.uvs) {
  38680. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38681. }
  38682. if (this.uvs2) {
  38683. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38684. }
  38685. if (this.uvs3) {
  38686. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38687. }
  38688. if (this.uvs4) {
  38689. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38690. }
  38691. if (this.uvs5) {
  38692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38693. }
  38694. if (this.uvs6) {
  38695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38696. }
  38697. if (this.colors) {
  38698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38699. }
  38700. if (this.matricesIndices) {
  38701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38702. }
  38703. if (this.matricesWeights) {
  38704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38705. }
  38706. if (this.matricesIndicesExtra) {
  38707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38708. }
  38709. if (this.matricesWeightsExtra) {
  38710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38711. }
  38712. if (this.indices) {
  38713. meshOrGeometry.setIndices(this.indices);
  38714. }
  38715. return this;
  38716. };
  38717. /**
  38718. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  38719. * Returns the VertexData.
  38720. */
  38721. VertexData.prototype.transform = function (matrix) {
  38722. var transformed = BABYLON.Vector3.Zero();
  38723. var index;
  38724. if (this.positions) {
  38725. var position = BABYLON.Vector3.Zero();
  38726. for (index = 0; index < this.positions.length; index += 3) {
  38727. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38728. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38729. this.positions[index] = transformed.x;
  38730. this.positions[index + 1] = transformed.y;
  38731. this.positions[index + 2] = transformed.z;
  38732. }
  38733. }
  38734. if (this.normals) {
  38735. var normal = BABYLON.Vector3.Zero();
  38736. for (index = 0; index < this.normals.length; index += 3) {
  38737. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38738. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38739. this.normals[index] = transformed.x;
  38740. this.normals[index + 1] = transformed.y;
  38741. this.normals[index + 2] = transformed.z;
  38742. }
  38743. }
  38744. if (this.tangents) {
  38745. var tangent = BABYLON.Vector4.Zero();
  38746. var tangentTransformed = BABYLON.Vector4.Zero();
  38747. for (index = 0; index < this.tangents.length; index += 4) {
  38748. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38749. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38750. this.tangents[index] = tangentTransformed.x;
  38751. this.tangents[index + 1] = tangentTransformed.y;
  38752. this.tangents[index + 2] = tangentTransformed.z;
  38753. this.tangents[index + 3] = tangentTransformed.w;
  38754. }
  38755. }
  38756. return this;
  38757. };
  38758. /**
  38759. * Merges the passed VertexData into the current one.
  38760. * Returns the modified VertexData.
  38761. */
  38762. VertexData.prototype.merge = function (other) {
  38763. if (other.indices) {
  38764. if (!this.indices) {
  38765. this.indices = [];
  38766. }
  38767. var offset = this.positions ? this.positions.length / 3 : 0;
  38768. for (var index = 0; index < other.indices.length; index++) {
  38769. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  38770. this.indices.push(other.indices[index] + offset);
  38771. }
  38772. }
  38773. this.positions = this._mergeElement(this.positions, other.positions);
  38774. this.normals = this._mergeElement(this.normals, other.normals);
  38775. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38776. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38777. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38778. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38779. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38780. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38781. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38782. this.colors = this._mergeElement(this.colors, other.colors);
  38783. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38784. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38785. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38786. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38787. return this;
  38788. };
  38789. VertexData.prototype._mergeElement = function (source, other) {
  38790. if (!other)
  38791. return source;
  38792. if (!source)
  38793. return other;
  38794. var len = other.length + source.length;
  38795. var isSrcTypedArray = source instanceof Float32Array;
  38796. var isOthTypedArray = other instanceof Float32Array;
  38797. // use non-loop method when the source is Float32Array
  38798. if (isSrcTypedArray) {
  38799. var ret32 = new Float32Array(len);
  38800. ret32.set(source);
  38801. ret32.set(other, source.length);
  38802. return ret32;
  38803. // source is number[], when other is also use concat
  38804. }
  38805. else if (!isOthTypedArray) {
  38806. return source.concat(other);
  38807. // source is a number[], but other is a Float32Array, loop required
  38808. }
  38809. else {
  38810. var ret = source.slice(0); // copy source to a separate array
  38811. for (var i = 0, len = other.length; i < len; i++) {
  38812. ret.push(other[i]);
  38813. }
  38814. return ret;
  38815. }
  38816. };
  38817. /**
  38818. * Serializes the VertexData.
  38819. * Returns a serialized object.
  38820. */
  38821. VertexData.prototype.serialize = function () {
  38822. var serializationObject = this.serialize();
  38823. if (this.positions) {
  38824. serializationObject.positions = this.positions;
  38825. }
  38826. if (this.normals) {
  38827. serializationObject.normals = this.normals;
  38828. }
  38829. if (this.tangents) {
  38830. serializationObject.tangents = this.tangents;
  38831. }
  38832. if (this.uvs) {
  38833. serializationObject.uvs = this.uvs;
  38834. }
  38835. if (this.uvs2) {
  38836. serializationObject.uvs2 = this.uvs2;
  38837. }
  38838. if (this.uvs3) {
  38839. serializationObject.uvs3 = this.uvs3;
  38840. }
  38841. if (this.uvs4) {
  38842. serializationObject.uvs4 = this.uvs4;
  38843. }
  38844. if (this.uvs5) {
  38845. serializationObject.uvs5 = this.uvs5;
  38846. }
  38847. if (this.uvs6) {
  38848. serializationObject.uvs6 = this.uvs6;
  38849. }
  38850. if (this.colors) {
  38851. serializationObject.colors = this.colors;
  38852. }
  38853. if (this.matricesIndices) {
  38854. serializationObject.matricesIndices = this.matricesIndices;
  38855. serializationObject.matricesIndices._isExpanded = true;
  38856. }
  38857. if (this.matricesWeights) {
  38858. serializationObject.matricesWeights = this.matricesWeights;
  38859. }
  38860. if (this.matricesIndicesExtra) {
  38861. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38862. serializationObject.matricesIndicesExtra._isExpanded = true;
  38863. }
  38864. if (this.matricesWeightsExtra) {
  38865. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38866. }
  38867. serializationObject.indices = this.indices;
  38868. return serializationObject;
  38869. };
  38870. // Statics
  38871. /**
  38872. * Returns the object VertexData associated to the passed mesh.
  38873. */
  38874. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  38875. return VertexData._ExtractFrom(mesh, copyWhenShared);
  38876. };
  38877. /**
  38878. * Returns the object VertexData associated to the passed geometry.
  38879. */
  38880. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  38881. return VertexData._ExtractFrom(geometry, copyWhenShared);
  38882. };
  38883. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  38884. var result = new VertexData();
  38885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38886. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  38887. }
  38888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38889. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  38890. }
  38891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38892. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  38893. }
  38894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38895. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  38896. }
  38897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38898. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  38899. }
  38900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38901. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  38902. }
  38903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38904. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  38905. }
  38906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38907. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  38908. }
  38909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38910. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  38911. }
  38912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38913. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  38914. }
  38915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38916. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  38917. }
  38918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38919. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  38920. }
  38921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38922. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  38923. }
  38924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38925. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  38926. }
  38927. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  38928. return result;
  38929. };
  38930. /**
  38931. * Creates the vertexData of the Ribbon.
  38932. */
  38933. VertexData.CreateRibbon = function (options) {
  38934. var pathArray = options.pathArray;
  38935. var closeArray = options.closeArray || false;
  38936. var closePath = options.closePath || false;
  38937. var invertUV = options.invertUV || false;
  38938. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38939. var offset = options.offset || defaultOffset;
  38940. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38941. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38942. var customUV = options.uvs;
  38943. var customColors = options.colors;
  38944. var positions = [];
  38945. var indices = [];
  38946. var normals = [];
  38947. var uvs = [];
  38948. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38949. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38950. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38951. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38952. var minlg; // minimal length among all paths from pathArray
  38953. var lg = []; // array of path lengths : nb of vertex per path
  38954. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38955. var p; // path iterator
  38956. var i; // point iterator
  38957. var j; // point iterator
  38958. // if single path in pathArray
  38959. if (pathArray.length < 2) {
  38960. var ar1 = [];
  38961. var ar2 = [];
  38962. for (i = 0; i < pathArray[0].length - offset; i++) {
  38963. ar1.push(pathArray[0][i]);
  38964. ar2.push(pathArray[0][i + offset]);
  38965. }
  38966. pathArray = [ar1, ar2];
  38967. }
  38968. // positions and horizontal distances (u)
  38969. var idc = 0;
  38970. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38971. var path;
  38972. var l;
  38973. minlg = pathArray[0].length;
  38974. var vectlg;
  38975. var dist;
  38976. for (p = 0; p < pathArray.length; p++) {
  38977. uTotalDistance[p] = 0;
  38978. us[p] = [0];
  38979. path = pathArray[p];
  38980. l = path.length;
  38981. minlg = (minlg < l) ? minlg : l;
  38982. j = 0;
  38983. while (j < l) {
  38984. positions.push(path[j].x, path[j].y, path[j].z);
  38985. if (j > 0) {
  38986. vectlg = path[j].subtract(path[j - 1]).length();
  38987. dist = vectlg + uTotalDistance[p];
  38988. us[p].push(dist);
  38989. uTotalDistance[p] = dist;
  38990. }
  38991. j++;
  38992. }
  38993. if (closePath) {
  38994. j--;
  38995. positions.push(path[0].x, path[0].y, path[0].z);
  38996. vectlg = path[j].subtract(path[0]).length();
  38997. dist = vectlg + uTotalDistance[p];
  38998. us[p].push(dist);
  38999. uTotalDistance[p] = dist;
  39000. }
  39001. lg[p] = l + closePathCorr;
  39002. idx[p] = idc;
  39003. idc += (l + closePathCorr);
  39004. }
  39005. // vertical distances (v)
  39006. var path1;
  39007. var path2;
  39008. var vertex1;
  39009. var vertex2;
  39010. for (i = 0; i < minlg + closePathCorr; i++) {
  39011. vTotalDistance[i] = 0;
  39012. vs[i] = [0];
  39013. for (p = 0; p < pathArray.length - 1; p++) {
  39014. path1 = pathArray[p];
  39015. path2 = pathArray[p + 1];
  39016. if (i === minlg) {
  39017. vertex1 = path1[0];
  39018. vertex2 = path2[0];
  39019. }
  39020. else {
  39021. vertex1 = path1[i];
  39022. vertex2 = path2[i];
  39023. }
  39024. vectlg = vertex2.subtract(vertex1).length();
  39025. dist = vectlg + vTotalDistance[i];
  39026. vs[i].push(dist);
  39027. vTotalDistance[i] = dist;
  39028. }
  39029. if (closeArray) {
  39030. path1 = pathArray[p];
  39031. path2 = pathArray[0];
  39032. if (i === minlg) {
  39033. vertex2 = path2[0];
  39034. }
  39035. vectlg = vertex2.subtract(vertex1).length();
  39036. dist = vectlg + vTotalDistance[i];
  39037. vTotalDistance[i] = dist;
  39038. }
  39039. }
  39040. // uvs
  39041. var u;
  39042. var v;
  39043. if (customUV) {
  39044. for (p = 0; p < customUV.length; p++) {
  39045. uvs.push(customUV[p].x, customUV[p].y);
  39046. }
  39047. }
  39048. else {
  39049. for (p = 0; p < pathArray.length; p++) {
  39050. for (i = 0; i < minlg + closePathCorr; i++) {
  39051. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  39052. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  39053. if (invertUV) {
  39054. uvs.push(v, u);
  39055. }
  39056. else {
  39057. uvs.push(u, v);
  39058. }
  39059. }
  39060. }
  39061. }
  39062. // indices
  39063. p = 0; // path index
  39064. var pi = 0; // positions array index
  39065. var l1 = lg[p] - 1; // path1 length
  39066. var l2 = lg[p + 1] - 1; // path2 length
  39067. var min = (l1 < l2) ? l1 : l2; // current path stop index
  39068. var shft = idx[1] - idx[0]; // shift
  39069. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  39070. while (pi <= min && p < path1nb) {
  39071. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  39072. indices.push(pi, pi + shft, pi + 1);
  39073. indices.push(pi + shft + 1, pi + 1, pi + shft);
  39074. pi += 1;
  39075. if (pi === min) {
  39076. p++;
  39077. if (p === lg.length - 1) {
  39078. shft = idx[0] - idx[p];
  39079. l1 = lg[p] - 1;
  39080. l2 = lg[0] - 1;
  39081. }
  39082. else {
  39083. shft = idx[p + 1] - idx[p];
  39084. l1 = lg[p] - 1;
  39085. l2 = lg[p + 1] - 1;
  39086. }
  39087. pi = idx[p];
  39088. min = (l1 < l2) ? l1 + pi : l2 + pi;
  39089. }
  39090. }
  39091. // normals
  39092. VertexData.ComputeNormals(positions, indices, normals);
  39093. if (closePath) {
  39094. var indexFirst = 0;
  39095. var indexLast = 0;
  39096. for (p = 0; p < pathArray.length; p++) {
  39097. indexFirst = idx[p] * 3;
  39098. if (p + 1 < pathArray.length) {
  39099. indexLast = (idx[p + 1] - 1) * 3;
  39100. }
  39101. else {
  39102. indexLast = normals.length - 3;
  39103. }
  39104. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  39105. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  39106. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  39107. normals[indexLast] = normals[indexFirst];
  39108. normals[indexLast + 1] = normals[indexFirst + 1];
  39109. normals[indexLast + 2] = normals[indexFirst + 2];
  39110. }
  39111. }
  39112. // sides
  39113. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39114. // Colors
  39115. if (customColors) {
  39116. var colors = new Float32Array(customColors.length * 4);
  39117. for (var c = 0; c < customColors.length; c++) {
  39118. colors[c * 4] = customColors[c].r;
  39119. colors[c * 4 + 1] = customColors[c].g;
  39120. colors[c * 4 + 2] = customColors[c].b;
  39121. colors[c * 4 + 3] = customColors[c].a;
  39122. }
  39123. }
  39124. // Result
  39125. var vertexData = new VertexData();
  39126. var positions32 = new Float32Array(positions);
  39127. var normals32 = new Float32Array(normals);
  39128. var uvs32 = new Float32Array(uvs);
  39129. vertexData.indices = indices;
  39130. vertexData.positions = positions32;
  39131. vertexData.normals = normals32;
  39132. vertexData.uvs = uvs32;
  39133. if (customColors) {
  39134. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  39135. }
  39136. if (closePath) {
  39137. vertexData._idx = idx;
  39138. }
  39139. return vertexData;
  39140. };
  39141. /**
  39142. * Creates the VertexData of the Box.
  39143. */
  39144. VertexData.CreateBox = function (options) {
  39145. var normalsSource = [
  39146. new BABYLON.Vector3(0, 0, 1),
  39147. new BABYLON.Vector3(0, 0, -1),
  39148. new BABYLON.Vector3(1, 0, 0),
  39149. new BABYLON.Vector3(-1, 0, 0),
  39150. new BABYLON.Vector3(0, 1, 0),
  39151. new BABYLON.Vector3(0, -1, 0)
  39152. ];
  39153. var indices = [];
  39154. var positions = [];
  39155. var normals = [];
  39156. var uvs = [];
  39157. var width = options.width || options.size || 1;
  39158. var height = options.height || options.size || 1;
  39159. var depth = options.depth || options.size || 1;
  39160. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39161. var faceUV = options.faceUV || new Array(6);
  39162. var faceColors = options.faceColors;
  39163. var colors = [];
  39164. // default face colors and UV if undefined
  39165. for (var f = 0; f < 6; f++) {
  39166. if (faceUV[f] === undefined) {
  39167. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39168. }
  39169. if (faceColors && faceColors[f] === undefined) {
  39170. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39171. }
  39172. }
  39173. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  39174. // Create each face in turn.
  39175. for (var index = 0; index < normalsSource.length; index++) {
  39176. var normal = normalsSource[index];
  39177. // Get two vectors perpendicular to the face normal and to each other.
  39178. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  39179. var side2 = BABYLON.Vector3.Cross(normal, side1);
  39180. // Six indices (two triangles) per face.
  39181. var verticesLength = positions.length / 3;
  39182. indices.push(verticesLength);
  39183. indices.push(verticesLength + 1);
  39184. indices.push(verticesLength + 2);
  39185. indices.push(verticesLength);
  39186. indices.push(verticesLength + 2);
  39187. indices.push(verticesLength + 3);
  39188. // Four vertices per face.
  39189. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  39190. positions.push(vertex.x, vertex.y, vertex.z);
  39191. normals.push(normal.x, normal.y, normal.z);
  39192. uvs.push(faceUV[index].z, faceUV[index].w);
  39193. if (faceColors) {
  39194. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39195. }
  39196. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  39197. positions.push(vertex.x, vertex.y, vertex.z);
  39198. normals.push(normal.x, normal.y, normal.z);
  39199. uvs.push(faceUV[index].x, faceUV[index].w);
  39200. if (faceColors) {
  39201. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39202. }
  39203. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  39204. positions.push(vertex.x, vertex.y, vertex.z);
  39205. normals.push(normal.x, normal.y, normal.z);
  39206. uvs.push(faceUV[index].x, faceUV[index].y);
  39207. if (faceColors) {
  39208. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39209. }
  39210. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  39211. positions.push(vertex.x, vertex.y, vertex.z);
  39212. normals.push(normal.x, normal.y, normal.z);
  39213. uvs.push(faceUV[index].z, faceUV[index].y);
  39214. if (faceColors) {
  39215. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  39216. }
  39217. }
  39218. // sides
  39219. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39220. // Result
  39221. var vertexData = new VertexData();
  39222. vertexData.indices = indices;
  39223. vertexData.positions = positions;
  39224. vertexData.normals = normals;
  39225. vertexData.uvs = uvs;
  39226. if (faceColors) {
  39227. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39228. vertexData.colors = totalColors;
  39229. }
  39230. return vertexData;
  39231. };
  39232. /**
  39233. * Creates the VertexData of the Sphere.
  39234. */
  39235. VertexData.CreateSphere = function (options) {
  39236. var segments = options.segments || 32;
  39237. var diameterX = options.diameterX || options.diameter || 1;
  39238. var diameterY = options.diameterY || options.diameter || 1;
  39239. var diameterZ = options.diameterZ || options.diameter || 1;
  39240. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39241. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  39242. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39243. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  39244. var totalZRotationSteps = 2 + segments;
  39245. var totalYRotationSteps = 2 * totalZRotationSteps;
  39246. var indices = [];
  39247. var positions = [];
  39248. var normals = [];
  39249. var uvs = [];
  39250. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  39251. var normalizedZ = zRotationStep / totalZRotationSteps;
  39252. var angleZ = normalizedZ * Math.PI * slice;
  39253. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  39254. var normalizedY = yRotationStep / totalYRotationSteps;
  39255. var angleY = normalizedY * Math.PI * 2 * arc;
  39256. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  39257. var rotationY = BABYLON.Matrix.RotationY(angleY);
  39258. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  39259. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  39260. var vertex = complete.multiply(radius);
  39261. var normal = complete.divide(radius).normalize();
  39262. positions.push(vertex.x, vertex.y, vertex.z);
  39263. normals.push(normal.x, normal.y, normal.z);
  39264. uvs.push(normalizedY, normalizedZ);
  39265. }
  39266. if (zRotationStep > 0) {
  39267. var verticesCount = positions.length / 3;
  39268. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  39269. indices.push((firstIndex));
  39270. indices.push((firstIndex + 1));
  39271. indices.push(firstIndex + totalYRotationSteps + 1);
  39272. indices.push((firstIndex + totalYRotationSteps + 1));
  39273. indices.push((firstIndex + 1));
  39274. indices.push((firstIndex + totalYRotationSteps + 2));
  39275. }
  39276. }
  39277. }
  39278. // Sides
  39279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39280. // Result
  39281. var vertexData = new VertexData();
  39282. vertexData.indices = indices;
  39283. vertexData.positions = positions;
  39284. vertexData.normals = normals;
  39285. vertexData.uvs = uvs;
  39286. return vertexData;
  39287. };
  39288. /**
  39289. * Creates the VertexData of the Cylinder or Cone.
  39290. */
  39291. VertexData.CreateCylinder = function (options) {
  39292. var height = options.height || 2;
  39293. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  39294. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  39295. var tessellation = options.tessellation || 24;
  39296. var subdivisions = options.subdivisions || 1;
  39297. var hasRings = options.hasRings;
  39298. var enclose = options.enclose;
  39299. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39300. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39301. var faceUV = options.faceUV || new Array(3);
  39302. var faceColors = options.faceColors;
  39303. // default face colors and UV if undefined
  39304. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  39305. var ringNb = (hasRings) ? subdivisions : 1;
  39306. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  39307. var f;
  39308. for (f = 0; f < surfaceNb; f++) {
  39309. if (faceColors && faceColors[f] === undefined) {
  39310. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39311. }
  39312. }
  39313. for (f = 0; f < surfaceNb; f++) {
  39314. if (faceUV && faceUV[f] === undefined) {
  39315. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39316. }
  39317. }
  39318. var indices = [];
  39319. var positions = [];
  39320. var normals = [];
  39321. var uvs = [];
  39322. var colors = [];
  39323. var angle_step = Math.PI * 2 * arc / tessellation;
  39324. var angle;
  39325. var h;
  39326. var radius;
  39327. var tan = (diameterBottom - diameterTop) / 2 / height;
  39328. var ringVertex = BABYLON.Vector3.Zero();
  39329. var ringNormal = BABYLON.Vector3.Zero();
  39330. var ringFirstVertex = BABYLON.Vector3.Zero();
  39331. var ringFirstNormal = BABYLON.Vector3.Zero();
  39332. var quadNormal = BABYLON.Vector3.Zero();
  39333. var Y = BABYLON.Axis.Y;
  39334. // positions, normals, uvs
  39335. var i;
  39336. var j;
  39337. var r;
  39338. var ringIdx = 1;
  39339. var s = 1; // surface index
  39340. var cs = 0;
  39341. var v = 0;
  39342. for (i = 0; i <= subdivisions; i++) {
  39343. h = i / subdivisions;
  39344. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  39345. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  39346. for (r = 0; r < ringIdx; r++) {
  39347. if (hasRings) {
  39348. s += r;
  39349. }
  39350. if (enclose) {
  39351. s += 2 * r;
  39352. }
  39353. for (j = 0; j <= tessellation; j++) {
  39354. angle = j * angle_step;
  39355. // position
  39356. ringVertex.x = Math.cos(-angle) * radius;
  39357. ringVertex.y = -height / 2 + h * height;
  39358. ringVertex.z = Math.sin(-angle) * radius;
  39359. // normal
  39360. if (diameterTop === 0 && i === subdivisions) {
  39361. // if no top cap, reuse former normals
  39362. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  39363. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  39364. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  39365. }
  39366. else {
  39367. ringNormal.x = ringVertex.x;
  39368. ringNormal.z = ringVertex.z;
  39369. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  39370. ringNormal.normalize();
  39371. }
  39372. // keep first ring vertex values for enclose
  39373. if (j === 0) {
  39374. ringFirstVertex.copyFrom(ringVertex);
  39375. ringFirstNormal.copyFrom(ringNormal);
  39376. }
  39377. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39378. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  39379. if (hasRings) {
  39380. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  39381. }
  39382. else {
  39383. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  39384. }
  39385. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  39386. if (faceColors) {
  39387. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  39388. }
  39389. }
  39390. // if enclose, add four vertices and their dedicated normals
  39391. if (arc !== 1 && enclose) {
  39392. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39393. positions.push(0, ringVertex.y, 0);
  39394. positions.push(0, ringVertex.y, 0);
  39395. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  39396. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  39397. quadNormal.normalize();
  39398. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39399. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  39400. quadNormal.normalize();
  39401. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39402. if (hasRings) {
  39403. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  39404. }
  39405. else {
  39406. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  39407. }
  39408. uvs.push(faceUV[s + 1].x, v);
  39409. uvs.push(faceUV[s + 1].z, v);
  39410. if (hasRings) {
  39411. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  39412. }
  39413. else {
  39414. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  39415. }
  39416. uvs.push(faceUV[s + 2].x, v);
  39417. uvs.push(faceUV[s + 2].z, v);
  39418. if (faceColors) {
  39419. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39420. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39421. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39422. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39423. }
  39424. }
  39425. if (cs !== s) {
  39426. cs = s;
  39427. }
  39428. }
  39429. }
  39430. // indices
  39431. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39432. var s;
  39433. i = 0;
  39434. for (s = 0; s < subdivisions; s++) {
  39435. for (j = 0; j < tessellation; j++) {
  39436. var i0 = i * (e + 1) + j;
  39437. var i1 = (i + 1) * (e + 1) + j;
  39438. var i2 = i * (e + 1) + (j + 1);
  39439. var i3 = (i + 1) * (e + 1) + (j + 1);
  39440. indices.push(i0, i1, i2);
  39441. indices.push(i3, i2, i1);
  39442. }
  39443. if (arc !== 1 && enclose) {
  39444. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39445. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39446. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39447. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39448. }
  39449. i = (hasRings) ? (i + 2) : (i + 1);
  39450. }
  39451. // Caps
  39452. var createCylinderCap = function (isTop) {
  39453. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39454. if (radius === 0) {
  39455. return;
  39456. }
  39457. // Cap positions, normals & uvs
  39458. var angle;
  39459. var circleVector;
  39460. var i;
  39461. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39462. var c;
  39463. if (faceColors) {
  39464. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39465. }
  39466. // cap center
  39467. var vbase = positions.length / 3;
  39468. var offset = isTop ? height / 2 : -height / 2;
  39469. var center = new BABYLON.Vector3(0, offset, 0);
  39470. positions.push(center.x, center.y, center.z);
  39471. normals.push(0, isTop ? 1 : -1, 0);
  39472. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39473. if (faceColors) {
  39474. colors.push(c.r, c.g, c.b, c.a);
  39475. }
  39476. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39477. for (i = 0; i <= tessellation; i++) {
  39478. angle = Math.PI * 2 * i * arc / tessellation;
  39479. var cos = Math.cos(-angle);
  39480. var sin = Math.sin(-angle);
  39481. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39482. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39483. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39484. normals.push(0, isTop ? 1 : -1, 0);
  39485. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39486. if (faceColors) {
  39487. colors.push(c.r, c.g, c.b, c.a);
  39488. }
  39489. }
  39490. // Cap indices
  39491. for (i = 0; i < tessellation; i++) {
  39492. if (!isTop) {
  39493. indices.push(vbase);
  39494. indices.push(vbase + (i + 1));
  39495. indices.push(vbase + (i + 2));
  39496. }
  39497. else {
  39498. indices.push(vbase);
  39499. indices.push(vbase + (i + 2));
  39500. indices.push(vbase + (i + 1));
  39501. }
  39502. }
  39503. };
  39504. // add caps to geometry
  39505. createCylinderCap(false);
  39506. createCylinderCap(true);
  39507. // Sides
  39508. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39509. var vertexData = new VertexData();
  39510. vertexData.indices = indices;
  39511. vertexData.positions = positions;
  39512. vertexData.normals = normals;
  39513. vertexData.uvs = uvs;
  39514. if (faceColors) {
  39515. vertexData.colors = colors;
  39516. }
  39517. return vertexData;
  39518. };
  39519. /**
  39520. * Creates the VertexData of the Torus.
  39521. */
  39522. VertexData.CreateTorus = function (options) {
  39523. var indices = [];
  39524. var positions = [];
  39525. var normals = [];
  39526. var uvs = [];
  39527. var diameter = options.diameter || 1;
  39528. var thickness = options.thickness || 0.5;
  39529. var tessellation = options.tessellation || 16;
  39530. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39531. var stride = tessellation + 1;
  39532. for (var i = 0; i <= tessellation; i++) {
  39533. var u = i / tessellation;
  39534. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39535. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39536. for (var j = 0; j <= tessellation; j++) {
  39537. var v = 1 - j / tessellation;
  39538. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39539. var dx = Math.cos(innerAngle);
  39540. var dy = Math.sin(innerAngle);
  39541. // Create a vertex.
  39542. var normal = new BABYLON.Vector3(dx, dy, 0);
  39543. var position = normal.scale(thickness / 2);
  39544. var textureCoordinate = new BABYLON.Vector2(u, v);
  39545. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39546. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39547. positions.push(position.x, position.y, position.z);
  39548. normals.push(normal.x, normal.y, normal.z);
  39549. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39550. // And create indices for two triangles.
  39551. var nextI = (i + 1) % stride;
  39552. var nextJ = (j + 1) % stride;
  39553. indices.push(i * stride + j);
  39554. indices.push(i * stride + nextJ);
  39555. indices.push(nextI * stride + j);
  39556. indices.push(i * stride + nextJ);
  39557. indices.push(nextI * stride + nextJ);
  39558. indices.push(nextI * stride + j);
  39559. }
  39560. }
  39561. // Sides
  39562. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39563. // Result
  39564. var vertexData = new VertexData();
  39565. vertexData.indices = indices;
  39566. vertexData.positions = positions;
  39567. vertexData.normals = normals;
  39568. vertexData.uvs = uvs;
  39569. return vertexData;
  39570. };
  39571. /**
  39572. * Creates the VertexData of the LineSystem.
  39573. */
  39574. VertexData.CreateLineSystem = function (options) {
  39575. var indices = [];
  39576. var positions = [];
  39577. var lines = options.lines;
  39578. var idx = 0;
  39579. for (var l = 0; l < lines.length; l++) {
  39580. var points = lines[l];
  39581. for (var index = 0; index < points.length; index++) {
  39582. positions.push(points[index].x, points[index].y, points[index].z);
  39583. if (index > 0) {
  39584. indices.push(idx - 1);
  39585. indices.push(idx);
  39586. }
  39587. idx++;
  39588. }
  39589. }
  39590. var vertexData = new VertexData();
  39591. vertexData.indices = indices;
  39592. vertexData.positions = positions;
  39593. return vertexData;
  39594. };
  39595. /**
  39596. * Create the VertexData of the DashedLines.
  39597. */
  39598. VertexData.CreateDashedLines = function (options) {
  39599. var dashSize = options.dashSize || 3;
  39600. var gapSize = options.gapSize || 1;
  39601. var dashNb = options.dashNb || 200;
  39602. var points = options.points;
  39603. var positions = new Array();
  39604. var indices = new Array();
  39605. var curvect = BABYLON.Vector3.Zero();
  39606. var lg = 0;
  39607. var nb = 0;
  39608. var shft = 0;
  39609. var dashshft = 0;
  39610. var curshft = 0;
  39611. var idx = 0;
  39612. var i = 0;
  39613. for (i = 0; i < points.length - 1; i++) {
  39614. points[i + 1].subtractToRef(points[i], curvect);
  39615. lg += curvect.length();
  39616. }
  39617. shft = lg / dashNb;
  39618. dashshft = dashSize * shft / (dashSize + gapSize);
  39619. for (i = 0; i < points.length - 1; i++) {
  39620. points[i + 1].subtractToRef(points[i], curvect);
  39621. nb = Math.floor(curvect.length() / shft);
  39622. curvect.normalize();
  39623. for (var j = 0; j < nb; j++) {
  39624. curshft = shft * j;
  39625. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39626. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39627. indices.push(idx, idx + 1);
  39628. idx += 2;
  39629. }
  39630. }
  39631. // Result
  39632. var vertexData = new VertexData();
  39633. vertexData.positions = positions;
  39634. vertexData.indices = indices;
  39635. return vertexData;
  39636. };
  39637. /**
  39638. * Creates the VertexData of the Ground.
  39639. */
  39640. VertexData.CreateGround = function (options) {
  39641. var indices = [];
  39642. var positions = [];
  39643. var normals = [];
  39644. var uvs = [];
  39645. var row, col;
  39646. var width = options.width || 1;
  39647. var height = options.height || 1;
  39648. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39649. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39650. for (row = 0; row <= subdivisionsY; row++) {
  39651. for (col = 0; col <= subdivisionsX; col++) {
  39652. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39653. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39654. positions.push(position.x, position.y, position.z);
  39655. normals.push(normal.x, normal.y, normal.z);
  39656. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39657. }
  39658. }
  39659. for (row = 0; row < subdivisionsY; row++) {
  39660. for (col = 0; col < subdivisionsX; col++) {
  39661. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39662. indices.push(col + 1 + row * (subdivisionsX + 1));
  39663. indices.push(col + row * (subdivisionsX + 1));
  39664. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39665. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39666. indices.push(col + row * (subdivisionsX + 1));
  39667. }
  39668. }
  39669. // Result
  39670. var vertexData = new VertexData();
  39671. vertexData.indices = indices;
  39672. vertexData.positions = positions;
  39673. vertexData.normals = normals;
  39674. vertexData.uvs = uvs;
  39675. return vertexData;
  39676. };
  39677. /**
  39678. * Creates the VertexData of the TiledGround.
  39679. */
  39680. VertexData.CreateTiledGround = function (options) {
  39681. var xmin = options.xmin || -1.0;
  39682. var zmin = options.zmin || -1.0;
  39683. var xmax = options.xmax || 1.0;
  39684. var zmax = options.zmax || 1.0;
  39685. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39686. var precision = options.precision || { w: 1, h: 1 };
  39687. var indices = [];
  39688. var positions = [];
  39689. var normals = [];
  39690. var uvs = [];
  39691. var row, col, tileRow, tileCol;
  39692. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39693. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39694. precision.w = (precision.w < 1) ? 1 : precision.w;
  39695. precision.h = (precision.h < 1) ? 1 : precision.h;
  39696. var tileSize = {
  39697. 'w': (xmax - xmin) / subdivisions.w,
  39698. 'h': (zmax - zmin) / subdivisions.h
  39699. };
  39700. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39701. // Indices
  39702. var base = positions.length / 3;
  39703. var rowLength = precision.w + 1;
  39704. for (row = 0; row < precision.h; row++) {
  39705. for (col = 0; col < precision.w; col++) {
  39706. var square = [
  39707. base + col + row * rowLength,
  39708. base + (col + 1) + row * rowLength,
  39709. base + (col + 1) + (row + 1) * rowLength,
  39710. base + col + (row + 1) * rowLength
  39711. ];
  39712. indices.push(square[1]);
  39713. indices.push(square[2]);
  39714. indices.push(square[3]);
  39715. indices.push(square[0]);
  39716. indices.push(square[1]);
  39717. indices.push(square[3]);
  39718. }
  39719. }
  39720. // Position, normals and uvs
  39721. var position = BABYLON.Vector3.Zero();
  39722. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39723. for (row = 0; row <= precision.h; row++) {
  39724. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39725. for (col = 0; col <= precision.w; col++) {
  39726. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39727. position.y = 0;
  39728. positions.push(position.x, position.y, position.z);
  39729. normals.push(normal.x, normal.y, normal.z);
  39730. uvs.push(col / precision.w, row / precision.h);
  39731. }
  39732. }
  39733. }
  39734. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39735. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39736. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39737. }
  39738. }
  39739. // Result
  39740. var vertexData = new VertexData();
  39741. vertexData.indices = indices;
  39742. vertexData.positions = positions;
  39743. vertexData.normals = normals;
  39744. vertexData.uvs = uvs;
  39745. return vertexData;
  39746. };
  39747. /**
  39748. * Creates the VertexData of the Ground designed from a heightmap.
  39749. */
  39750. VertexData.CreateGroundFromHeightMap = function (options) {
  39751. var indices = [];
  39752. var positions = [];
  39753. var normals = [];
  39754. var uvs = [];
  39755. var row, col;
  39756. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39757. // Vertices
  39758. for (row = 0; row <= options.subdivisions; row++) {
  39759. for (col = 0; col <= options.subdivisions; col++) {
  39760. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  39761. // Compute height
  39762. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39763. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39764. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39765. var r = options.buffer[pos] / 255.0;
  39766. var g = options.buffer[pos + 1] / 255.0;
  39767. var b = options.buffer[pos + 2] / 255.0;
  39768. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39769. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39770. // Add vertex
  39771. positions.push(position.x, position.y, position.z);
  39772. normals.push(0, 0, 0);
  39773. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39774. }
  39775. }
  39776. // Indices
  39777. for (row = 0; row < options.subdivisions; row++) {
  39778. for (col = 0; col < options.subdivisions; col++) {
  39779. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  39780. indices.push(col + 1 + row * (options.subdivisions + 1));
  39781. indices.push(col + row * (options.subdivisions + 1));
  39782. indices.push(col + (row + 1) * (options.subdivisions + 1));
  39783. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  39784. indices.push(col + row * (options.subdivisions + 1));
  39785. }
  39786. }
  39787. // Normals
  39788. VertexData.ComputeNormals(positions, indices, normals);
  39789. // Result
  39790. var vertexData = new VertexData();
  39791. vertexData.indices = indices;
  39792. vertexData.positions = positions;
  39793. vertexData.normals = normals;
  39794. vertexData.uvs = uvs;
  39795. return vertexData;
  39796. };
  39797. /**
  39798. * Creates the VertexData of the Plane.
  39799. */
  39800. VertexData.CreatePlane = function (options) {
  39801. var indices = [];
  39802. var positions = [];
  39803. var normals = [];
  39804. var uvs = [];
  39805. var width = options.width || options.size || 1;
  39806. var height = options.height || options.size || 1;
  39807. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39808. // Vertices
  39809. var halfWidth = width / 2.0;
  39810. var halfHeight = height / 2.0;
  39811. positions.push(-halfWidth, -halfHeight, 0);
  39812. normals.push(0, 0, -1.0);
  39813. uvs.push(0.0, 0.0);
  39814. positions.push(halfWidth, -halfHeight, 0);
  39815. normals.push(0, 0, -1.0);
  39816. uvs.push(1.0, 0.0);
  39817. positions.push(halfWidth, halfHeight, 0);
  39818. normals.push(0, 0, -1.0);
  39819. uvs.push(1.0, 1.0);
  39820. positions.push(-halfWidth, halfHeight, 0);
  39821. normals.push(0, 0, -1.0);
  39822. uvs.push(0.0, 1.0);
  39823. // Indices
  39824. indices.push(0);
  39825. indices.push(1);
  39826. indices.push(2);
  39827. indices.push(0);
  39828. indices.push(2);
  39829. indices.push(3);
  39830. // Sides
  39831. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39832. // Result
  39833. var vertexData = new VertexData();
  39834. vertexData.indices = indices;
  39835. vertexData.positions = positions;
  39836. vertexData.normals = normals;
  39837. vertexData.uvs = uvs;
  39838. return vertexData;
  39839. };
  39840. /**
  39841. * Creates the VertexData of the Disc or regular Polygon.
  39842. */
  39843. VertexData.CreateDisc = function (options) {
  39844. var positions = [];
  39845. var indices = [];
  39846. var normals = [];
  39847. var uvs = [];
  39848. var radius = options.radius || 0.5;
  39849. var tessellation = options.tessellation || 64;
  39850. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39851. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39852. // positions and uvs
  39853. positions.push(0, 0, 0); // disc center first
  39854. uvs.push(0.5, 0.5);
  39855. var theta = Math.PI * 2 * arc;
  39856. var step = theta / tessellation;
  39857. for (var a = 0; a < theta; a += step) {
  39858. var x = Math.cos(a);
  39859. var y = Math.sin(a);
  39860. var u = (x + 1) / 2;
  39861. var v = (1 - y) / 2;
  39862. positions.push(radius * x, radius * y, 0);
  39863. uvs.push(u, v);
  39864. }
  39865. if (arc === 1) {
  39866. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39867. uvs.push(uvs[2], uvs[3]);
  39868. }
  39869. //indices
  39870. var vertexNb = positions.length / 3;
  39871. for (var i = 1; i < vertexNb - 1; i++) {
  39872. indices.push(i + 1, 0, i);
  39873. }
  39874. // result
  39875. VertexData.ComputeNormals(positions, indices, normals);
  39876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  39877. var vertexData = new VertexData();
  39878. vertexData.indices = indices;
  39879. vertexData.positions = positions;
  39880. vertexData.normals = normals;
  39881. vertexData.uvs = uvs;
  39882. return vertexData;
  39883. };
  39884. /**
  39885. * Creates the VertexData of the IcoSphere.
  39886. */
  39887. VertexData.CreateIcoSphere = function (options) {
  39888. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39889. var radius = options.radius || 1;
  39890. var flat = (options.flat === undefined) ? true : options.flat;
  39891. var subdivisions = options.subdivisions || 4;
  39892. var radiusX = options.radiusX || radius;
  39893. var radiusY = options.radiusY || radius;
  39894. var radiusZ = options.radiusZ || radius;
  39895. var t = (1 + Math.sqrt(5)) / 2;
  39896. // 12 vertex x,y,z
  39897. var ico_vertices = [
  39898. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39899. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39900. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39901. ];
  39902. // index of 3 vertex makes a face of icopshere
  39903. var ico_indices = [
  39904. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39905. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39906. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39907. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39908. ];
  39909. // vertex for uv have aliased position, not for UV
  39910. var vertices_unalias_id = [
  39911. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39912. // vertex alias
  39913. 0,
  39914. 2,
  39915. 3,
  39916. 3,
  39917. 3,
  39918. 4,
  39919. 7,
  39920. 8,
  39921. 9,
  39922. 9,
  39923. 10,
  39924. 11 // 23: B + 12
  39925. ];
  39926. // uv as integer step (not pixels !)
  39927. var ico_vertexuv = [
  39928. 5, 1, 3, 1, 6, 4, 0, 0,
  39929. 5, 3, 4, 2, 2, 2, 4, 0,
  39930. 2, 0, 1, 1, 6, 0, 6, 2,
  39931. // vertex alias (for same vertex on different faces)
  39932. 0, 4,
  39933. 3, 3,
  39934. 4, 4,
  39935. 3, 1,
  39936. 4, 2,
  39937. 4, 4,
  39938. 0, 2,
  39939. 1, 1,
  39940. 2, 2,
  39941. 3, 3,
  39942. 1, 3,
  39943. 2, 4 // 23: B + 12
  39944. ];
  39945. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39946. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39947. // First island of uv mapping
  39948. // v = 4h 3+ 2
  39949. // v = 3h 9+ 4
  39950. // v = 2h 9+ 5 B
  39951. // v = 1h 9 1 0
  39952. // v = 0h 3 8 7 A
  39953. // u = 0 1 2 3 4 5 6 *a
  39954. // Second island of uv mapping
  39955. // v = 4h 0+ B+ 4+
  39956. // v = 3h A+ 2+
  39957. // v = 2h 7+ 6 3+
  39958. // v = 1h 8+ 3+
  39959. // v = 0h
  39960. // u = 0 1 2 3 4 5 6 *a
  39961. // Face layout on texture UV mapping
  39962. // ============
  39963. // \ 4 /\ 16 / ======
  39964. // \ / \ / /\ 11 /
  39965. // \/ 7 \/ / \ /
  39966. // ======= / 10 \/
  39967. // /\ 17 /\ =======
  39968. // / \ / \ \ 15 /\
  39969. // / 8 \/ 12 \ \ / \
  39970. // ============ \/ 6 \
  39971. // \ 18 /\ ============
  39972. // \ / \ \ 5 /\ 0 /
  39973. // \/ 13 \ \ / \ /
  39974. // ======= \/ 1 \/
  39975. // =============
  39976. // /\ 19 /\ 2 /\
  39977. // / \ / \ / \
  39978. // / 14 \/ 9 \/ 3 \
  39979. // ===================
  39980. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39981. var ustep = 138 / 1024;
  39982. var vstep = 239 / 1024;
  39983. var uoffset = 60 / 1024;
  39984. var voffset = 26 / 1024;
  39985. // Second island should have margin, not to touch the first island
  39986. // avoid any borderline artefact in pixel rounding
  39987. var island_u_offset = -40 / 1024;
  39988. var island_v_offset = +20 / 1024;
  39989. // face is either island 0 or 1 :
  39990. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39991. var island = [
  39992. 0, 0, 0, 0, 1,
  39993. 0, 0, 1, 1, 0,
  39994. 0, 0, 1, 1, 0,
  39995. 0, 1, 1, 1, 0 // 15 - 19
  39996. ];
  39997. var indices = [];
  39998. var positions = [];
  39999. var normals = [];
  40000. var uvs = [];
  40001. var current_indice = 0;
  40002. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  40003. var face_vertex_pos = new Array(3);
  40004. var face_vertex_uv = new Array(3);
  40005. var v012;
  40006. for (v012 = 0; v012 < 3; v012++) {
  40007. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  40008. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  40009. }
  40010. // create all with normals
  40011. for (var face = 0; face < 20; face++) {
  40012. // 3 vertex per face
  40013. for (v012 = 0; v012 < 3; v012++) {
  40014. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  40015. var v_id = ico_indices[3 * face + v012];
  40016. // vertex have 3D position (x,y,z)
  40017. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  40018. // Normalize to get normal, then scale to radius
  40019. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  40020. // uv Coordinates from vertex ID
  40021. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  40022. }
  40023. // Subdivide the face (interpolate pos, norm, uv)
  40024. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  40025. // - norm is linear interpolation of vertex corner normal
  40026. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  40027. // - uv is linear interpolation
  40028. //
  40029. // Topology is as below for sub-divide by 2
  40030. // vertex shown as v0,v1,v2
  40031. // interp index is i1 to progress in range [v0,v1[
  40032. // interp index is i2 to progress in range [v0,v2[
  40033. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  40034. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  40035. //
  40036. //
  40037. // i2 v2
  40038. // ^ ^
  40039. // / / \
  40040. // / / \
  40041. // / / \
  40042. // / / (0,1) \
  40043. // / #---------\
  40044. // / / \ (0,0)'/ \
  40045. // / / \ / \
  40046. // / / \ / \
  40047. // / / (0,0) \ / (1,0) \
  40048. // / #---------#---------\
  40049. // v0 v1
  40050. //
  40051. // --------------------> i1
  40052. //
  40053. // interp of (i1,i2):
  40054. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  40055. // along i1 : lerp(x0,x1, i1/(S-i2))
  40056. //
  40057. // centroid of triangle is needed to get help normal computation
  40058. // (c1,c2) are used for centroid location
  40059. var interp_vertex = function (i1, i2, c1, c2) {
  40060. // vertex is interpolated from
  40061. // - face_vertex_pos[0..2]
  40062. // - face_vertex_uv[0..2]
  40063. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  40064. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  40065. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  40066. pos_interp.normalize();
  40067. var vertex_normal;
  40068. if (flat) {
  40069. // in flat mode, recalculate normal as face centroid normal
  40070. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  40071. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  40072. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  40073. }
  40074. else {
  40075. // in smooth mode, recalculate normal from each single vertex position
  40076. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  40077. }
  40078. // Vertex normal need correction due to X,Y,Z radius scaling
  40079. vertex_normal.x /= radiusX;
  40080. vertex_normal.y /= radiusY;
  40081. vertex_normal.z /= radiusZ;
  40082. vertex_normal.normalize();
  40083. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  40084. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  40085. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  40086. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  40087. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  40088. uvs.push(uv_interp.x, uv_interp.y);
  40089. // push each vertex has member of a face
  40090. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  40091. indices.push(current_indice);
  40092. current_indice++;
  40093. };
  40094. for (var i2 = 0; i2 < subdivisions; i2++) {
  40095. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  40096. // face : (i1,i2) for /\ :
  40097. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  40098. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40099. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40100. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  40101. if (i1 + i2 + 1 < subdivisions) {
  40102. // face : (i1,i2)' for \/ :
  40103. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  40104. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40105. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40106. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  40107. }
  40108. }
  40109. }
  40110. }
  40111. // Sides
  40112. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  40113. // Result
  40114. var vertexData = new VertexData();
  40115. vertexData.indices = indices;
  40116. vertexData.positions = positions;
  40117. vertexData.normals = normals;
  40118. vertexData.uvs = uvs;
  40119. return vertexData;
  40120. };
  40121. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  40122. /**
  40123. * Creates the VertexData of the Polyhedron.
  40124. */
  40125. VertexData.CreatePolyhedron = function (options) {
  40126. // provided polyhedron types :
  40127. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  40128. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  40129. var polyhedra = [];
  40130. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  40131. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  40132. polyhedra[2] = {
  40133. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  40134. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  40135. };
  40136. polyhedra[3] = {
  40137. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  40138. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  40139. };
  40140. polyhedra[4] = {
  40141. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  40142. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  40143. };
  40144. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  40145. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  40146. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  40147. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  40148. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  40149. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  40150. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  40151. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  40152. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  40153. polyhedra[14] = {
  40154. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  40155. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  40156. };
  40157. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  40158. var size = options.size;
  40159. var sizeX = options.sizeX || size || 1;
  40160. var sizeY = options.sizeY || size || 1;
  40161. var sizeZ = options.sizeZ || size || 1;
  40162. var data = options.custom || polyhedra[type];
  40163. var nbfaces = data.face.length;
  40164. var faceUV = options.faceUV || new Array(nbfaces);
  40165. var faceColors = options.faceColors;
  40166. var flat = (options.flat === undefined) ? true : options.flat;
  40167. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40168. var positions = [];
  40169. var indices = [];
  40170. var normals = [];
  40171. var uvs = [];
  40172. var colors = [];
  40173. var index = 0;
  40174. var faceIdx = 0; // face cursor in the array "indexes"
  40175. var indexes = [];
  40176. var i = 0;
  40177. var f = 0;
  40178. var u, v, ang, x, y, tmp;
  40179. // default face colors and UV if undefined
  40180. if (flat) {
  40181. for (f = 0; f < nbfaces; f++) {
  40182. if (faceColors && faceColors[f] === undefined) {
  40183. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  40184. }
  40185. if (faceUV && faceUV[f] === undefined) {
  40186. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  40187. }
  40188. }
  40189. }
  40190. if (!flat) {
  40191. for (i = 0; i < data.vertex.length; i++) {
  40192. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  40193. uvs.push(0, 0);
  40194. }
  40195. for (f = 0; f < nbfaces; f++) {
  40196. for (i = 0; i < data.face[f].length - 2; i++) {
  40197. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  40198. }
  40199. }
  40200. }
  40201. else {
  40202. for (f = 0; f < nbfaces; f++) {
  40203. var fl = data.face[f].length; // number of vertices of the current face
  40204. ang = 2 * Math.PI / fl;
  40205. x = 0.5 * Math.tan(ang / 2);
  40206. y = 0.5;
  40207. // positions, uvs, colors
  40208. for (i = 0; i < fl; i++) {
  40209. // positions
  40210. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  40211. indexes.push(index);
  40212. index++;
  40213. // uvs
  40214. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  40215. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  40216. uvs.push(u, v);
  40217. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  40218. y = x * Math.sin(ang) + y * Math.cos(ang);
  40219. x = tmp;
  40220. // colors
  40221. if (faceColors) {
  40222. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  40223. }
  40224. }
  40225. // indices from indexes
  40226. for (i = 0; i < fl - 2; i++) {
  40227. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  40228. }
  40229. faceIdx += fl;
  40230. }
  40231. }
  40232. VertexData.ComputeNormals(positions, indices, normals);
  40233. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  40234. var vertexData = new VertexData();
  40235. vertexData.positions = positions;
  40236. vertexData.indices = indices;
  40237. vertexData.normals = normals;
  40238. vertexData.uvs = uvs;
  40239. if (faceColors && flat) {
  40240. vertexData.colors = colors;
  40241. }
  40242. return vertexData;
  40243. };
  40244. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40245. /**
  40246. * Creates the VertexData of the Torus Knot.
  40247. */
  40248. VertexData.CreateTorusKnot = function (options) {
  40249. var indices = [];
  40250. var positions = [];
  40251. var normals = [];
  40252. var uvs = [];
  40253. var radius = options.radius || 2;
  40254. var tube = options.tube || 0.5;
  40255. var radialSegments = options.radialSegments || 32;
  40256. var tubularSegments = options.tubularSegments || 32;
  40257. var p = options.p || 2;
  40258. var q = options.q || 3;
  40259. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40260. // Helper
  40261. var getPos = function (angle) {
  40262. var cu = Math.cos(angle);
  40263. var su = Math.sin(angle);
  40264. var quOverP = q / p * angle;
  40265. var cs = Math.cos(quOverP);
  40266. var tx = radius * (2 + cs) * 0.5 * cu;
  40267. var ty = radius * (2 + cs) * su * 0.5;
  40268. var tz = radius * Math.sin(quOverP) * 0.5;
  40269. return new BABYLON.Vector3(tx, ty, tz);
  40270. };
  40271. // Vertices
  40272. var i;
  40273. var j;
  40274. for (i = 0; i <= radialSegments; i++) {
  40275. var modI = i % radialSegments;
  40276. var u = modI / radialSegments * 2 * p * Math.PI;
  40277. var p1 = getPos(u);
  40278. var p2 = getPos(u + 0.01);
  40279. var tang = p2.subtract(p1);
  40280. var n = p2.add(p1);
  40281. var bitan = BABYLON.Vector3.Cross(tang, n);
  40282. n = BABYLON.Vector3.Cross(bitan, tang);
  40283. bitan.normalize();
  40284. n.normalize();
  40285. for (j = 0; j < tubularSegments; j++) {
  40286. var modJ = j % tubularSegments;
  40287. var v = modJ / tubularSegments * 2 * Math.PI;
  40288. var cx = -tube * Math.cos(v);
  40289. var cy = tube * Math.sin(v);
  40290. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40291. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40292. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40293. uvs.push(i / radialSegments);
  40294. uvs.push(j / tubularSegments);
  40295. }
  40296. }
  40297. for (i = 0; i < radialSegments; i++) {
  40298. for (j = 0; j < tubularSegments; j++) {
  40299. var jNext = (j + 1) % tubularSegments;
  40300. var a = i * tubularSegments + j;
  40301. var b = (i + 1) * tubularSegments + j;
  40302. var c = (i + 1) * tubularSegments + jNext;
  40303. var d = i * tubularSegments + jNext;
  40304. indices.push(d);
  40305. indices.push(b);
  40306. indices.push(a);
  40307. indices.push(d);
  40308. indices.push(c);
  40309. indices.push(b);
  40310. }
  40311. }
  40312. // Normals
  40313. VertexData.ComputeNormals(positions, indices, normals);
  40314. // Sides
  40315. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  40316. // Result
  40317. var vertexData = new VertexData();
  40318. vertexData.indices = indices;
  40319. vertexData.positions = positions;
  40320. vertexData.normals = normals;
  40321. vertexData.uvs = uvs;
  40322. return vertexData;
  40323. };
  40324. // Tools
  40325. /**
  40326. * @param {any} - positions (number[] or Float32Array)
  40327. * @param {any} - indices (number[] or Uint16Array)
  40328. * @param {any} - normals (number[] or Float32Array)
  40329. * options (optional) :
  40330. * facetPositions : optional array of facet positions (vector3)
  40331. * facetNormals : optional array of facet normals (vector3)
  40332. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40333. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40334. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40335. * bbSize : optional bounding box size data, required for facetPartitioning computation
  40336. * bInfo : optional bounding info, required for facetPartitioning computation
  40337. */
  40338. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40339. // temporary scalar variables
  40340. var index = 0; // facet index
  40341. var p1p2x = 0.0; // p1p2 vector x coordinate
  40342. var p1p2y = 0.0; // p1p2 vector y coordinate
  40343. var p1p2z = 0.0; // p1p2 vector z coordinate
  40344. var p3p2x = 0.0; // p3p2 vector x coordinate
  40345. var p3p2y = 0.0; // p3p2 vector y coordinate
  40346. var p3p2z = 0.0; // p3p2 vector z coordinate
  40347. var faceNormalx = 0.0; // facet normal x coordinate
  40348. var faceNormaly = 0.0; // facet normal y coordinate
  40349. var faceNormalz = 0.0; // facet normal z coordinate
  40350. var length = 0.0; // facet normal length before normalization
  40351. var v1x = 0; // vector1 x index in the positions array
  40352. var v1y = 0; // vector1 y index in the positions array
  40353. var v1z = 0; // vector1 z index in the positions array
  40354. var v2x = 0; // vector2 x index in the positions array
  40355. var v2y = 0; // vector2 y index in the positions array
  40356. var v2z = 0; // vector2 z index in the positions array
  40357. var v3x = 0; // vector3 x index in the positions array
  40358. var v3y = 0; // vector3 y index in the positions array
  40359. var v3z = 0; // vector3 z index in the positions array
  40360. var computeFacetNormals = false;
  40361. var computeFacetPositions = false;
  40362. var computeFacetPartitioning = false;
  40363. if (options) {
  40364. computeFacetNormals = (options.facetNormals) ? true : false;
  40365. computeFacetPositions = (options.facetPositions) ? true : false;
  40366. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40367. }
  40368. // facetPartitioning reinit if needed
  40369. if (computeFacetPartitioning) {
  40370. var ox = 0; // X partitioning index for facet position
  40371. var oy = 0; // Y partinioning index for facet position
  40372. var oz = 0; // Z partinioning index for facet position
  40373. var b1x = 0; // X partitioning index for facet v1 vertex
  40374. var b1y = 0; // Y partitioning index for facet v1 vertex
  40375. var b1z = 0; // z partitioning index for facet v1 vertex
  40376. var b2x = 0; // X partitioning index for facet v2 vertex
  40377. var b2y = 0; // Y partitioning index for facet v2 vertex
  40378. var b2z = 0; // Z partitioning index for facet v2 vertex
  40379. var b3x = 0; // X partitioning index for facet v3 vertex
  40380. var b3y = 0; // Y partitioning index for facet v3 vertex
  40381. var b3z = 0; // Z partitioning index for facet v3 vertex
  40382. var block_idx_o = 0; // facet barycenter block index
  40383. var block_idx_v1 = 0; // v1 vertex block index
  40384. var block_idx_v2 = 0; // v2 vertex block index
  40385. var block_idx_v3 = 0; // v3 vertex block index
  40386. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40387. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40388. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  40389. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  40390. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  40391. var subSq = options.subDiv.max * options.subDiv.max;
  40392. options.facetPartitioning.length = 0;
  40393. }
  40394. // reset the normals
  40395. for (index = 0; index < positions.length; index++) {
  40396. normals[index] = 0.0;
  40397. }
  40398. // Loop : 1 indice triplet = 1 facet
  40399. var nbFaces = indices.length / 3;
  40400. for (index = 0; index < nbFaces; index++) {
  40401. // get the indexes of the coordinates of each vertex of the facet
  40402. v1x = indices[index * 3] * 3;
  40403. v1y = v1x + 1;
  40404. v1z = v1x + 2;
  40405. v2x = indices[index * 3 + 1] * 3;
  40406. v2y = v2x + 1;
  40407. v2z = v2x + 2;
  40408. v3x = indices[index * 3 + 2] * 3;
  40409. v3y = v3x + 1;
  40410. v3z = v3x + 2;
  40411. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40412. p1p2y = positions[v1y] - positions[v2y];
  40413. p1p2z = positions[v1z] - positions[v2z];
  40414. p3p2x = positions[v3x] - positions[v2x];
  40415. p3p2y = positions[v3y] - positions[v2y];
  40416. p3p2z = positions[v3z] - positions[v2z];
  40417. // compute the face normal with the cross product
  40418. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  40419. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  40420. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  40421. // normalize this normal and store it in the array facetData
  40422. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40423. length = (length === 0) ? 1.0 : length;
  40424. faceNormalx /= length;
  40425. faceNormaly /= length;
  40426. faceNormalz /= length;
  40427. if (computeFacetNormals) {
  40428. options.facetNormals[index].x = faceNormalx;
  40429. options.facetNormals[index].y = faceNormaly;
  40430. options.facetNormals[index].z = faceNormalz;
  40431. }
  40432. if (computeFacetPositions) {
  40433. // compute and the facet barycenter coordinates in the array facetPositions
  40434. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40435. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40436. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40437. }
  40438. if (computeFacetPartitioning) {
  40439. // store the facet indexes in arrays in the main facetPartitioning array :
  40440. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40441. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  40442. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  40443. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  40444. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  40445. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  40446. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  40447. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  40448. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  40449. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  40450. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  40451. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  40452. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  40453. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40454. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40455. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40456. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40457. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40458. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40459. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40460. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40461. // push each facet index in each block containing the vertex
  40462. options.facetPartitioning[block_idx_v1].push(index);
  40463. if (block_idx_v2 != block_idx_v1) {
  40464. options.facetPartitioning[block_idx_v2].push(index);
  40465. }
  40466. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40467. options.facetPartitioning[block_idx_v3].push(index);
  40468. }
  40469. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40470. options.facetPartitioning[block_idx_o].push(index);
  40471. }
  40472. }
  40473. // compute the normals anyway
  40474. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40475. normals[v1y] += faceNormaly;
  40476. normals[v1z] += faceNormalz;
  40477. normals[v2x] += faceNormalx;
  40478. normals[v2y] += faceNormaly;
  40479. normals[v2z] += faceNormalz;
  40480. normals[v3x] += faceNormalx;
  40481. normals[v3y] += faceNormaly;
  40482. normals[v3z] += faceNormalz;
  40483. }
  40484. // last normalization of each normal
  40485. for (index = 0; index < normals.length / 3; index++) {
  40486. faceNormalx = normals[index * 3];
  40487. faceNormaly = normals[index * 3 + 1];
  40488. faceNormalz = normals[index * 3 + 2];
  40489. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40490. length = (length === 0) ? 1.0 : length;
  40491. faceNormalx /= length;
  40492. faceNormaly /= length;
  40493. faceNormalz /= length;
  40494. normals[index * 3] = faceNormalx;
  40495. normals[index * 3 + 1] = faceNormaly;
  40496. normals[index * 3 + 2] = faceNormalz;
  40497. }
  40498. };
  40499. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  40500. var li = indices.length;
  40501. var ln = normals.length;
  40502. var i;
  40503. var n;
  40504. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40505. switch (sideOrientation) {
  40506. case BABYLON.Mesh.FRONTSIDE:
  40507. // nothing changed
  40508. break;
  40509. case BABYLON.Mesh.BACKSIDE:
  40510. var tmp;
  40511. // indices
  40512. for (i = 0; i < li; i += 3) {
  40513. tmp = indices[i];
  40514. indices[i] = indices[i + 2];
  40515. indices[i + 2] = tmp;
  40516. }
  40517. // normals
  40518. for (n = 0; n < ln; n++) {
  40519. normals[n] = -normals[n];
  40520. }
  40521. break;
  40522. case BABYLON.Mesh.DOUBLESIDE:
  40523. // positions
  40524. var lp = positions.length;
  40525. var l = lp / 3;
  40526. for (var p = 0; p < lp; p++) {
  40527. positions[lp + p] = positions[p];
  40528. }
  40529. // indices
  40530. for (i = 0; i < li; i += 3) {
  40531. indices[i + li] = indices[i + 2] + l;
  40532. indices[i + 1 + li] = indices[i + 1] + l;
  40533. indices[i + 2 + li] = indices[i] + l;
  40534. }
  40535. // normals
  40536. for (n = 0; n < ln; n++) {
  40537. normals[ln + n] = -normals[n];
  40538. }
  40539. // uvs
  40540. var lu = uvs.length;
  40541. for (var u = 0; u < lu; u++) {
  40542. uvs[u + lu] = uvs[u];
  40543. }
  40544. break;
  40545. }
  40546. };
  40547. /**
  40548. * Creates a new VertexData from the imported parameters.
  40549. */
  40550. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40551. var vertexData = new VertexData();
  40552. // positions
  40553. var positions = parsedVertexData.positions;
  40554. if (positions) {
  40555. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40556. }
  40557. // normals
  40558. var normals = parsedVertexData.normals;
  40559. if (normals) {
  40560. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40561. }
  40562. // tangents
  40563. var tangents = parsedVertexData.tangents;
  40564. if (tangents) {
  40565. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40566. }
  40567. // uvs
  40568. var uvs = parsedVertexData.uvs;
  40569. if (uvs) {
  40570. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40571. }
  40572. // uv2s
  40573. var uv2s = parsedVertexData.uv2s;
  40574. if (uv2s) {
  40575. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40576. }
  40577. // uv3s
  40578. var uv3s = parsedVertexData.uv3s;
  40579. if (uv3s) {
  40580. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40581. }
  40582. // uv4s
  40583. var uv4s = parsedVertexData.uv4s;
  40584. if (uv4s) {
  40585. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40586. }
  40587. // uv5s
  40588. var uv5s = parsedVertexData.uv5s;
  40589. if (uv5s) {
  40590. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40591. }
  40592. // uv6s
  40593. var uv6s = parsedVertexData.uv6s;
  40594. if (uv6s) {
  40595. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40596. }
  40597. // colors
  40598. var colors = parsedVertexData.colors;
  40599. if (colors) {
  40600. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40601. }
  40602. // matricesIndices
  40603. var matricesIndices = parsedVertexData.matricesIndices;
  40604. if (matricesIndices) {
  40605. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40606. }
  40607. // matricesWeights
  40608. var matricesWeights = parsedVertexData.matricesWeights;
  40609. if (matricesWeights) {
  40610. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40611. }
  40612. // indices
  40613. var indices = parsedVertexData.indices;
  40614. if (indices) {
  40615. vertexData.indices = indices;
  40616. }
  40617. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40618. };
  40619. return VertexData;
  40620. }());
  40621. BABYLON.VertexData = VertexData;
  40622. })(BABYLON || (BABYLON = {}));
  40623. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40624. var BABYLON;
  40625. (function (BABYLON) {
  40626. var Tags = (function () {
  40627. function Tags() {
  40628. }
  40629. Tags.EnableFor = function (obj) {
  40630. obj._tags = obj._tags || {};
  40631. obj.hasTags = function () {
  40632. return Tags.HasTags(obj);
  40633. };
  40634. obj.addTags = function (tagsString) {
  40635. return Tags.AddTagsTo(obj, tagsString);
  40636. };
  40637. obj.removeTags = function (tagsString) {
  40638. return Tags.RemoveTagsFrom(obj, tagsString);
  40639. };
  40640. obj.matchesTagsQuery = function (tagsQuery) {
  40641. return Tags.MatchesQuery(obj, tagsQuery);
  40642. };
  40643. };
  40644. Tags.DisableFor = function (obj) {
  40645. delete obj._tags;
  40646. delete obj.hasTags;
  40647. delete obj.addTags;
  40648. delete obj.removeTags;
  40649. delete obj.matchesTagsQuery;
  40650. };
  40651. Tags.HasTags = function (obj) {
  40652. if (!obj._tags) {
  40653. return false;
  40654. }
  40655. return !BABYLON.Tools.IsEmpty(obj._tags);
  40656. };
  40657. Tags.GetTags = function (obj, asString) {
  40658. if (asString === void 0) { asString = true; }
  40659. if (!obj._tags) {
  40660. return null;
  40661. }
  40662. if (asString) {
  40663. var tagsArray = [];
  40664. for (var tag in obj._tags) {
  40665. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  40666. tagsArray.push(tag);
  40667. }
  40668. }
  40669. return tagsArray.join(" ");
  40670. }
  40671. else {
  40672. return obj._tags;
  40673. }
  40674. };
  40675. // the tags 'true' and 'false' are reserved and cannot be used as tags
  40676. // a tag cannot start with '||', '&&', and '!'
  40677. // it cannot contain whitespaces
  40678. Tags.AddTagsTo = function (obj, tagsString) {
  40679. if (!tagsString) {
  40680. return;
  40681. }
  40682. if (typeof tagsString !== "string") {
  40683. return;
  40684. }
  40685. var tags = tagsString.split(" ");
  40686. tags.forEach(function (tag, index, array) {
  40687. Tags._AddTagTo(obj, tag);
  40688. });
  40689. };
  40690. Tags._AddTagTo = function (obj, tag) {
  40691. tag = tag.trim();
  40692. if (tag === "" || tag === "true" || tag === "false") {
  40693. return;
  40694. }
  40695. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  40696. return;
  40697. }
  40698. Tags.EnableFor(obj);
  40699. obj._tags[tag] = true;
  40700. };
  40701. Tags.RemoveTagsFrom = function (obj, tagsString) {
  40702. if (!Tags.HasTags(obj)) {
  40703. return;
  40704. }
  40705. var tags = tagsString.split(" ");
  40706. for (var t in tags) {
  40707. Tags._RemoveTagFrom(obj, tags[t]);
  40708. }
  40709. };
  40710. Tags._RemoveTagFrom = function (obj, tag) {
  40711. delete obj._tags[tag];
  40712. };
  40713. Tags.MatchesQuery = function (obj, tagsQuery) {
  40714. if (tagsQuery === undefined) {
  40715. return true;
  40716. }
  40717. if (tagsQuery === "") {
  40718. return Tags.HasTags(obj);
  40719. }
  40720. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  40721. };
  40722. return Tags;
  40723. }());
  40724. BABYLON.Tags = Tags;
  40725. })(BABYLON || (BABYLON = {}));
  40726. //# sourceMappingURL=babylon.tags.js.map
  40727. var BABYLON;
  40728. (function (BABYLON) {
  40729. var Internals;
  40730. (function (Internals) {
  40731. var AndOrNotEvaluator = (function () {
  40732. function AndOrNotEvaluator() {
  40733. }
  40734. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  40735. if (!query.match(/\([^\(\)]*\)/g)) {
  40736. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  40737. }
  40738. else {
  40739. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  40740. // remove parenthesis
  40741. r = r.slice(1, r.length - 1);
  40742. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  40743. });
  40744. }
  40745. if (query === "true") {
  40746. return true;
  40747. }
  40748. if (query === "false") {
  40749. return false;
  40750. }
  40751. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  40752. };
  40753. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  40754. evaluateCallback = evaluateCallback || (function (r) {
  40755. return r === "true" ? true : false;
  40756. });
  40757. var result;
  40758. var or = parenthesisContent.split("||");
  40759. for (var i in or) {
  40760. if (or.hasOwnProperty(i)) {
  40761. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  40762. var and = ori.split("&&");
  40763. if (and.length > 1) {
  40764. for (var j = 0; j < and.length; ++j) {
  40765. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  40766. if (andj !== "true" && andj !== "false") {
  40767. if (andj[0] === "!") {
  40768. result = !evaluateCallback(andj.substring(1));
  40769. }
  40770. else {
  40771. result = evaluateCallback(andj);
  40772. }
  40773. }
  40774. else {
  40775. result = andj === "true" ? true : false;
  40776. }
  40777. if (!result) {
  40778. ori = "false";
  40779. break;
  40780. }
  40781. }
  40782. }
  40783. if (result || ori === "true") {
  40784. result = true;
  40785. break;
  40786. }
  40787. // result equals false (or undefined)
  40788. if (ori !== "true" && ori !== "false") {
  40789. if (ori[0] === "!") {
  40790. result = !evaluateCallback(ori.substring(1));
  40791. }
  40792. else {
  40793. result = evaluateCallback(ori);
  40794. }
  40795. }
  40796. else {
  40797. result = ori === "true" ? true : false;
  40798. }
  40799. }
  40800. }
  40801. // the whole parenthesis scope is replaced by 'true' or 'false'
  40802. return result ? "true" : "false";
  40803. };
  40804. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  40805. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  40806. // remove whitespaces
  40807. r = r.replace(/[\s]/g, function () { return ""; });
  40808. return r.length % 2 ? "!" : "";
  40809. });
  40810. booleanString = booleanString.trim();
  40811. if (booleanString === "!true") {
  40812. booleanString = "false";
  40813. }
  40814. else if (booleanString === "!false") {
  40815. booleanString = "true";
  40816. }
  40817. return booleanString;
  40818. };
  40819. return AndOrNotEvaluator;
  40820. }());
  40821. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  40822. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40823. })(BABYLON || (BABYLON = {}));
  40824. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  40825. var BABYLON;
  40826. (function (BABYLON) {
  40827. var PostProcessRenderPass = (function () {
  40828. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  40829. this._enabled = true;
  40830. this._refCount = 0;
  40831. this._name = name;
  40832. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  40833. this.setRenderList(renderList);
  40834. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  40835. this._renderTexture.onAfterRenderObservable.add(afterRender);
  40836. this._scene = scene;
  40837. this._renderList = renderList;
  40838. }
  40839. // private
  40840. PostProcessRenderPass.prototype._incRefCount = function () {
  40841. if (this._refCount === 0) {
  40842. this._scene.customRenderTargets.push(this._renderTexture);
  40843. }
  40844. return ++this._refCount;
  40845. };
  40846. PostProcessRenderPass.prototype._decRefCount = function () {
  40847. this._refCount--;
  40848. if (this._refCount <= 0) {
  40849. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  40850. }
  40851. return this._refCount;
  40852. };
  40853. PostProcessRenderPass.prototype._update = function () {
  40854. this.setRenderList(this._renderList);
  40855. };
  40856. // public
  40857. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  40858. this._renderTexture.renderList = renderList;
  40859. };
  40860. PostProcessRenderPass.prototype.getRenderTexture = function () {
  40861. return this._renderTexture;
  40862. };
  40863. return PostProcessRenderPass;
  40864. }());
  40865. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  40866. })(BABYLON || (BABYLON = {}));
  40867. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  40868. var BABYLON;
  40869. (function (BABYLON) {
  40870. var PostProcessRenderEffect = (function () {
  40871. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  40872. this._engine = engine;
  40873. this._name = name;
  40874. this._singleInstance = singleInstance || true;
  40875. this._getPostProcess = getPostProcess;
  40876. this._cameras = [];
  40877. this._indicesForCamera = [];
  40878. this._postProcesses = {};
  40879. this._renderPasses = {};
  40880. this._renderEffectAsPasses = {};
  40881. }
  40882. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  40883. get: function () {
  40884. for (var index in this._postProcesses) {
  40885. if (!this._postProcesses[index].isSupported) {
  40886. return false;
  40887. }
  40888. }
  40889. return true;
  40890. },
  40891. enumerable: true,
  40892. configurable: true
  40893. });
  40894. PostProcessRenderEffect.prototype._update = function () {
  40895. for (var renderPassName in this._renderPasses) {
  40896. this._renderPasses[renderPassName]._update();
  40897. }
  40898. };
  40899. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  40900. this._renderPasses[renderPass._name] = renderPass;
  40901. this._linkParameters();
  40902. };
  40903. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  40904. delete this._renderPasses[renderPass._name];
  40905. this._linkParameters();
  40906. };
  40907. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  40908. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  40909. this._linkParameters();
  40910. };
  40911. PostProcessRenderEffect.prototype.getPass = function (passName) {
  40912. for (var renderPassName in this._renderPasses) {
  40913. if (renderPassName === passName) {
  40914. return this._renderPasses[passName];
  40915. }
  40916. }
  40917. };
  40918. PostProcessRenderEffect.prototype.emptyPasses = function () {
  40919. this._renderPasses = {};
  40920. this._linkParameters();
  40921. };
  40922. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  40923. var cameraKey;
  40924. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40925. for (var i = 0; i < _cam.length; i++) {
  40926. var camera = _cam[i];
  40927. var cameraName = camera.name;
  40928. if (this._singleInstance) {
  40929. cameraKey = 0;
  40930. }
  40931. else {
  40932. cameraKey = cameraName;
  40933. }
  40934. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  40935. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  40936. if (!this._indicesForCamera[cameraName]) {
  40937. this._indicesForCamera[cameraName] = [];
  40938. }
  40939. this._indicesForCamera[cameraName].push(index);
  40940. if (this._cameras.indexOf(camera) === -1) {
  40941. this._cameras[cameraName] = camera;
  40942. }
  40943. for (var passName in this._renderPasses) {
  40944. this._renderPasses[passName]._incRefCount();
  40945. }
  40946. }
  40947. this._linkParameters();
  40948. };
  40949. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  40950. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40951. for (var i = 0; i < _cam.length; i++) {
  40952. var camera = _cam[i];
  40953. var cameraName = camera.name;
  40954. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40955. var index = this._cameras.indexOf(cameraName);
  40956. this._indicesForCamera.splice(index, 1);
  40957. this._cameras.splice(index, 1);
  40958. for (var passName in this._renderPasses) {
  40959. this._renderPasses[passName]._decRefCount();
  40960. }
  40961. }
  40962. };
  40963. PostProcessRenderEffect.prototype._enable = function (cameras) {
  40964. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40965. for (var i = 0; i < _cam.length; i++) {
  40966. var camera = _cam[i];
  40967. var cameraName = camera.name;
  40968. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  40969. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  40970. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  40971. }
  40972. }
  40973. for (var passName in this._renderPasses) {
  40974. this._renderPasses[passName]._incRefCount();
  40975. }
  40976. }
  40977. };
  40978. PostProcessRenderEffect.prototype._disable = function (cameras) {
  40979. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40980. for (var i = 0; i < _cam.length; i++) {
  40981. var camera = _cam[i];
  40982. var cameraName = camera.Name;
  40983. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40984. for (var passName in this._renderPasses) {
  40985. this._renderPasses[passName]._decRefCount();
  40986. }
  40987. }
  40988. };
  40989. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  40990. if (this._singleInstance) {
  40991. return this._postProcesses[0];
  40992. }
  40993. else {
  40994. return this._postProcesses[camera.name];
  40995. }
  40996. };
  40997. PostProcessRenderEffect.prototype._linkParameters = function () {
  40998. var _this = this;
  40999. for (var index in this._postProcesses) {
  41000. if (this.applyParameters) {
  41001. this.applyParameters(this._postProcesses[index]);
  41002. }
  41003. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  41004. _this._linkTextures(effect);
  41005. });
  41006. }
  41007. };
  41008. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  41009. for (var renderPassName in this._renderPasses) {
  41010. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  41011. }
  41012. for (var renderEffectName in this._renderEffectAsPasses) {
  41013. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  41014. }
  41015. };
  41016. return PostProcessRenderEffect;
  41017. }());
  41018. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  41019. })(BABYLON || (BABYLON = {}));
  41020. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  41021. var BABYLON;
  41022. (function (BABYLON) {
  41023. var PostProcessRenderPipeline = (function () {
  41024. function PostProcessRenderPipeline(engine, name) {
  41025. this._engine = engine;
  41026. this._name = name;
  41027. this._renderEffects = {};
  41028. this._renderEffectsForIsolatedPass = {};
  41029. this._cameras = [];
  41030. }
  41031. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  41032. get: function () {
  41033. for (var renderEffectName in this._renderEffects) {
  41034. if (!this._renderEffects[renderEffectName].isSupported) {
  41035. return false;
  41036. }
  41037. }
  41038. return true;
  41039. },
  41040. enumerable: true,
  41041. configurable: true
  41042. });
  41043. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  41044. this._renderEffects[renderEffect._name] = renderEffect;
  41045. };
  41046. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  41047. var renderEffects = this._renderEffects[renderEffectName];
  41048. if (!renderEffects) {
  41049. return;
  41050. }
  41051. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  41052. };
  41053. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  41054. var renderEffects = this._renderEffects[renderEffectName];
  41055. if (!renderEffects) {
  41056. return;
  41057. }
  41058. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  41059. };
  41060. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  41061. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41062. var indicesToDelete = [];
  41063. var i;
  41064. for (i = 0; i < _cam.length; i++) {
  41065. var camera = _cam[i];
  41066. var cameraName = camera.name;
  41067. if (this._cameras.indexOf(camera) === -1) {
  41068. this._cameras[cameraName] = camera;
  41069. }
  41070. else if (unique) {
  41071. indicesToDelete.push(i);
  41072. }
  41073. }
  41074. for (i = 0; i < indicesToDelete.length; i++) {
  41075. cameras.splice(indicesToDelete[i], 1);
  41076. }
  41077. for (var renderEffectName in this._renderEffects) {
  41078. this._renderEffects[renderEffectName]._attachCameras(_cam);
  41079. }
  41080. };
  41081. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  41082. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41083. for (var renderEffectName in this._renderEffects) {
  41084. this._renderEffects[renderEffectName]._detachCameras(_cam);
  41085. }
  41086. for (var i = 0; i < _cam.length; i++) {
  41087. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  41088. }
  41089. };
  41090. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  41091. var _this = this;
  41092. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41093. var pass = null;
  41094. var renderEffectName;
  41095. for (renderEffectName in this._renderEffects) {
  41096. pass = this._renderEffects[renderEffectName].getPass(passName);
  41097. if (pass != null) {
  41098. break;
  41099. }
  41100. }
  41101. if (pass === null) {
  41102. return;
  41103. }
  41104. for (renderEffectName in this._renderEffects) {
  41105. this._renderEffects[renderEffectName]._disable(_cam);
  41106. }
  41107. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  41108. for (var i = 0; i < _cam.length; i++) {
  41109. var camera = _cam[i];
  41110. var cameraName = camera.name;
  41111. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  41112. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  41113. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  41114. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  41115. }
  41116. };
  41117. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  41118. var _this = this;
  41119. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  41120. for (var i = 0; i < _cam.length; i++) {
  41121. var camera = _cam[i];
  41122. var cameraName = camera.name;
  41123. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  41124. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  41125. }
  41126. for (var renderEffectName in this._renderEffects) {
  41127. this._renderEffects[renderEffectName]._enable(_cam);
  41128. }
  41129. };
  41130. PostProcessRenderPipeline.prototype._update = function () {
  41131. for (var renderEffectName in this._renderEffects) {
  41132. this._renderEffects[renderEffectName]._update();
  41133. }
  41134. for (var i = 0; i < this._cameras.length; i++) {
  41135. var cameraName = this._cameras[i].name;
  41136. if (this._renderEffectsForIsolatedPass[cameraName]) {
  41137. this._renderEffectsForIsolatedPass[cameraName]._update();
  41138. }
  41139. }
  41140. };
  41141. PostProcessRenderPipeline.prototype.dispose = function () {
  41142. // Must be implemented by children
  41143. };
  41144. return PostProcessRenderPipeline;
  41145. }());
  41146. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  41147. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  41148. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  41149. })(BABYLON || (BABYLON = {}));
  41150. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  41151. var BABYLON;
  41152. (function (BABYLON) {
  41153. var Condition = (function () {
  41154. function Condition(actionManager) {
  41155. this._actionManager = actionManager;
  41156. }
  41157. Condition.prototype.isValid = function () {
  41158. return true;
  41159. };
  41160. Condition.prototype._getProperty = function (propertyPath) {
  41161. return this._actionManager._getProperty(propertyPath);
  41162. };
  41163. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41164. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41165. };
  41166. Condition.prototype.serialize = function () {
  41167. };
  41168. Condition.prototype._serialize = function (serializedCondition) {
  41169. return {
  41170. type: 2,
  41171. children: [],
  41172. name: serializedCondition.name,
  41173. properties: serializedCondition.properties
  41174. };
  41175. };
  41176. return Condition;
  41177. }());
  41178. BABYLON.Condition = Condition;
  41179. var ValueCondition = (function (_super) {
  41180. __extends(ValueCondition, _super);
  41181. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41182. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41183. var _this = _super.call(this, actionManager) || this;
  41184. _this.propertyPath = propertyPath;
  41185. _this.value = value;
  41186. _this.operator = operator;
  41187. _this._target = target;
  41188. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41189. _this._property = _this._getProperty(_this.propertyPath);
  41190. return _this;
  41191. }
  41192. Object.defineProperty(ValueCondition, "IsEqual", {
  41193. get: function () {
  41194. return ValueCondition._IsEqual;
  41195. },
  41196. enumerable: true,
  41197. configurable: true
  41198. });
  41199. Object.defineProperty(ValueCondition, "IsDifferent", {
  41200. get: function () {
  41201. return ValueCondition._IsDifferent;
  41202. },
  41203. enumerable: true,
  41204. configurable: true
  41205. });
  41206. Object.defineProperty(ValueCondition, "IsGreater", {
  41207. get: function () {
  41208. return ValueCondition._IsGreater;
  41209. },
  41210. enumerable: true,
  41211. configurable: true
  41212. });
  41213. Object.defineProperty(ValueCondition, "IsLesser", {
  41214. get: function () {
  41215. return ValueCondition._IsLesser;
  41216. },
  41217. enumerable: true,
  41218. configurable: true
  41219. });
  41220. // Methods
  41221. ValueCondition.prototype.isValid = function () {
  41222. switch (this.operator) {
  41223. case ValueCondition.IsGreater:
  41224. return this._effectiveTarget[this._property] > this.value;
  41225. case ValueCondition.IsLesser:
  41226. return this._effectiveTarget[this._property] < this.value;
  41227. case ValueCondition.IsEqual:
  41228. case ValueCondition.IsDifferent:
  41229. var check;
  41230. if (this.value.equals) {
  41231. check = this.value.equals(this._effectiveTarget[this._property]);
  41232. }
  41233. else {
  41234. check = this.value === this._effectiveTarget[this._property];
  41235. }
  41236. return this.operator === ValueCondition.IsEqual ? check : !check;
  41237. }
  41238. return false;
  41239. };
  41240. ValueCondition.prototype.serialize = function () {
  41241. return this._serialize({
  41242. name: "ValueCondition",
  41243. properties: [
  41244. BABYLON.Action._GetTargetProperty(this._target),
  41245. { name: "propertyPath", value: this.propertyPath },
  41246. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41247. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41248. ]
  41249. });
  41250. };
  41251. ValueCondition.GetOperatorName = function (operator) {
  41252. switch (operator) {
  41253. case ValueCondition._IsEqual: return "IsEqual";
  41254. case ValueCondition._IsDifferent: return "IsDifferent";
  41255. case ValueCondition._IsGreater: return "IsGreater";
  41256. case ValueCondition._IsLesser: return "IsLesser";
  41257. default: return "";
  41258. }
  41259. };
  41260. return ValueCondition;
  41261. }(Condition));
  41262. // Statics
  41263. ValueCondition._IsEqual = 0;
  41264. ValueCondition._IsDifferent = 1;
  41265. ValueCondition._IsGreater = 2;
  41266. ValueCondition._IsLesser = 3;
  41267. BABYLON.ValueCondition = ValueCondition;
  41268. var PredicateCondition = (function (_super) {
  41269. __extends(PredicateCondition, _super);
  41270. function PredicateCondition(actionManager, predicate) {
  41271. var _this = _super.call(this, actionManager) || this;
  41272. _this.predicate = predicate;
  41273. return _this;
  41274. }
  41275. PredicateCondition.prototype.isValid = function () {
  41276. return this.predicate();
  41277. };
  41278. return PredicateCondition;
  41279. }(Condition));
  41280. BABYLON.PredicateCondition = PredicateCondition;
  41281. var StateCondition = (function (_super) {
  41282. __extends(StateCondition, _super);
  41283. function StateCondition(actionManager, target, value) {
  41284. var _this = _super.call(this, actionManager) || this;
  41285. _this.value = value;
  41286. _this._target = target;
  41287. return _this;
  41288. }
  41289. // Methods
  41290. StateCondition.prototype.isValid = function () {
  41291. return this._target.state === this.value;
  41292. };
  41293. StateCondition.prototype.serialize = function () {
  41294. return this._serialize({
  41295. name: "StateCondition",
  41296. properties: [
  41297. BABYLON.Action._GetTargetProperty(this._target),
  41298. { name: "value", value: this.value }
  41299. ]
  41300. });
  41301. };
  41302. return StateCondition;
  41303. }(Condition));
  41304. BABYLON.StateCondition = StateCondition;
  41305. })(BABYLON || (BABYLON = {}));
  41306. //# sourceMappingURL=babylon.condition.js.map
  41307. var BABYLON;
  41308. (function (BABYLON) {
  41309. var Action = (function () {
  41310. function Action(triggerOptions, condition) {
  41311. this.triggerOptions = triggerOptions;
  41312. if (triggerOptions.parameter) {
  41313. this.trigger = triggerOptions.trigger;
  41314. this._triggerParameter = triggerOptions.parameter;
  41315. }
  41316. else {
  41317. this.trigger = triggerOptions;
  41318. }
  41319. this._nextActiveAction = this;
  41320. this._condition = condition;
  41321. }
  41322. // Methods
  41323. Action.prototype._prepare = function () {
  41324. };
  41325. Action.prototype.getTriggerParameter = function () {
  41326. return this._triggerParameter;
  41327. };
  41328. Action.prototype._executeCurrent = function (evt) {
  41329. if (this._nextActiveAction._condition) {
  41330. var condition = this._nextActiveAction._condition;
  41331. var currentRenderId = this._actionManager.getScene().getRenderId();
  41332. // We cache the current evaluation for the current frame
  41333. if (condition._evaluationId === currentRenderId) {
  41334. if (!condition._currentResult) {
  41335. return;
  41336. }
  41337. }
  41338. else {
  41339. condition._evaluationId = currentRenderId;
  41340. if (!condition.isValid()) {
  41341. condition._currentResult = false;
  41342. return;
  41343. }
  41344. condition._currentResult = true;
  41345. }
  41346. }
  41347. this._nextActiveAction.execute(evt);
  41348. this.skipToNextActiveAction();
  41349. };
  41350. Action.prototype.execute = function (evt) {
  41351. };
  41352. Action.prototype.skipToNextActiveAction = function () {
  41353. if (this._nextActiveAction._child) {
  41354. if (!this._nextActiveAction._child._actionManager) {
  41355. this._nextActiveAction._child._actionManager = this._actionManager;
  41356. }
  41357. this._nextActiveAction = this._nextActiveAction._child;
  41358. }
  41359. else {
  41360. this._nextActiveAction = this;
  41361. }
  41362. };
  41363. Action.prototype.then = function (action) {
  41364. this._child = action;
  41365. action._actionManager = this._actionManager;
  41366. action._prepare();
  41367. return action;
  41368. };
  41369. Action.prototype._getProperty = function (propertyPath) {
  41370. return this._actionManager._getProperty(propertyPath);
  41371. };
  41372. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41373. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41374. };
  41375. Action.prototype.serialize = function (parent) {
  41376. };
  41377. // Called by BABYLON.Action objects in serialize(...). Internal use
  41378. Action.prototype._serialize = function (serializedAction, parent) {
  41379. var serializationObject = {
  41380. type: 1,
  41381. children: [],
  41382. name: serializedAction.name,
  41383. properties: serializedAction.properties || []
  41384. };
  41385. // Serialize child
  41386. if (this._child) {
  41387. this._child.serialize(serializationObject);
  41388. }
  41389. // Check if "this" has a condition
  41390. if (this._condition) {
  41391. var serializedCondition = this._condition.serialize();
  41392. serializedCondition.children.push(serializationObject);
  41393. if (parent) {
  41394. parent.children.push(serializedCondition);
  41395. }
  41396. return serializedCondition;
  41397. }
  41398. if (parent) {
  41399. parent.children.push(serializationObject);
  41400. }
  41401. return serializationObject;
  41402. };
  41403. return Action;
  41404. }());
  41405. Action._SerializeValueAsString = function (value) {
  41406. if (typeof value === "number") {
  41407. return value.toString();
  41408. }
  41409. if (typeof value === "boolean") {
  41410. return value ? "true" : "false";
  41411. }
  41412. if (value instanceof BABYLON.Vector2) {
  41413. return value.x + ", " + value.y;
  41414. }
  41415. if (value instanceof BABYLON.Vector3) {
  41416. return value.x + ", " + value.y + ", " + value.z;
  41417. }
  41418. if (value instanceof BABYLON.Color3) {
  41419. return value.r + ", " + value.g + ", " + value.b;
  41420. }
  41421. if (value instanceof BABYLON.Color4) {
  41422. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41423. }
  41424. return value; // string
  41425. };
  41426. Action._GetTargetProperty = function (target) {
  41427. return {
  41428. name: "target",
  41429. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41430. : target instanceof BABYLON.Light ? "LightProperties"
  41431. : target instanceof BABYLON.Camera ? "CameraProperties"
  41432. : "SceneProperties",
  41433. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41434. };
  41435. };
  41436. BABYLON.Action = Action;
  41437. })(BABYLON || (BABYLON = {}));
  41438. //# sourceMappingURL=babylon.action.js.map
  41439. var BABYLON;
  41440. (function (BABYLON) {
  41441. /**
  41442. * ActionEvent is the event beint sent when an action is triggered.
  41443. */
  41444. var ActionEvent = (function () {
  41445. /**
  41446. * @constructor
  41447. * @param source The mesh or sprite that triggered the action.
  41448. * @param pointerX The X mouse cursor position at the time of the event
  41449. * @param pointerY The Y mouse cursor position at the time of the event
  41450. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41451. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41452. */
  41453. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41454. this.source = source;
  41455. this.pointerX = pointerX;
  41456. this.pointerY = pointerY;
  41457. this.meshUnderPointer = meshUnderPointer;
  41458. this.sourceEvent = sourceEvent;
  41459. this.additionalData = additionalData;
  41460. }
  41461. /**
  41462. * Helper function to auto-create an ActionEvent from a source mesh.
  41463. * @param source The source mesh that triggered the event
  41464. * @param evt {Event} The original (browser) event
  41465. */
  41466. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41467. var scene = source.getScene();
  41468. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41469. };
  41470. /**
  41471. * Helper function to auto-create an ActionEvent from a source mesh.
  41472. * @param source The source sprite that triggered the event
  41473. * @param scene Scene associated with the sprite
  41474. * @param evt {Event} The original (browser) event
  41475. */
  41476. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41477. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41478. };
  41479. /**
  41480. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41481. * @param scene the scene where the event occurred
  41482. * @param evt {Event} The original (browser) event
  41483. */
  41484. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41485. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41486. };
  41487. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41488. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41489. };
  41490. return ActionEvent;
  41491. }());
  41492. BABYLON.ActionEvent = ActionEvent;
  41493. /**
  41494. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41495. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41496. */
  41497. var ActionManager = (function () {
  41498. function ActionManager(scene) {
  41499. // Members
  41500. this.actions = new Array();
  41501. this.hoverCursor = '';
  41502. this._scene = scene;
  41503. scene._actionManagers.push(this);
  41504. }
  41505. Object.defineProperty(ActionManager, "NothingTrigger", {
  41506. get: function () {
  41507. return ActionManager._NothingTrigger;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41513. get: function () {
  41514. return ActionManager._OnPickTrigger;
  41515. },
  41516. enumerable: true,
  41517. configurable: true
  41518. });
  41519. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41520. get: function () {
  41521. return ActionManager._OnLeftPickTrigger;
  41522. },
  41523. enumerable: true,
  41524. configurable: true
  41525. });
  41526. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41527. get: function () {
  41528. return ActionManager._OnRightPickTrigger;
  41529. },
  41530. enumerable: true,
  41531. configurable: true
  41532. });
  41533. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41534. get: function () {
  41535. return ActionManager._OnCenterPickTrigger;
  41536. },
  41537. enumerable: true,
  41538. configurable: true
  41539. });
  41540. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41541. get: function () {
  41542. return ActionManager._OnPickDownTrigger;
  41543. },
  41544. enumerable: true,
  41545. configurable: true
  41546. });
  41547. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41548. get: function () {
  41549. return ActionManager._OnDoublePickTrigger;
  41550. },
  41551. enumerable: true,
  41552. configurable: true
  41553. });
  41554. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41555. get: function () {
  41556. return ActionManager._OnPickUpTrigger;
  41557. },
  41558. enumerable: true,
  41559. configurable: true
  41560. });
  41561. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41562. /// This trigger will only be raised if you also declared a OnPickDown
  41563. get: function () {
  41564. return ActionManager._OnPickOutTrigger;
  41565. },
  41566. enumerable: true,
  41567. configurable: true
  41568. });
  41569. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41570. get: function () {
  41571. return ActionManager._OnLongPressTrigger;
  41572. },
  41573. enumerable: true,
  41574. configurable: true
  41575. });
  41576. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41577. get: function () {
  41578. return ActionManager._OnPointerOverTrigger;
  41579. },
  41580. enumerable: true,
  41581. configurable: true
  41582. });
  41583. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41584. get: function () {
  41585. return ActionManager._OnPointerOutTrigger;
  41586. },
  41587. enumerable: true,
  41588. configurable: true
  41589. });
  41590. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41591. get: function () {
  41592. return ActionManager._OnEveryFrameTrigger;
  41593. },
  41594. enumerable: true,
  41595. configurable: true
  41596. });
  41597. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41598. get: function () {
  41599. return ActionManager._OnIntersectionEnterTrigger;
  41600. },
  41601. enumerable: true,
  41602. configurable: true
  41603. });
  41604. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41605. get: function () {
  41606. return ActionManager._OnIntersectionExitTrigger;
  41607. },
  41608. enumerable: true,
  41609. configurable: true
  41610. });
  41611. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41612. get: function () {
  41613. return ActionManager._OnKeyDownTrigger;
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41619. get: function () {
  41620. return ActionManager._OnKeyUpTrigger;
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. // Methods
  41626. ActionManager.prototype.dispose = function () {
  41627. var index = this._scene._actionManagers.indexOf(this);
  41628. for (var i = 0; i < this.actions.length; i++) {
  41629. var action = this.actions[i];
  41630. ActionManager.Triggers[action.trigger]--;
  41631. if (ActionManager.Triggers[action.trigger] === 0) {
  41632. delete ActionManager.Triggers[action.trigger];
  41633. }
  41634. }
  41635. if (index > -1) {
  41636. this._scene._actionManagers.splice(index, 1);
  41637. }
  41638. };
  41639. ActionManager.prototype.getScene = function () {
  41640. return this._scene;
  41641. };
  41642. /**
  41643. * Does this action manager handles actions of any of the given triggers
  41644. * @param {number[]} triggers - the triggers to be tested
  41645. * @return {boolean} whether one (or more) of the triggers is handeled
  41646. */
  41647. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41648. for (var index = 0; index < this.actions.length; index++) {
  41649. var action = this.actions[index];
  41650. if (triggers.indexOf(action.trigger) > -1) {
  41651. return true;
  41652. }
  41653. }
  41654. return false;
  41655. };
  41656. /**
  41657. * Does this action manager handles actions of a given trigger
  41658. * @param {number} trigger - the trigger to be tested
  41659. * @return {boolean} whether the trigger is handeled
  41660. */
  41661. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41662. for (var index = 0; index < this.actions.length; index++) {
  41663. var action = this.actions[index];
  41664. if (action.trigger === trigger) {
  41665. return true;
  41666. }
  41667. }
  41668. return false;
  41669. };
  41670. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41671. /**
  41672. * Does this action manager has pointer triggers
  41673. * @return {boolean} whether or not it has pointer triggers
  41674. */
  41675. get: function () {
  41676. for (var index = 0; index < this.actions.length; index++) {
  41677. var action = this.actions[index];
  41678. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41679. return true;
  41680. }
  41681. }
  41682. return false;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41688. /**
  41689. * Does this action manager has pick triggers
  41690. * @return {boolean} whether or not it has pick triggers
  41691. */
  41692. get: function () {
  41693. for (var index = 0; index < this.actions.length; index++) {
  41694. var action = this.actions[index];
  41695. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41696. return true;
  41697. }
  41698. }
  41699. return false;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(ActionManager, "HasTriggers", {
  41705. /**
  41706. * Does exist one action manager with at least one trigger
  41707. * @return {boolean} whether or not it exists one action manager with one trigger
  41708. **/
  41709. get: function () {
  41710. for (var t in ActionManager.Triggers) {
  41711. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41712. return true;
  41713. }
  41714. }
  41715. return false;
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41721. /**
  41722. * Does exist one action manager with at least one pick trigger
  41723. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41724. **/
  41725. get: function () {
  41726. for (var t in ActionManager.Triggers) {
  41727. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41728. var t_int = parseInt(t);
  41729. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41730. return true;
  41731. }
  41732. }
  41733. }
  41734. return false;
  41735. },
  41736. enumerable: true,
  41737. configurable: true
  41738. });
  41739. /**
  41740. * Does exist one action manager that handles actions of a given trigger
  41741. * @param {number} trigger - the trigger to be tested
  41742. * @return {boolean} whether the trigger is handeled by at least one action manager
  41743. **/
  41744. ActionManager.HasSpecificTrigger = function (trigger) {
  41745. for (var t in ActionManager.Triggers) {
  41746. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41747. var t_int = parseInt(t);
  41748. if (t_int === trigger) {
  41749. return true;
  41750. }
  41751. }
  41752. }
  41753. return false;
  41754. };
  41755. /**
  41756. * Registers an action to this action manager
  41757. * @param {BABYLON.Action} action - the action to be registered
  41758. * @return {BABYLON.Action} the action amended (prepared) after registration
  41759. */
  41760. ActionManager.prototype.registerAction = function (action) {
  41761. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41762. if (this.getScene().actionManager !== this) {
  41763. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41764. return null;
  41765. }
  41766. }
  41767. this.actions.push(action);
  41768. if (ActionManager.Triggers[action.trigger]) {
  41769. ActionManager.Triggers[action.trigger]++;
  41770. }
  41771. else {
  41772. ActionManager.Triggers[action.trigger] = 1;
  41773. }
  41774. action._actionManager = this;
  41775. action._prepare();
  41776. return action;
  41777. };
  41778. /**
  41779. * Process a specific trigger
  41780. * @param {number} trigger - the trigger to process
  41781. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41782. */
  41783. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41784. for (var index = 0; index < this.actions.length; index++) {
  41785. var action = this.actions[index];
  41786. if (action.trigger === trigger) {
  41787. if (trigger === ActionManager.OnKeyUpTrigger
  41788. || trigger === ActionManager.OnKeyDownTrigger) {
  41789. var parameter = action.getTriggerParameter();
  41790. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41791. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41792. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41793. if (actualkey !== parameter.toLowerCase()) {
  41794. continue;
  41795. }
  41796. }
  41797. }
  41798. action._executeCurrent(evt);
  41799. }
  41800. }
  41801. };
  41802. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41803. var properties = propertyPath.split(".");
  41804. for (var index = 0; index < properties.length - 1; index++) {
  41805. target = target[properties[index]];
  41806. }
  41807. return target;
  41808. };
  41809. ActionManager.prototype._getProperty = function (propertyPath) {
  41810. var properties = propertyPath.split(".");
  41811. return properties[properties.length - 1];
  41812. };
  41813. ActionManager.prototype.serialize = function (name) {
  41814. var root = {
  41815. children: [],
  41816. name: name,
  41817. type: 3,
  41818. properties: [] // Empty for root but required
  41819. };
  41820. for (var i = 0; i < this.actions.length; i++) {
  41821. var triggerObject = {
  41822. type: 0,
  41823. children: [],
  41824. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41825. properties: []
  41826. };
  41827. var triggerOptions = this.actions[i].triggerOptions;
  41828. if (triggerOptions && typeof triggerOptions !== "number") {
  41829. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41830. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41831. }
  41832. else {
  41833. var parameter = {};
  41834. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41835. if (triggerOptions.parameter.mesh) {
  41836. parameter._meshId = triggerOptions.parameter.mesh.id;
  41837. }
  41838. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41839. }
  41840. }
  41841. // Serialize child action, recursively
  41842. this.actions[i].serialize(triggerObject);
  41843. // Add serialized trigger
  41844. root.children.push(triggerObject);
  41845. }
  41846. return root;
  41847. };
  41848. ActionManager.Parse = function (parsedActions, object, scene) {
  41849. var actionManager = new BABYLON.ActionManager(scene);
  41850. if (object === null)
  41851. scene.actionManager = actionManager;
  41852. else
  41853. object.actionManager = actionManager;
  41854. // instanciate a new object
  41855. var instanciate = function (name, params) {
  41856. var newInstance = Object.create(BABYLON[name].prototype);
  41857. newInstance.constructor.apply(newInstance, params);
  41858. return newInstance;
  41859. };
  41860. var parseParameter = function (name, value, target, propertyPath) {
  41861. if (propertyPath === null) {
  41862. // String, boolean or float
  41863. var floatValue = parseFloat(value);
  41864. if (value === "true" || value === "false")
  41865. return value === "true";
  41866. else
  41867. return isNaN(floatValue) ? value : floatValue;
  41868. }
  41869. var effectiveTarget = propertyPath.split(".");
  41870. var values = value.split(",");
  41871. // Get effective Target
  41872. for (var i = 0; i < effectiveTarget.length; i++) {
  41873. target = target[effectiveTarget[i]];
  41874. }
  41875. // Return appropriate value with its type
  41876. if (typeof (target) === "boolean")
  41877. return values[0] === "true";
  41878. if (typeof (target) === "string")
  41879. return values[0];
  41880. // Parameters with multiple values such as Vector3 etc.
  41881. var split = new Array();
  41882. for (var i = 0; i < values.length; i++)
  41883. split.push(parseFloat(values[i]));
  41884. if (target instanceof BABYLON.Vector3)
  41885. return BABYLON.Vector3.FromArray(split);
  41886. if (target instanceof BABYLON.Vector4)
  41887. return BABYLON.Vector4.FromArray(split);
  41888. if (target instanceof BABYLON.Color3)
  41889. return BABYLON.Color3.FromArray(split);
  41890. if (target instanceof BABYLON.Color4)
  41891. return BABYLON.Color4.FromArray(split);
  41892. return parseFloat(values[0]);
  41893. };
  41894. // traverse graph per trigger
  41895. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41896. if (combineArray === void 0) { combineArray = null; }
  41897. if (parsedAction.detached)
  41898. return;
  41899. var parameters = new Array();
  41900. var target = null;
  41901. var propertyPath = null;
  41902. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41903. // Parameters
  41904. if (parsedAction.type === 2)
  41905. parameters.push(actionManager);
  41906. else
  41907. parameters.push(trigger);
  41908. if (combine) {
  41909. var actions = new Array();
  41910. for (var j = 0; j < parsedAction.combine.length; j++) {
  41911. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41912. }
  41913. parameters.push(actions);
  41914. }
  41915. else {
  41916. for (var i = 0; i < parsedAction.properties.length; i++) {
  41917. var value = parsedAction.properties[i].value;
  41918. var name = parsedAction.properties[i].name;
  41919. var targetType = parsedAction.properties[i].targetType;
  41920. if (name === "target")
  41921. if (targetType !== null && targetType === "SceneProperties")
  41922. value = target = scene;
  41923. else
  41924. value = target = scene.getNodeByName(value);
  41925. else if (name === "parent")
  41926. value = scene.getNodeByName(value);
  41927. else if (name === "sound")
  41928. value = scene.getSoundByName(value);
  41929. else if (name !== "propertyPath") {
  41930. if (parsedAction.type === 2 && name === "operator")
  41931. value = BABYLON.ValueCondition[value];
  41932. else
  41933. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41934. }
  41935. else {
  41936. propertyPath = value;
  41937. }
  41938. parameters.push(value);
  41939. }
  41940. }
  41941. if (combineArray === null) {
  41942. parameters.push(condition);
  41943. }
  41944. else {
  41945. parameters.push(null);
  41946. }
  41947. // If interpolate value action
  41948. if (parsedAction.name === "InterpolateValueAction") {
  41949. var param = parameters[parameters.length - 2];
  41950. parameters[parameters.length - 1] = param;
  41951. parameters[parameters.length - 2] = condition;
  41952. }
  41953. // Action or condition(s) and not CombineAction
  41954. var newAction = instanciate(parsedAction.name, parameters);
  41955. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41956. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41957. if (action)
  41958. action.then(nothing);
  41959. else
  41960. actionManager.registerAction(nothing);
  41961. action = nothing;
  41962. }
  41963. if (combineArray === null) {
  41964. if (newAction instanceof BABYLON.Condition) {
  41965. condition = newAction;
  41966. newAction = action;
  41967. }
  41968. else {
  41969. condition = null;
  41970. if (action)
  41971. action.then(newAction);
  41972. else
  41973. actionManager.registerAction(newAction);
  41974. }
  41975. }
  41976. else {
  41977. combineArray.push(newAction);
  41978. }
  41979. for (var i = 0; i < parsedAction.children.length; i++)
  41980. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41981. };
  41982. // triggers
  41983. for (var i = 0; i < parsedActions.children.length; i++) {
  41984. var triggerParams;
  41985. var trigger = parsedActions.children[i];
  41986. if (trigger.properties.length > 0) {
  41987. var param = trigger.properties[0].value;
  41988. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41989. if (value._meshId) {
  41990. value.mesh = scene.getMeshByID(value._meshId);
  41991. }
  41992. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  41993. }
  41994. else
  41995. triggerParams = BABYLON.ActionManager[trigger.name];
  41996. for (var j = 0; j < trigger.children.length; j++) {
  41997. if (!trigger.detached)
  41998. traverse(trigger.children[j], triggerParams, null, null);
  41999. }
  42000. }
  42001. };
  42002. ActionManager.GetTriggerName = function (trigger) {
  42003. switch (trigger) {
  42004. case 0: return "NothingTrigger";
  42005. case 1: return "OnPickTrigger";
  42006. case 2: return "OnLeftPickTrigger";
  42007. case 3: return "OnRightPickTrigger";
  42008. case 4: return "OnCenterPickTrigger";
  42009. case 5: return "OnPickDownTrigger";
  42010. case 6: return "OnPickUpTrigger";
  42011. case 7: return "OnLongPressTrigger";
  42012. case 8: return "OnPointerOverTrigger";
  42013. case 9: return "OnPointerOutTrigger";
  42014. case 10: return "OnEveryFrameTrigger";
  42015. case 11: return "OnIntersectionEnterTrigger";
  42016. case 12: return "OnIntersectionExitTrigger";
  42017. case 13: return "OnKeyDownTrigger";
  42018. case 14: return "OnKeyUpTrigger";
  42019. case 15: return "OnPickOutTrigger";
  42020. default: return "";
  42021. }
  42022. };
  42023. return ActionManager;
  42024. }());
  42025. // Statics
  42026. ActionManager._NothingTrigger = 0;
  42027. ActionManager._OnPickTrigger = 1;
  42028. ActionManager._OnLeftPickTrigger = 2;
  42029. ActionManager._OnRightPickTrigger = 3;
  42030. ActionManager._OnCenterPickTrigger = 4;
  42031. ActionManager._OnPickDownTrigger = 5;
  42032. ActionManager._OnDoublePickTrigger = 6;
  42033. ActionManager._OnPickUpTrigger = 7;
  42034. ActionManager._OnLongPressTrigger = 8;
  42035. ActionManager._OnPointerOverTrigger = 9;
  42036. ActionManager._OnPointerOutTrigger = 10;
  42037. ActionManager._OnEveryFrameTrigger = 11;
  42038. ActionManager._OnIntersectionEnterTrigger = 12;
  42039. ActionManager._OnIntersectionExitTrigger = 13;
  42040. ActionManager._OnKeyDownTrigger = 14;
  42041. ActionManager._OnKeyUpTrigger = 15;
  42042. ActionManager._OnPickOutTrigger = 16;
  42043. ActionManager.Triggers = {};
  42044. BABYLON.ActionManager = ActionManager;
  42045. })(BABYLON || (BABYLON = {}));
  42046. //# sourceMappingURL=babylon.actionManager.js.map
  42047. var BABYLON;
  42048. (function (BABYLON) {
  42049. var InterpolateValueAction = (function (_super) {
  42050. __extends(InterpolateValueAction, _super);
  42051. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42052. if (duration === void 0) { duration = 1000; }
  42053. var _this = _super.call(this, triggerOptions, condition) || this;
  42054. _this.propertyPath = propertyPath;
  42055. _this.value = value;
  42056. _this.duration = duration;
  42057. _this.stopOtherAnimations = stopOtherAnimations;
  42058. _this.onInterpolationDone = onInterpolationDone;
  42059. _this._target = _this._effectiveTarget = target;
  42060. return _this;
  42061. }
  42062. InterpolateValueAction.prototype._prepare = function () {
  42063. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42064. this._property = this._getProperty(this.propertyPath);
  42065. };
  42066. InterpolateValueAction.prototype.execute = function () {
  42067. var scene = this._actionManager.getScene();
  42068. var keys = [
  42069. {
  42070. frame: 0,
  42071. value: this._effectiveTarget[this._property]
  42072. }, {
  42073. frame: 100,
  42074. value: this.value
  42075. }
  42076. ];
  42077. var dataType;
  42078. if (typeof this.value === "number") {
  42079. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42080. }
  42081. else if (this.value instanceof BABYLON.Color3) {
  42082. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42083. }
  42084. else if (this.value instanceof BABYLON.Vector3) {
  42085. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42086. }
  42087. else if (this.value instanceof BABYLON.Matrix) {
  42088. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42089. }
  42090. else if (this.value instanceof BABYLON.Quaternion) {
  42091. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42092. }
  42093. else {
  42094. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42095. return;
  42096. }
  42097. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42098. animation.setKeys(keys);
  42099. if (this.stopOtherAnimations) {
  42100. scene.stopAnimation(this._effectiveTarget);
  42101. }
  42102. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  42103. };
  42104. InterpolateValueAction.prototype.serialize = function (parent) {
  42105. return _super.prototype._serialize.call(this, {
  42106. name: "InterpolateValueAction",
  42107. properties: [
  42108. BABYLON.Action._GetTargetProperty(this._target),
  42109. { name: "propertyPath", value: this.propertyPath },
  42110. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42111. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42112. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42113. ]
  42114. }, parent);
  42115. };
  42116. return InterpolateValueAction;
  42117. }(BABYLON.Action));
  42118. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42119. })(BABYLON || (BABYLON = {}));
  42120. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42121. var BABYLON;
  42122. (function (BABYLON) {
  42123. var SwitchBooleanAction = (function (_super) {
  42124. __extends(SwitchBooleanAction, _super);
  42125. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42126. var _this = _super.call(this, triggerOptions, condition) || this;
  42127. _this.propertyPath = propertyPath;
  42128. _this._target = _this._effectiveTarget = target;
  42129. return _this;
  42130. }
  42131. SwitchBooleanAction.prototype._prepare = function () {
  42132. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42133. this._property = this._getProperty(this.propertyPath);
  42134. };
  42135. SwitchBooleanAction.prototype.execute = function () {
  42136. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42137. };
  42138. SwitchBooleanAction.prototype.serialize = function (parent) {
  42139. return _super.prototype._serialize.call(this, {
  42140. name: "SwitchBooleanAction",
  42141. properties: [
  42142. BABYLON.Action._GetTargetProperty(this._target),
  42143. { name: "propertyPath", value: this.propertyPath }
  42144. ]
  42145. }, parent);
  42146. };
  42147. return SwitchBooleanAction;
  42148. }(BABYLON.Action));
  42149. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42150. var SetStateAction = (function (_super) {
  42151. __extends(SetStateAction, _super);
  42152. function SetStateAction(triggerOptions, target, value, condition) {
  42153. var _this = _super.call(this, triggerOptions, condition) || this;
  42154. _this.value = value;
  42155. _this._target = target;
  42156. return _this;
  42157. }
  42158. SetStateAction.prototype.execute = function () {
  42159. this._target.state = this.value;
  42160. };
  42161. SetStateAction.prototype.serialize = function (parent) {
  42162. return _super.prototype._serialize.call(this, {
  42163. name: "SetStateAction",
  42164. properties: [
  42165. BABYLON.Action._GetTargetProperty(this._target),
  42166. { name: "value", value: this.value }
  42167. ]
  42168. }, parent);
  42169. };
  42170. return SetStateAction;
  42171. }(BABYLON.Action));
  42172. BABYLON.SetStateAction = SetStateAction;
  42173. var SetValueAction = (function (_super) {
  42174. __extends(SetValueAction, _super);
  42175. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42176. var _this = _super.call(this, triggerOptions, condition) || this;
  42177. _this.propertyPath = propertyPath;
  42178. _this.value = value;
  42179. _this._target = _this._effectiveTarget = target;
  42180. return _this;
  42181. }
  42182. SetValueAction.prototype._prepare = function () {
  42183. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42184. this._property = this._getProperty(this.propertyPath);
  42185. };
  42186. SetValueAction.prototype.execute = function () {
  42187. this._effectiveTarget[this._property] = this.value;
  42188. if (this._target.markAsDirty) {
  42189. this._target.markAsDirty(this._property);
  42190. }
  42191. };
  42192. SetValueAction.prototype.serialize = function (parent) {
  42193. return _super.prototype._serialize.call(this, {
  42194. name: "SetValueAction",
  42195. properties: [
  42196. BABYLON.Action._GetTargetProperty(this._target),
  42197. { name: "propertyPath", value: this.propertyPath },
  42198. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42199. ]
  42200. }, parent);
  42201. };
  42202. return SetValueAction;
  42203. }(BABYLON.Action));
  42204. BABYLON.SetValueAction = SetValueAction;
  42205. var IncrementValueAction = (function (_super) {
  42206. __extends(IncrementValueAction, _super);
  42207. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42208. var _this = _super.call(this, triggerOptions, condition) || this;
  42209. _this.propertyPath = propertyPath;
  42210. _this.value = value;
  42211. _this._target = _this._effectiveTarget = target;
  42212. return _this;
  42213. }
  42214. IncrementValueAction.prototype._prepare = function () {
  42215. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42216. this._property = this._getProperty(this.propertyPath);
  42217. if (typeof this._effectiveTarget[this._property] !== "number") {
  42218. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42219. }
  42220. };
  42221. IncrementValueAction.prototype.execute = function () {
  42222. this._effectiveTarget[this._property] += this.value;
  42223. if (this._target.markAsDirty) {
  42224. this._target.markAsDirty(this._property);
  42225. }
  42226. };
  42227. IncrementValueAction.prototype.serialize = function (parent) {
  42228. return _super.prototype._serialize.call(this, {
  42229. name: "IncrementValueAction",
  42230. properties: [
  42231. BABYLON.Action._GetTargetProperty(this._target),
  42232. { name: "propertyPath", value: this.propertyPath },
  42233. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42234. ]
  42235. }, parent);
  42236. };
  42237. return IncrementValueAction;
  42238. }(BABYLON.Action));
  42239. BABYLON.IncrementValueAction = IncrementValueAction;
  42240. var PlayAnimationAction = (function (_super) {
  42241. __extends(PlayAnimationAction, _super);
  42242. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42243. var _this = _super.call(this, triggerOptions, condition) || this;
  42244. _this.from = from;
  42245. _this.to = to;
  42246. _this.loop = loop;
  42247. _this._target = target;
  42248. return _this;
  42249. }
  42250. PlayAnimationAction.prototype._prepare = function () {
  42251. };
  42252. PlayAnimationAction.prototype.execute = function () {
  42253. var scene = this._actionManager.getScene();
  42254. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42255. };
  42256. PlayAnimationAction.prototype.serialize = function (parent) {
  42257. return _super.prototype._serialize.call(this, {
  42258. name: "PlayAnimationAction",
  42259. properties: [
  42260. BABYLON.Action._GetTargetProperty(this._target),
  42261. { name: "from", value: String(this.from) },
  42262. { name: "to", value: String(this.to) },
  42263. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42264. ]
  42265. }, parent);
  42266. };
  42267. return PlayAnimationAction;
  42268. }(BABYLON.Action));
  42269. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42270. var StopAnimationAction = (function (_super) {
  42271. __extends(StopAnimationAction, _super);
  42272. function StopAnimationAction(triggerOptions, target, condition) {
  42273. var _this = _super.call(this, triggerOptions, condition) || this;
  42274. _this._target = target;
  42275. return _this;
  42276. }
  42277. StopAnimationAction.prototype._prepare = function () {
  42278. };
  42279. StopAnimationAction.prototype.execute = function () {
  42280. var scene = this._actionManager.getScene();
  42281. scene.stopAnimation(this._target);
  42282. };
  42283. StopAnimationAction.prototype.serialize = function (parent) {
  42284. return _super.prototype._serialize.call(this, {
  42285. name: "StopAnimationAction",
  42286. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42287. }, parent);
  42288. };
  42289. return StopAnimationAction;
  42290. }(BABYLON.Action));
  42291. BABYLON.StopAnimationAction = StopAnimationAction;
  42292. var DoNothingAction = (function (_super) {
  42293. __extends(DoNothingAction, _super);
  42294. function DoNothingAction(triggerOptions, condition) {
  42295. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42296. return _super.call(this, triggerOptions, condition) || this;
  42297. }
  42298. DoNothingAction.prototype.execute = function () {
  42299. };
  42300. DoNothingAction.prototype.serialize = function (parent) {
  42301. return _super.prototype._serialize.call(this, {
  42302. name: "DoNothingAction",
  42303. properties: []
  42304. }, parent);
  42305. };
  42306. return DoNothingAction;
  42307. }(BABYLON.Action));
  42308. BABYLON.DoNothingAction = DoNothingAction;
  42309. var CombineAction = (function (_super) {
  42310. __extends(CombineAction, _super);
  42311. function CombineAction(triggerOptions, children, condition) {
  42312. var _this = _super.call(this, triggerOptions, condition) || this;
  42313. _this.children = children;
  42314. return _this;
  42315. }
  42316. CombineAction.prototype._prepare = function () {
  42317. for (var index = 0; index < this.children.length; index++) {
  42318. this.children[index]._actionManager = this._actionManager;
  42319. this.children[index]._prepare();
  42320. }
  42321. };
  42322. CombineAction.prototype.execute = function (evt) {
  42323. for (var index = 0; index < this.children.length; index++) {
  42324. this.children[index].execute(evt);
  42325. }
  42326. };
  42327. CombineAction.prototype.serialize = function (parent) {
  42328. var serializationObject = _super.prototype._serialize.call(this, {
  42329. name: "CombineAction",
  42330. properties: [],
  42331. combine: []
  42332. }, parent);
  42333. for (var i = 0; i < this.children.length; i++) {
  42334. serializationObject.combine.push(this.children[i].serialize(null));
  42335. }
  42336. return serializationObject;
  42337. };
  42338. return CombineAction;
  42339. }(BABYLON.Action));
  42340. BABYLON.CombineAction = CombineAction;
  42341. var ExecuteCodeAction = (function (_super) {
  42342. __extends(ExecuteCodeAction, _super);
  42343. function ExecuteCodeAction(triggerOptions, func, condition) {
  42344. var _this = _super.call(this, triggerOptions, condition) || this;
  42345. _this.func = func;
  42346. return _this;
  42347. }
  42348. ExecuteCodeAction.prototype.execute = function (evt) {
  42349. this.func(evt);
  42350. };
  42351. return ExecuteCodeAction;
  42352. }(BABYLON.Action));
  42353. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42354. var SetParentAction = (function (_super) {
  42355. __extends(SetParentAction, _super);
  42356. function SetParentAction(triggerOptions, target, parent, condition) {
  42357. var _this = _super.call(this, triggerOptions, condition) || this;
  42358. _this._target = target;
  42359. _this._parent = parent;
  42360. return _this;
  42361. }
  42362. SetParentAction.prototype._prepare = function () {
  42363. };
  42364. SetParentAction.prototype.execute = function () {
  42365. if (this._target.parent === this._parent) {
  42366. return;
  42367. }
  42368. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42369. invertParentWorldMatrix.invert();
  42370. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42371. this._target.parent = this._parent;
  42372. };
  42373. SetParentAction.prototype.serialize = function (parent) {
  42374. return _super.prototype._serialize.call(this, {
  42375. name: "SetParentAction",
  42376. properties: [
  42377. BABYLON.Action._GetTargetProperty(this._target),
  42378. BABYLON.Action._GetTargetProperty(this._parent),
  42379. ]
  42380. }, parent);
  42381. };
  42382. return SetParentAction;
  42383. }(BABYLON.Action));
  42384. BABYLON.SetParentAction = SetParentAction;
  42385. var PlaySoundAction = (function (_super) {
  42386. __extends(PlaySoundAction, _super);
  42387. function PlaySoundAction(triggerOptions, sound, condition) {
  42388. var _this = _super.call(this, triggerOptions, condition) || this;
  42389. _this._sound = sound;
  42390. return _this;
  42391. }
  42392. PlaySoundAction.prototype._prepare = function () {
  42393. };
  42394. PlaySoundAction.prototype.execute = function () {
  42395. if (this._sound !== undefined)
  42396. this._sound.play();
  42397. };
  42398. PlaySoundAction.prototype.serialize = function (parent) {
  42399. return _super.prototype._serialize.call(this, {
  42400. name: "PlaySoundAction",
  42401. properties: [{ name: "sound", value: this._sound.name }]
  42402. }, parent);
  42403. };
  42404. return PlaySoundAction;
  42405. }(BABYLON.Action));
  42406. BABYLON.PlaySoundAction = PlaySoundAction;
  42407. var StopSoundAction = (function (_super) {
  42408. __extends(StopSoundAction, _super);
  42409. function StopSoundAction(triggerOptions, sound, condition) {
  42410. var _this = _super.call(this, triggerOptions, condition) || this;
  42411. _this._sound = sound;
  42412. return _this;
  42413. }
  42414. StopSoundAction.prototype._prepare = function () {
  42415. };
  42416. StopSoundAction.prototype.execute = function () {
  42417. if (this._sound !== undefined)
  42418. this._sound.stop();
  42419. };
  42420. StopSoundAction.prototype.serialize = function (parent) {
  42421. return _super.prototype._serialize.call(this, {
  42422. name: "StopSoundAction",
  42423. properties: [{ name: "sound", value: this._sound.name }]
  42424. }, parent);
  42425. };
  42426. return StopSoundAction;
  42427. }(BABYLON.Action));
  42428. BABYLON.StopSoundAction = StopSoundAction;
  42429. })(BABYLON || (BABYLON = {}));
  42430. //# sourceMappingURL=babylon.directActions.js.map
  42431. var BABYLON;
  42432. (function (BABYLON) {
  42433. var Geometry = (function () {
  42434. function Geometry(id, scene, vertexData, updatable, mesh) {
  42435. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  42436. this._totalVertices = 0;
  42437. this._isDisposed = false;
  42438. this.id = id;
  42439. this._engine = scene.getEngine();
  42440. this._meshes = [];
  42441. this._scene = scene;
  42442. //Init vertex buffer cache
  42443. this._vertexBuffers = {};
  42444. this._indices = [];
  42445. // vertexData
  42446. if (vertexData) {
  42447. this.setAllVerticesData(vertexData, updatable);
  42448. }
  42449. else {
  42450. this._totalVertices = 0;
  42451. this._indices = [];
  42452. }
  42453. if (this._engine.getCaps().vertexArrayObject) {
  42454. this._vertexArrayObjects = {};
  42455. }
  42456. // applyToMesh
  42457. if (mesh) {
  42458. if (mesh.getClassName() === "LinesMesh") {
  42459. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  42460. this.updateExtend();
  42461. }
  42462. this.applyToMesh(mesh);
  42463. mesh.computeWorldMatrix(true);
  42464. }
  42465. }
  42466. Object.defineProperty(Geometry.prototype, "boundingBias", {
  42467. /**
  42468. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  42469. * @returns The Bias Vector
  42470. */
  42471. get: function () {
  42472. return this._boundingBias;
  42473. },
  42474. set: function (value) {
  42475. if (this._boundingBias && this._boundingBias.equals(value)) {
  42476. return;
  42477. }
  42478. this._boundingBias = value.clone();
  42479. this.updateBoundingInfo(true, null);
  42480. },
  42481. enumerable: true,
  42482. configurable: true
  42483. });
  42484. Object.defineProperty(Geometry.prototype, "extend", {
  42485. get: function () {
  42486. return this._extend;
  42487. },
  42488. enumerable: true,
  42489. configurable: true
  42490. });
  42491. Geometry.prototype.getScene = function () {
  42492. return this._scene;
  42493. };
  42494. Geometry.prototype.getEngine = function () {
  42495. return this._engine;
  42496. };
  42497. Geometry.prototype.isReady = function () {
  42498. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  42499. };
  42500. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  42501. get: function () {
  42502. for (var index = 0; index < this._meshes.length; index++) {
  42503. if (!this._meshes[index].doNotSerialize) {
  42504. return false;
  42505. }
  42506. }
  42507. return true;
  42508. },
  42509. enumerable: true,
  42510. configurable: true
  42511. });
  42512. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  42513. vertexData.applyToGeometry(this, updatable);
  42514. this.notifyUpdate();
  42515. };
  42516. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42517. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  42518. this.setVerticesBuffer(buffer);
  42519. };
  42520. Geometry.prototype.removeVerticesData = function (kind) {
  42521. if (this._vertexBuffers[kind]) {
  42522. this._vertexBuffers[kind].dispose();
  42523. delete this._vertexBuffers[kind];
  42524. }
  42525. };
  42526. Geometry.prototype.setVerticesBuffer = function (buffer) {
  42527. var kind = buffer.getKind();
  42528. if (this._vertexBuffers[kind]) {
  42529. this._vertexBuffers[kind].dispose();
  42530. }
  42531. this._vertexBuffers[kind] = buffer;
  42532. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42533. var data = buffer.getData();
  42534. var stride = buffer.getStrideSize();
  42535. this._totalVertices = data.length / stride;
  42536. this.updateExtend(data, stride);
  42537. var meshes = this._meshes;
  42538. var numOfMeshes = meshes.length;
  42539. for (var index = 0; index < numOfMeshes; index++) {
  42540. var mesh = meshes[index];
  42541. mesh._resetPointsArrayCache();
  42542. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42543. mesh._createGlobalSubMesh();
  42544. mesh.computeWorldMatrix(true);
  42545. }
  42546. }
  42547. this.notifyUpdate(kind);
  42548. if (this._vertexArrayObjects) {
  42549. this._disposeVertexArrayObjects();
  42550. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  42551. }
  42552. };
  42553. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  42554. var vertexBuffer = this.getVertexBuffer(kind);
  42555. if (!vertexBuffer) {
  42556. return;
  42557. }
  42558. vertexBuffer.updateDirectly(data, offset);
  42559. this.notifyUpdate(kind);
  42560. };
  42561. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  42562. var vertexBuffer = this.getVertexBuffer(kind);
  42563. if (!vertexBuffer) {
  42564. return;
  42565. }
  42566. vertexBuffer.update(data);
  42567. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42568. var stride = vertexBuffer.getStrideSize();
  42569. this._totalVertices = data.length / stride;
  42570. this.updateBoundingInfo(updateExtends, data);
  42571. }
  42572. this.notifyUpdate(kind);
  42573. };
  42574. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  42575. if (updateExtends) {
  42576. this.updateExtend(data);
  42577. }
  42578. var meshes = this._meshes;
  42579. var numOfMeshes = meshes.length;
  42580. for (var index = 0; index < numOfMeshes; index++) {
  42581. var mesh = meshes[index];
  42582. mesh._resetPointsArrayCache();
  42583. if (updateExtends) {
  42584. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42585. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42586. var subMesh = mesh.subMeshes[subIndex];
  42587. subMesh.refreshBoundingInfo();
  42588. }
  42589. }
  42590. }
  42591. };
  42592. Geometry.prototype._bind = function (effect, indexToBind) {
  42593. if (indexToBind === void 0) { indexToBind = undefined; }
  42594. if (indexToBind === undefined) {
  42595. indexToBind = this._indexBuffer;
  42596. }
  42597. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  42598. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  42599. return;
  42600. }
  42601. // Using VAO
  42602. if (!this._vertexArrayObjects[effect.key]) {
  42603. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  42604. }
  42605. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  42606. };
  42607. Geometry.prototype.getTotalVertices = function () {
  42608. if (!this.isReady()) {
  42609. return 0;
  42610. }
  42611. return this._totalVertices;
  42612. };
  42613. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  42614. var vertexBuffer = this.getVertexBuffer(kind);
  42615. if (!vertexBuffer) {
  42616. return null;
  42617. }
  42618. var orig = vertexBuffer.getData();
  42619. if (!copyWhenShared || this._meshes.length === 1) {
  42620. return orig;
  42621. }
  42622. else {
  42623. var len = orig.length;
  42624. var copy = [];
  42625. for (var i = 0; i < len; i++) {
  42626. copy.push(orig[i]);
  42627. }
  42628. return copy;
  42629. }
  42630. };
  42631. Geometry.prototype.getVertexBuffer = function (kind) {
  42632. if (!this.isReady()) {
  42633. return null;
  42634. }
  42635. return this._vertexBuffers[kind];
  42636. };
  42637. Geometry.prototype.getVertexBuffers = function () {
  42638. if (!this.isReady()) {
  42639. return null;
  42640. }
  42641. return this._vertexBuffers;
  42642. };
  42643. Geometry.prototype.isVerticesDataPresent = function (kind) {
  42644. if (!this._vertexBuffers) {
  42645. if (this._delayInfo) {
  42646. return this._delayInfo.indexOf(kind) !== -1;
  42647. }
  42648. return false;
  42649. }
  42650. return this._vertexBuffers[kind] !== undefined;
  42651. };
  42652. Geometry.prototype.getVerticesDataKinds = function () {
  42653. var result = [];
  42654. var kind;
  42655. if (!this._vertexBuffers && this._delayInfo) {
  42656. for (kind in this._delayInfo) {
  42657. result.push(kind);
  42658. }
  42659. }
  42660. else {
  42661. for (kind in this._vertexBuffers) {
  42662. result.push(kind);
  42663. }
  42664. }
  42665. return result;
  42666. };
  42667. Geometry.prototype.setIndices = function (indices, totalVertices) {
  42668. if (this._indexBuffer) {
  42669. this._engine._releaseBuffer(this._indexBuffer);
  42670. }
  42671. this._disposeVertexArrayObjects();
  42672. this._indices = indices;
  42673. if (this._meshes.length !== 0 && this._indices) {
  42674. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  42675. }
  42676. if (totalVertices !== undefined) {
  42677. this._totalVertices = totalVertices;
  42678. }
  42679. var meshes = this._meshes;
  42680. var numOfMeshes = meshes.length;
  42681. for (var index = 0; index < numOfMeshes; index++) {
  42682. meshes[index]._createGlobalSubMesh();
  42683. }
  42684. this.notifyUpdate();
  42685. };
  42686. Geometry.prototype.getTotalIndices = function () {
  42687. if (!this.isReady()) {
  42688. return 0;
  42689. }
  42690. return this._indices.length;
  42691. };
  42692. Geometry.prototype.getIndices = function (copyWhenShared) {
  42693. if (!this.isReady()) {
  42694. return null;
  42695. }
  42696. var orig = this._indices;
  42697. if (!copyWhenShared || this._meshes.length === 1) {
  42698. return orig;
  42699. }
  42700. else {
  42701. var len = orig.length;
  42702. var copy = [];
  42703. for (var i = 0; i < len; i++) {
  42704. copy.push(orig[i]);
  42705. }
  42706. return copy;
  42707. }
  42708. };
  42709. Geometry.prototype.getIndexBuffer = function () {
  42710. if (!this.isReady()) {
  42711. return null;
  42712. }
  42713. return this._indexBuffer;
  42714. };
  42715. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  42716. if (!effect) {
  42717. return;
  42718. }
  42719. if (this._vertexArrayObjects[effect.key]) {
  42720. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  42721. delete this._vertexArrayObjects[effect.key];
  42722. }
  42723. };
  42724. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  42725. var meshes = this._meshes;
  42726. var index = meshes.indexOf(mesh);
  42727. if (index === -1) {
  42728. return;
  42729. }
  42730. meshes.splice(index, 1);
  42731. mesh._geometry = null;
  42732. if (meshes.length === 0 && shouldDispose) {
  42733. this.dispose();
  42734. }
  42735. };
  42736. Geometry.prototype.applyToMesh = function (mesh) {
  42737. if (mesh._geometry === this) {
  42738. return;
  42739. }
  42740. var previousGeometry = mesh._geometry;
  42741. if (previousGeometry) {
  42742. previousGeometry.releaseForMesh(mesh);
  42743. }
  42744. var meshes = this._meshes;
  42745. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  42746. mesh._geometry = this;
  42747. this._scene.pushGeometry(this);
  42748. meshes.push(mesh);
  42749. if (this.isReady()) {
  42750. this._applyToMesh(mesh);
  42751. }
  42752. else {
  42753. mesh._boundingInfo = this._boundingInfo;
  42754. }
  42755. };
  42756. Geometry.prototype.updateExtend = function (data, stride) {
  42757. if (data === void 0) { data = null; }
  42758. if (!data) {
  42759. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  42760. }
  42761. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  42762. };
  42763. Geometry.prototype._applyToMesh = function (mesh) {
  42764. var numOfMeshes = this._meshes.length;
  42765. // vertexBuffers
  42766. for (var kind in this._vertexBuffers) {
  42767. if (numOfMeshes === 1) {
  42768. this._vertexBuffers[kind].create();
  42769. }
  42770. var buffer = this._vertexBuffers[kind].getBuffer();
  42771. if (buffer)
  42772. buffer.references = numOfMeshes;
  42773. if (kind === BABYLON.VertexBuffer.PositionKind) {
  42774. mesh._resetPointsArrayCache();
  42775. if (!this._extend) {
  42776. this.updateExtend(this._vertexBuffers[kind].getData());
  42777. }
  42778. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42779. mesh._createGlobalSubMesh();
  42780. //bounding info was just created again, world matrix should be applied again.
  42781. mesh._updateBoundingInfo();
  42782. }
  42783. }
  42784. // indexBuffer
  42785. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  42786. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  42787. }
  42788. if (this._indexBuffer) {
  42789. this._indexBuffer.references = numOfMeshes;
  42790. }
  42791. };
  42792. Geometry.prototype.notifyUpdate = function (kind) {
  42793. if (this.onGeometryUpdated) {
  42794. this.onGeometryUpdated(this, kind);
  42795. }
  42796. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  42797. var mesh = _a[_i];
  42798. mesh._markSubMeshesAsAttributesDirty();
  42799. }
  42800. };
  42801. Geometry.prototype.load = function (scene, onLoaded) {
  42802. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  42803. return;
  42804. }
  42805. if (this.isReady()) {
  42806. if (onLoaded) {
  42807. onLoaded();
  42808. }
  42809. return;
  42810. }
  42811. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  42812. this._queueLoad(scene, onLoaded);
  42813. };
  42814. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  42815. var _this = this;
  42816. scene._addPendingData(this);
  42817. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  42818. _this._delayLoadingFunction(JSON.parse(data), _this);
  42819. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42820. _this._delayInfo = [];
  42821. scene._removePendingData(_this);
  42822. var meshes = _this._meshes;
  42823. var numOfMeshes = meshes.length;
  42824. for (var index = 0; index < numOfMeshes; index++) {
  42825. _this._applyToMesh(meshes[index]);
  42826. }
  42827. if (onLoaded) {
  42828. onLoaded();
  42829. }
  42830. }, function () { }, scene.database);
  42831. };
  42832. /**
  42833. * Invert the geometry to move from a right handed system to a left handed one.
  42834. */
  42835. Geometry.prototype.toLeftHanded = function () {
  42836. // Flip faces
  42837. var tIndices = this.getIndices(false);
  42838. if (tIndices != null && tIndices.length > 0) {
  42839. for (var i = 0; i < tIndices.length; i += 3) {
  42840. var tTemp = tIndices[i + 0];
  42841. tIndices[i + 0] = tIndices[i + 2];
  42842. tIndices[i + 2] = tTemp;
  42843. }
  42844. this.setIndices(tIndices);
  42845. }
  42846. // Negate position.z
  42847. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  42848. if (tPositions != null && tPositions.length > 0) {
  42849. for (var i = 0; i < tPositions.length; i += 3) {
  42850. tPositions[i + 2] = -tPositions[i + 2];
  42851. }
  42852. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  42853. }
  42854. // Negate normal.z
  42855. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  42856. if (tNormals != null && tNormals.length > 0) {
  42857. for (var i = 0; i < tNormals.length; i += 3) {
  42858. tNormals[i + 2] = -tNormals[i + 2];
  42859. }
  42860. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  42861. }
  42862. };
  42863. Geometry.prototype.isDisposed = function () {
  42864. return this._isDisposed;
  42865. };
  42866. Geometry.prototype._disposeVertexArrayObjects = function () {
  42867. if (this._vertexArrayObjects) {
  42868. for (var kind in this._vertexArrayObjects) {
  42869. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  42870. }
  42871. this._vertexArrayObjects = {};
  42872. }
  42873. };
  42874. Geometry.prototype.dispose = function () {
  42875. var meshes = this._meshes;
  42876. var numOfMeshes = meshes.length;
  42877. var index;
  42878. for (index = 0; index < numOfMeshes; index++) {
  42879. this.releaseForMesh(meshes[index]);
  42880. }
  42881. this._meshes = [];
  42882. this._disposeVertexArrayObjects();
  42883. for (var kind in this._vertexBuffers) {
  42884. this._vertexBuffers[kind].dispose();
  42885. }
  42886. this._vertexBuffers = {};
  42887. this._totalVertices = 0;
  42888. if (this._indexBuffer) {
  42889. this._engine._releaseBuffer(this._indexBuffer);
  42890. }
  42891. this._indexBuffer = null;
  42892. this._indices = [];
  42893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  42894. this.delayLoadingFile = null;
  42895. this._delayLoadingFunction = null;
  42896. this._delayInfo = [];
  42897. this._boundingInfo = null;
  42898. this._scene.removeGeometry(this);
  42899. this._isDisposed = true;
  42900. };
  42901. Geometry.prototype.copy = function (id) {
  42902. var vertexData = new BABYLON.VertexData();
  42903. vertexData.indices = [];
  42904. var indices = this.getIndices();
  42905. for (var index = 0; index < indices.length; index++) {
  42906. vertexData.indices.push(indices[index]);
  42907. }
  42908. var updatable = false;
  42909. var stopChecking = false;
  42910. var kind;
  42911. for (kind in this._vertexBuffers) {
  42912. // using slice() to make a copy of the array and not just reference it
  42913. var data = this.getVerticesData(kind);
  42914. if (data instanceof Float32Array) {
  42915. vertexData.set(new Float32Array(data), kind);
  42916. }
  42917. else {
  42918. vertexData.set(data.slice(0), kind);
  42919. }
  42920. if (!stopChecking) {
  42921. updatable = this.getVertexBuffer(kind).isUpdatable();
  42922. stopChecking = !updatable;
  42923. }
  42924. }
  42925. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  42926. geometry.delayLoadState = this.delayLoadState;
  42927. geometry.delayLoadingFile = this.delayLoadingFile;
  42928. geometry._delayLoadingFunction = this._delayLoadingFunction;
  42929. for (kind in this._delayInfo) {
  42930. geometry._delayInfo = geometry._delayInfo || [];
  42931. geometry._delayInfo.push(kind);
  42932. }
  42933. // Bounding info
  42934. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  42935. return geometry;
  42936. };
  42937. Geometry.prototype.serialize = function () {
  42938. var serializationObject = {};
  42939. serializationObject.id = this.id;
  42940. if (BABYLON.Tags.HasTags(this)) {
  42941. serializationObject.tags = BABYLON.Tags.GetTags(this);
  42942. }
  42943. return serializationObject;
  42944. };
  42945. Geometry.prototype.serializeVerticeData = function () {
  42946. var serializationObject = this.serialize();
  42947. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  42948. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42949. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  42950. serializationObject.positions._updatable = true;
  42951. }
  42952. }
  42953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42954. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42955. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  42956. serializationObject.normals._updatable = true;
  42957. }
  42958. }
  42959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42960. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42961. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  42962. serializationObject.uvs._updatable = true;
  42963. }
  42964. }
  42965. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42966. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  42967. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  42968. serializationObject.uv2s._updatable = true;
  42969. }
  42970. }
  42971. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  42972. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  42973. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  42974. serializationObject.uv3s._updatable = true;
  42975. }
  42976. }
  42977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  42978. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  42979. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  42980. serializationObject.uv4s._updatable = true;
  42981. }
  42982. }
  42983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  42984. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  42985. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  42986. serializationObject.uv5s._updatable = true;
  42987. }
  42988. }
  42989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  42990. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  42991. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  42992. serializationObject.uv6s._updatable = true;
  42993. }
  42994. }
  42995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42996. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42997. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  42998. serializationObject.colors._updatable = true;
  42999. }
  43000. }
  43001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  43002. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  43003. serializationObject.matricesIndices._isExpanded = true;
  43004. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  43005. serializationObject.matricesIndices._updatable = true;
  43006. }
  43007. }
  43008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  43009. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  43010. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  43011. serializationObject.matricesWeights._updatable = true;
  43012. }
  43013. }
  43014. serializationObject.indices = this.getIndices();
  43015. return serializationObject;
  43016. };
  43017. // Statics
  43018. Geometry.ExtractFromMesh = function (mesh, id) {
  43019. var geometry = mesh._geometry;
  43020. if (!geometry) {
  43021. return null;
  43022. }
  43023. return geometry.copy(id);
  43024. };
  43025. /**
  43026. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  43027. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  43028. * Be aware Math.random() could cause collisions, but:
  43029. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  43030. */
  43031. Geometry.RandomId = function () {
  43032. return BABYLON.Tools.RandomId();
  43033. };
  43034. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  43035. var scene = mesh.getScene();
  43036. // Geometry
  43037. var geometryId = parsedGeometry.geometryId;
  43038. if (geometryId) {
  43039. var geometry = scene.getGeometryByID(geometryId);
  43040. if (geometry) {
  43041. geometry.applyToMesh(mesh);
  43042. }
  43043. }
  43044. else if (parsedGeometry instanceof ArrayBuffer) {
  43045. var binaryInfo = mesh._binaryInfo;
  43046. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  43047. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  43048. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  43049. }
  43050. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  43051. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  43052. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  43053. }
  43054. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  43055. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  43056. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  43057. }
  43058. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  43059. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  43060. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  43061. }
  43062. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  43063. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  43064. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  43065. }
  43066. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  43067. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  43068. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  43069. }
  43070. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  43071. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  43072. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  43073. }
  43074. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  43075. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  43076. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  43077. }
  43078. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  43079. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  43080. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  43081. }
  43082. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  43083. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  43084. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  43085. }
  43086. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  43087. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  43088. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  43089. }
  43090. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  43091. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  43092. mesh.setIndices(indicesData);
  43093. }
  43094. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  43095. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  43096. mesh.subMeshes = [];
  43097. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  43098. var materialIndex = subMeshesData[(i * 5) + 0];
  43099. var verticesStart = subMeshesData[(i * 5) + 1];
  43100. var verticesCount = subMeshesData[(i * 5) + 2];
  43101. var indexStart = subMeshesData[(i * 5) + 3];
  43102. var indexCount = subMeshesData[(i * 5) + 4];
  43103. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  43104. }
  43105. }
  43106. }
  43107. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  43108. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  43109. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  43110. if (parsedGeometry.uvs) {
  43111. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  43112. }
  43113. if (parsedGeometry.uvs2) {
  43114. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  43115. }
  43116. if (parsedGeometry.uvs3) {
  43117. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  43118. }
  43119. if (parsedGeometry.uvs4) {
  43120. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  43121. }
  43122. if (parsedGeometry.uvs5) {
  43123. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  43124. }
  43125. if (parsedGeometry.uvs6) {
  43126. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  43127. }
  43128. if (parsedGeometry.colors) {
  43129. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  43130. }
  43131. if (parsedGeometry.matricesIndices) {
  43132. if (!parsedGeometry.matricesIndices._isExpanded) {
  43133. var floatIndices = [];
  43134. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  43135. var matricesIndex = parsedGeometry.matricesIndices[i];
  43136. floatIndices.push(matricesIndex & 0x000000FF);
  43137. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  43138. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  43139. floatIndices.push(matricesIndex >> 24);
  43140. }
  43141. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  43142. }
  43143. else {
  43144. delete parsedGeometry.matricesIndices._isExpanded;
  43145. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  43146. }
  43147. }
  43148. if (parsedGeometry.matricesIndicesExtra) {
  43149. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  43150. var floatIndices = [];
  43151. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  43152. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  43153. floatIndices.push(matricesIndex & 0x000000FF);
  43154. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  43155. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  43156. floatIndices.push(matricesIndex >> 24);
  43157. }
  43158. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  43159. }
  43160. else {
  43161. delete parsedGeometry.matricesIndices._isExpanded;
  43162. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  43163. }
  43164. }
  43165. if (parsedGeometry.matricesWeights) {
  43166. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  43167. }
  43168. if (parsedGeometry.matricesWeightsExtra) {
  43169. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  43170. }
  43171. mesh.setIndices(parsedGeometry.indices);
  43172. }
  43173. // SubMeshes
  43174. if (parsedGeometry.subMeshes) {
  43175. mesh.subMeshes = [];
  43176. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  43177. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  43178. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  43179. }
  43180. }
  43181. // Flat shading
  43182. if (mesh._shouldGenerateFlatShading) {
  43183. mesh.convertToFlatShadedMesh();
  43184. delete mesh._shouldGenerateFlatShading;
  43185. }
  43186. // Update
  43187. mesh.computeWorldMatrix(true);
  43188. // Octree
  43189. if (scene['_selectionOctree']) {
  43190. scene['_selectionOctree'].addMesh(mesh);
  43191. }
  43192. };
  43193. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  43194. if (scene.getGeometryByID(parsedVertexData.id)) {
  43195. return null; // null since geometry could be something else than a box...
  43196. }
  43197. var geometry = new Geometry(parsedVertexData.id, scene);
  43198. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  43199. if (parsedVertexData.delayLoadingFile) {
  43200. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43201. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  43202. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  43203. geometry._delayInfo = [];
  43204. if (parsedVertexData.hasUVs) {
  43205. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  43206. }
  43207. if (parsedVertexData.hasUVs2) {
  43208. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  43209. }
  43210. if (parsedVertexData.hasUVs3) {
  43211. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  43212. }
  43213. if (parsedVertexData.hasUVs4) {
  43214. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  43215. }
  43216. if (parsedVertexData.hasUVs5) {
  43217. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  43218. }
  43219. if (parsedVertexData.hasUVs6) {
  43220. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  43221. }
  43222. if (parsedVertexData.hasColors) {
  43223. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  43224. }
  43225. if (parsedVertexData.hasMatricesIndices) {
  43226. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43227. }
  43228. if (parsedVertexData.hasMatricesWeights) {
  43229. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43230. }
  43231. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  43232. }
  43233. else {
  43234. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  43235. }
  43236. scene.pushGeometry(geometry, true);
  43237. return geometry;
  43238. };
  43239. return Geometry;
  43240. }());
  43241. BABYLON.Geometry = Geometry;
  43242. /////// Primitives //////////////////////////////////////////////
  43243. (function (Geometry) {
  43244. var Primitives;
  43245. (function (Primitives) {
  43246. /// Abstract class
  43247. var _Primitive = (function (_super) {
  43248. __extends(_Primitive, _super);
  43249. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  43250. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  43251. _this._canBeRegenerated = _canBeRegenerated;
  43252. _this._beingRegenerated = true;
  43253. _this.regenerate();
  43254. _this._beingRegenerated = false;
  43255. return _this;
  43256. }
  43257. _Primitive.prototype.canBeRegenerated = function () {
  43258. return this._canBeRegenerated;
  43259. };
  43260. _Primitive.prototype.regenerate = function () {
  43261. if (!this._canBeRegenerated) {
  43262. return;
  43263. }
  43264. this._beingRegenerated = true;
  43265. this.setAllVerticesData(this._regenerateVertexData(), false);
  43266. this._beingRegenerated = false;
  43267. };
  43268. _Primitive.prototype.asNewGeometry = function (id) {
  43269. return _super.prototype.copy.call(this, id);
  43270. };
  43271. // overrides
  43272. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  43273. if (!this._beingRegenerated) {
  43274. return;
  43275. }
  43276. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  43277. };
  43278. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  43279. if (!this._beingRegenerated) {
  43280. return;
  43281. }
  43282. _super.prototype.setVerticesData.call(this, kind, data, false);
  43283. };
  43284. // to override
  43285. // protected
  43286. _Primitive.prototype._regenerateVertexData = function () {
  43287. throw new Error("Abstract method");
  43288. };
  43289. _Primitive.prototype.copy = function (id) {
  43290. throw new Error("Must be overriden in sub-classes.");
  43291. };
  43292. _Primitive.prototype.serialize = function () {
  43293. var serializationObject = _super.prototype.serialize.call(this);
  43294. serializationObject.canBeRegenerated = this.canBeRegenerated();
  43295. return serializationObject;
  43296. };
  43297. return _Primitive;
  43298. }(Geometry));
  43299. Primitives._Primitive = _Primitive;
  43300. var Ribbon = (function (_super) {
  43301. __extends(Ribbon, _super);
  43302. // Members
  43303. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  43304. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43305. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43306. _this.pathArray = pathArray;
  43307. _this.closeArray = closeArray;
  43308. _this.closePath = closePath;
  43309. _this.offset = offset;
  43310. _this.side = side;
  43311. return _this;
  43312. }
  43313. Ribbon.prototype._regenerateVertexData = function () {
  43314. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  43315. };
  43316. Ribbon.prototype.copy = function (id) {
  43317. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  43318. };
  43319. return Ribbon;
  43320. }(_Primitive));
  43321. Primitives.Ribbon = Ribbon;
  43322. var Box = (function (_super) {
  43323. __extends(Box, _super);
  43324. // Members
  43325. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  43326. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43327. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43328. _this.size = size;
  43329. _this.side = side;
  43330. return _this;
  43331. }
  43332. Box.prototype._regenerateVertexData = function () {
  43333. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  43334. };
  43335. Box.prototype.copy = function (id) {
  43336. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  43337. };
  43338. Box.prototype.serialize = function () {
  43339. var serializationObject = _super.prototype.serialize.call(this);
  43340. serializationObject.size = this.size;
  43341. return serializationObject;
  43342. };
  43343. Box.Parse = function (parsedBox, scene) {
  43344. if (scene.getGeometryByID(parsedBox.id)) {
  43345. return null; // null since geometry could be something else than a box...
  43346. }
  43347. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  43348. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  43349. scene.pushGeometry(box, true);
  43350. return box;
  43351. };
  43352. return Box;
  43353. }(_Primitive));
  43354. Primitives.Box = Box;
  43355. var Sphere = (function (_super) {
  43356. __extends(Sphere, _super);
  43357. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  43358. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43359. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43360. _this.segments = segments;
  43361. _this.diameter = diameter;
  43362. _this.side = side;
  43363. return _this;
  43364. }
  43365. Sphere.prototype._regenerateVertexData = function () {
  43366. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  43367. };
  43368. Sphere.prototype.copy = function (id) {
  43369. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  43370. };
  43371. Sphere.prototype.serialize = function () {
  43372. var serializationObject = _super.prototype.serialize.call(this);
  43373. serializationObject.segments = this.segments;
  43374. serializationObject.diameter = this.diameter;
  43375. return serializationObject;
  43376. };
  43377. Sphere.Parse = function (parsedSphere, scene) {
  43378. if (scene.getGeometryByID(parsedSphere.id)) {
  43379. return null; // null since geometry could be something else than a sphere...
  43380. }
  43381. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  43382. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  43383. scene.pushGeometry(sphere, true);
  43384. return sphere;
  43385. };
  43386. return Sphere;
  43387. }(_Primitive));
  43388. Primitives.Sphere = Sphere;
  43389. var Disc = (function (_super) {
  43390. __extends(Disc, _super);
  43391. // Members
  43392. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  43393. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43394. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43395. _this.radius = radius;
  43396. _this.tessellation = tessellation;
  43397. _this.side = side;
  43398. return _this;
  43399. }
  43400. Disc.prototype._regenerateVertexData = function () {
  43401. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  43402. };
  43403. Disc.prototype.copy = function (id) {
  43404. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  43405. };
  43406. return Disc;
  43407. }(_Primitive));
  43408. Primitives.Disc = Disc;
  43409. var Cylinder = (function (_super) {
  43410. __extends(Cylinder, _super);
  43411. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  43412. if (subdivisions === void 0) { subdivisions = 1; }
  43413. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43414. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43415. _this.height = height;
  43416. _this.diameterTop = diameterTop;
  43417. _this.diameterBottom = diameterBottom;
  43418. _this.tessellation = tessellation;
  43419. _this.subdivisions = subdivisions;
  43420. _this.side = side;
  43421. return _this;
  43422. }
  43423. Cylinder.prototype._regenerateVertexData = function () {
  43424. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  43425. };
  43426. Cylinder.prototype.copy = function (id) {
  43427. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  43428. };
  43429. Cylinder.prototype.serialize = function () {
  43430. var serializationObject = _super.prototype.serialize.call(this);
  43431. serializationObject.height = this.height;
  43432. serializationObject.diameterTop = this.diameterTop;
  43433. serializationObject.diameterBottom = this.diameterBottom;
  43434. serializationObject.tessellation = this.tessellation;
  43435. return serializationObject;
  43436. };
  43437. Cylinder.Parse = function (parsedCylinder, scene) {
  43438. if (scene.getGeometryByID(parsedCylinder.id)) {
  43439. return null; // null since geometry could be something else than a cylinder...
  43440. }
  43441. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  43442. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  43443. scene.pushGeometry(cylinder, true);
  43444. return cylinder;
  43445. };
  43446. return Cylinder;
  43447. }(_Primitive));
  43448. Primitives.Cylinder = Cylinder;
  43449. var Torus = (function (_super) {
  43450. __extends(Torus, _super);
  43451. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  43452. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43453. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43454. _this.diameter = diameter;
  43455. _this.thickness = thickness;
  43456. _this.tessellation = tessellation;
  43457. _this.side = side;
  43458. return _this;
  43459. }
  43460. Torus.prototype._regenerateVertexData = function () {
  43461. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  43462. };
  43463. Torus.prototype.copy = function (id) {
  43464. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  43465. };
  43466. Torus.prototype.serialize = function () {
  43467. var serializationObject = _super.prototype.serialize.call(this);
  43468. serializationObject.diameter = this.diameter;
  43469. serializationObject.thickness = this.thickness;
  43470. serializationObject.tessellation = this.tessellation;
  43471. return serializationObject;
  43472. };
  43473. Torus.Parse = function (parsedTorus, scene) {
  43474. if (scene.getGeometryByID(parsedTorus.id)) {
  43475. return null; // null since geometry could be something else than a torus...
  43476. }
  43477. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  43478. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  43479. scene.pushGeometry(torus, true);
  43480. return torus;
  43481. };
  43482. return Torus;
  43483. }(_Primitive));
  43484. Primitives.Torus = Torus;
  43485. var Ground = (function (_super) {
  43486. __extends(Ground, _super);
  43487. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  43488. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43489. _this.width = width;
  43490. _this.height = height;
  43491. _this.subdivisions = subdivisions;
  43492. return _this;
  43493. }
  43494. Ground.prototype._regenerateVertexData = function () {
  43495. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  43496. };
  43497. Ground.prototype.copy = function (id) {
  43498. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  43499. };
  43500. Ground.prototype.serialize = function () {
  43501. var serializationObject = _super.prototype.serialize.call(this);
  43502. serializationObject.width = this.width;
  43503. serializationObject.height = this.height;
  43504. serializationObject.subdivisions = this.subdivisions;
  43505. return serializationObject;
  43506. };
  43507. Ground.Parse = function (parsedGround, scene) {
  43508. if (scene.getGeometryByID(parsedGround.id)) {
  43509. return null; // null since geometry could be something else than a ground...
  43510. }
  43511. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  43512. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  43513. scene.pushGeometry(ground, true);
  43514. return ground;
  43515. };
  43516. return Ground;
  43517. }(_Primitive));
  43518. Primitives.Ground = Ground;
  43519. var TiledGround = (function (_super) {
  43520. __extends(TiledGround, _super);
  43521. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  43522. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43523. _this.xmin = xmin;
  43524. _this.zmin = zmin;
  43525. _this.xmax = xmax;
  43526. _this.zmax = zmax;
  43527. _this.subdivisions = subdivisions;
  43528. _this.precision = precision;
  43529. return _this;
  43530. }
  43531. TiledGround.prototype._regenerateVertexData = function () {
  43532. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  43533. };
  43534. TiledGround.prototype.copy = function (id) {
  43535. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  43536. };
  43537. return TiledGround;
  43538. }(_Primitive));
  43539. Primitives.TiledGround = TiledGround;
  43540. var Plane = (function (_super) {
  43541. __extends(Plane, _super);
  43542. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  43543. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43544. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43545. _this.size = size;
  43546. _this.side = side;
  43547. return _this;
  43548. }
  43549. Plane.prototype._regenerateVertexData = function () {
  43550. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  43551. };
  43552. Plane.prototype.copy = function (id) {
  43553. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  43554. };
  43555. Plane.prototype.serialize = function () {
  43556. var serializationObject = _super.prototype.serialize.call(this);
  43557. serializationObject.size = this.size;
  43558. return serializationObject;
  43559. };
  43560. Plane.Parse = function (parsedPlane, scene) {
  43561. if (scene.getGeometryByID(parsedPlane.id)) {
  43562. return null; // null since geometry could be something else than a ground...
  43563. }
  43564. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  43565. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  43566. scene.pushGeometry(plane, true);
  43567. return plane;
  43568. };
  43569. return Plane;
  43570. }(_Primitive));
  43571. Primitives.Plane = Plane;
  43572. var TorusKnot = (function (_super) {
  43573. __extends(TorusKnot, _super);
  43574. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  43575. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  43576. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  43577. _this.radius = radius;
  43578. _this.tube = tube;
  43579. _this.radialSegments = radialSegments;
  43580. _this.tubularSegments = tubularSegments;
  43581. _this.p = p;
  43582. _this.q = q;
  43583. _this.side = side;
  43584. return _this;
  43585. }
  43586. TorusKnot.prototype._regenerateVertexData = function () {
  43587. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  43588. };
  43589. TorusKnot.prototype.copy = function (id) {
  43590. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  43591. };
  43592. TorusKnot.prototype.serialize = function () {
  43593. var serializationObject = _super.prototype.serialize.call(this);
  43594. serializationObject.radius = this.radius;
  43595. serializationObject.tube = this.tube;
  43596. serializationObject.radialSegments = this.radialSegments;
  43597. serializationObject.tubularSegments = this.tubularSegments;
  43598. serializationObject.p = this.p;
  43599. serializationObject.q = this.q;
  43600. return serializationObject;
  43601. };
  43602. ;
  43603. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  43604. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  43605. return null; // null since geometry could be something else than a ground...
  43606. }
  43607. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  43608. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  43609. scene.pushGeometry(torusKnot, true);
  43610. return torusKnot;
  43611. };
  43612. return TorusKnot;
  43613. }(_Primitive));
  43614. Primitives.TorusKnot = TorusKnot;
  43615. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  43616. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  43617. })(BABYLON || (BABYLON = {}));
  43618. //# sourceMappingURL=babylon.geometry.js.map
  43619. /// <reference path="babylon.mesh.ts" />
  43620. var BABYLON;
  43621. (function (BABYLON) {
  43622. var GroundMesh = (function (_super) {
  43623. __extends(GroundMesh, _super);
  43624. function GroundMesh(name, scene) {
  43625. var _this = _super.call(this, name, scene) || this;
  43626. _this.generateOctree = false;
  43627. _this._worldInverse = new BABYLON.Matrix();
  43628. return _this;
  43629. }
  43630. GroundMesh.prototype.getClassName = function () {
  43631. return "GroundMesh";
  43632. };
  43633. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  43634. get: function () {
  43635. return Math.min(this._subdivisionsX, this._subdivisionsY);
  43636. },
  43637. enumerable: true,
  43638. configurable: true
  43639. });
  43640. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  43641. get: function () {
  43642. return this._subdivisionsX;
  43643. },
  43644. enumerable: true,
  43645. configurable: true
  43646. });
  43647. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  43648. get: function () {
  43649. return this._subdivisionsY;
  43650. },
  43651. enumerable: true,
  43652. configurable: true
  43653. });
  43654. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  43655. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  43656. this._subdivisionsX = chunksCount;
  43657. this._subdivisionsY = chunksCount;
  43658. this.subdivide(chunksCount);
  43659. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  43660. };
  43661. /**
  43662. * Returns a height (y) value in the Worl system :
  43663. * the ground altitude at the coordinates (x, z) expressed in the World system.
  43664. * Returns the ground y position if (x, z) are outside the ground surface.
  43665. */
  43666. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  43667. var world = this.getWorldMatrix();
  43668. var invMat = BABYLON.Tmp.Matrix[5];
  43669. world.invertToRef(invMat);
  43670. var tmpVect = BABYLON.Tmp.Vector3[8];
  43671. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  43672. x = tmpVect.x;
  43673. z = tmpVect.z;
  43674. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43675. return this.position.y;
  43676. }
  43677. if (!this._heightQuads || this._heightQuads.length == 0) {
  43678. this._initHeightQuads();
  43679. this._computeHeightQuads();
  43680. }
  43681. var facet = this._getFacetAt(x, z);
  43682. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  43683. // return y in the World system
  43684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  43685. return tmpVect.y;
  43686. };
  43687. /**
  43688. * Returns a normalized vector (Vector3) orthogonal to the ground
  43689. * at the ground coordinates (x, z) expressed in the World system.
  43690. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  43691. */
  43692. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  43693. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  43694. this.getNormalAtCoordinatesToRef(x, z, normal);
  43695. return normal;
  43696. };
  43697. /**
  43698. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  43699. * at the ground coordinates (x, z) expressed in the World system.
  43700. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  43701. * Returns the GroundMesh.
  43702. */
  43703. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  43704. var world = this.getWorldMatrix();
  43705. var tmpMat = BABYLON.Tmp.Matrix[5];
  43706. world.invertToRef(tmpMat);
  43707. var tmpVect = BABYLON.Tmp.Vector3[8];
  43708. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  43709. x = tmpVect.x;
  43710. z = tmpVect.z;
  43711. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  43712. return this;
  43713. }
  43714. if (!this._heightQuads || this._heightQuads.length == 0) {
  43715. this._initHeightQuads();
  43716. this._computeHeightQuads();
  43717. }
  43718. var facet = this._getFacetAt(x, z);
  43719. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  43720. return this;
  43721. };
  43722. /**
  43723. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  43724. * if the ground has been updated.
  43725. * This can be used in the render loop.
  43726. * Returns the GroundMesh.
  43727. */
  43728. GroundMesh.prototype.updateCoordinateHeights = function () {
  43729. if (!this._heightQuads || this._heightQuads.length == 0) {
  43730. this._initHeightQuads();
  43731. }
  43732. this._computeHeightQuads();
  43733. return this;
  43734. };
  43735. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  43736. GroundMesh.prototype._getFacetAt = function (x, z) {
  43737. // retrieve col and row from x, z coordinates in the ground local system
  43738. var subdivisionsX = this._subdivisionsX;
  43739. var subdivisionsY = this._subdivisionsY;
  43740. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  43741. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  43742. var quad = this._heightQuads[row * this._subdivisionsX + col];
  43743. var facet;
  43744. if (z < quad.slope.x * x + quad.slope.y) {
  43745. facet = quad.facet1;
  43746. }
  43747. else {
  43748. facet = quad.facet2;
  43749. }
  43750. return facet;
  43751. };
  43752. // Creates and populates the heightMap array with "facet" elements :
  43753. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  43754. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43755. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43756. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43757. // Returns the GroundMesh.
  43758. GroundMesh.prototype._initHeightQuads = function () {
  43759. var subdivisionsX = this._subdivisionsX;
  43760. var subdivisionsY = this._subdivisionsY;
  43761. this._heightQuads = new Array();
  43762. for (var row = 0; row < subdivisionsY; row++) {
  43763. for (var col = 0; col < subdivisionsX; col++) {
  43764. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  43765. this._heightQuads[row * subdivisionsX + col] = quad;
  43766. }
  43767. }
  43768. return this;
  43769. };
  43770. // Compute each quad element values and update the the heightMap array :
  43771. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  43772. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  43773. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  43774. // Returns the GroundMesh.
  43775. GroundMesh.prototype._computeHeightQuads = function () {
  43776. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43777. var v1 = BABYLON.Tmp.Vector3[3];
  43778. var v2 = BABYLON.Tmp.Vector3[2];
  43779. var v3 = BABYLON.Tmp.Vector3[1];
  43780. var v4 = BABYLON.Tmp.Vector3[0];
  43781. var v1v2 = BABYLON.Tmp.Vector3[4];
  43782. var v1v3 = BABYLON.Tmp.Vector3[5];
  43783. var v1v4 = BABYLON.Tmp.Vector3[6];
  43784. var norm1 = BABYLON.Tmp.Vector3[7];
  43785. var norm2 = BABYLON.Tmp.Vector3[8];
  43786. var i = 0;
  43787. var j = 0;
  43788. var k = 0;
  43789. var cd = 0; // 2D slope coefficient : z = cd * x + h
  43790. var h = 0;
  43791. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  43792. var d2 = 0;
  43793. var subdivisionsX = this._subdivisionsX;
  43794. var subdivisionsY = this._subdivisionsY;
  43795. for (var row = 0; row < subdivisionsY; row++) {
  43796. for (var col = 0; col < subdivisionsX; col++) {
  43797. i = col * 3;
  43798. j = row * (subdivisionsX + 1) * 3;
  43799. k = (row + 1) * (subdivisionsX + 1) * 3;
  43800. v1.x = positions[j + i];
  43801. v1.y = positions[j + i + 1];
  43802. v1.z = positions[j + i + 2];
  43803. v2.x = positions[j + i + 3];
  43804. v2.y = positions[j + i + 4];
  43805. v2.z = positions[j + i + 5];
  43806. v3.x = positions[k + i];
  43807. v3.y = positions[k + i + 1];
  43808. v3.z = positions[k + i + 2];
  43809. v4.x = positions[k + i + 3];
  43810. v4.y = positions[k + i + 4];
  43811. v4.z = positions[k + i + 5];
  43812. // 2D slope V1V4
  43813. cd = (v4.z - v1.z) / (v4.x - v1.x);
  43814. h = v1.z - cd * v1.x; // v1 belongs to the slope
  43815. // facet equations :
  43816. // we compute each facet normal vector
  43817. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  43818. // we compute the value d by applying the equation to v1 which belongs to the plane
  43819. // then we store the facet equation in a Vector4
  43820. v2.subtractToRef(v1, v1v2);
  43821. v3.subtractToRef(v1, v1v3);
  43822. v4.subtractToRef(v1, v1v4);
  43823. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  43824. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  43825. norm1.normalize();
  43826. norm2.normalize();
  43827. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  43828. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  43829. var quad = this._heightQuads[row * subdivisionsX + col];
  43830. quad.slope.copyFromFloats(cd, h);
  43831. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  43832. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  43833. }
  43834. }
  43835. return this;
  43836. };
  43837. GroundMesh.prototype.serialize = function (serializationObject) {
  43838. _super.prototype.serialize.call(this, serializationObject);
  43839. serializationObject.subdivisionsX = this._subdivisionsX;
  43840. serializationObject.subdivisionsY = this._subdivisionsY;
  43841. serializationObject.minX = this._minX;
  43842. serializationObject.maxX = this._maxX;
  43843. serializationObject.minZ = this._minZ;
  43844. serializationObject.maxZ = this._maxZ;
  43845. serializationObject.width = this._width;
  43846. serializationObject.height = this._height;
  43847. };
  43848. GroundMesh.Parse = function (parsedMesh, scene) {
  43849. var result = new GroundMesh(parsedMesh.name, scene);
  43850. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  43851. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  43852. result._minX = parsedMesh.minX;
  43853. result._maxX = parsedMesh.maxX;
  43854. result._minZ = parsedMesh.minZ;
  43855. result._maxZ = parsedMesh.maxZ;
  43856. result._width = parsedMesh.width;
  43857. result._height = parsedMesh.height;
  43858. return result;
  43859. };
  43860. return GroundMesh;
  43861. }(BABYLON.Mesh));
  43862. BABYLON.GroundMesh = GroundMesh;
  43863. })(BABYLON || (BABYLON = {}));
  43864. //# sourceMappingURL=babylon.groundMesh.js.map
  43865. /// <reference path="babylon.mesh.ts" />
  43866. var BABYLON;
  43867. (function (BABYLON) {
  43868. var LinesMesh = (function (_super) {
  43869. __extends(LinesMesh, _super);
  43870. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  43871. if (parent === void 0) { parent = null; }
  43872. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  43873. _this.color = new BABYLON.Color3(1, 1, 1);
  43874. _this.alpha = 1;
  43875. _this._positionBuffer = {};
  43876. if (source) {
  43877. _this.color = source.color.clone();
  43878. _this.alpha = source.alpha;
  43879. }
  43880. _this._intersectionThreshold = 0.1;
  43881. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  43882. attributes: [BABYLON.VertexBuffer.PositionKind],
  43883. uniforms: ["worldViewProjection", "color"],
  43884. needAlphaBlending: true
  43885. });
  43886. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  43887. return _this;
  43888. }
  43889. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  43890. /**
  43891. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43892. * This margin is expressed in world space coordinates, so its value may vary.
  43893. * Default value is 0.1
  43894. * @returns the intersection Threshold value.
  43895. */
  43896. get: function () {
  43897. return this._intersectionThreshold;
  43898. },
  43899. /**
  43900. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  43901. * This margin is expressed in world space coordinates, so its value may vary.
  43902. * @param value the new threshold to apply
  43903. */
  43904. set: function (value) {
  43905. if (this._intersectionThreshold === value) {
  43906. return;
  43907. }
  43908. this._intersectionThreshold = value;
  43909. if (this.geometry) {
  43910. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  43911. }
  43912. },
  43913. enumerable: true,
  43914. configurable: true
  43915. });
  43916. /**
  43917. * Returns the string "LineMesh"
  43918. */
  43919. LinesMesh.prototype.getClassName = function () {
  43920. return "LinesMesh";
  43921. };
  43922. Object.defineProperty(LinesMesh.prototype, "material", {
  43923. get: function () {
  43924. return this._colorShader;
  43925. },
  43926. enumerable: true,
  43927. configurable: true
  43928. });
  43929. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  43930. get: function () {
  43931. return false;
  43932. },
  43933. enumerable: true,
  43934. configurable: true
  43935. });
  43936. LinesMesh.prototype.createInstance = function (name) {
  43937. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  43938. return null;
  43939. };
  43940. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  43941. var engine = this.getScene().getEngine();
  43942. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  43943. // VBOs
  43944. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  43945. // Color
  43946. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  43947. return this;
  43948. };
  43949. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  43950. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  43951. return this;
  43952. }
  43953. var engine = this.getScene().getEngine();
  43954. // Draw order
  43955. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  43956. return this;
  43957. };
  43958. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43959. this._colorShader.dispose();
  43960. _super.prototype.dispose.call(this, doNotRecurse);
  43961. };
  43962. /**
  43963. * Returns a new LineMesh object cloned from the current one.
  43964. */
  43965. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43966. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43967. };
  43968. return LinesMesh;
  43969. }(BABYLON.Mesh));
  43970. BABYLON.LinesMesh = LinesMesh;
  43971. })(BABYLON || (BABYLON = {}));
  43972. //# sourceMappingURL=babylon.linesMesh.js.map
  43973. var BABYLON;
  43974. (function (BABYLON) {
  43975. var AudioEngine = (function () {
  43976. function AudioEngine() {
  43977. this._audioContext = null;
  43978. this._audioContextInitialized = false;
  43979. this.canUseWebAudio = false;
  43980. this.WarnedWebAudioUnsupported = false;
  43981. this.unlocked = false;
  43982. this.isMP3supported = false;
  43983. this.isOGGsupported = false;
  43984. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  43985. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  43986. this.canUseWebAudio = true;
  43987. }
  43988. var audioElem = document.createElement('audio');
  43989. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  43990. this.isMP3supported = true;
  43991. }
  43992. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  43993. this.isOGGsupported = true;
  43994. }
  43995. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  43996. this._unlockiOSaudio();
  43997. }
  43998. else {
  43999. this.unlocked = true;
  44000. }
  44001. }
  44002. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44003. get: function () {
  44004. if (!this._audioContextInitialized) {
  44005. this._initializeAudioContext();
  44006. }
  44007. return this._audioContext;
  44008. },
  44009. enumerable: true,
  44010. configurable: true
  44011. });
  44012. AudioEngine.prototype._unlockiOSaudio = function () {
  44013. var _this = this;
  44014. var unlockaudio = function () {
  44015. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44016. var source = _this.audioContext.createBufferSource();
  44017. source.buffer = buffer;
  44018. source.connect(_this.audioContext.destination);
  44019. source.start(0);
  44020. setTimeout(function () {
  44021. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44022. _this.unlocked = true;
  44023. window.removeEventListener('touchend', unlockaudio, false);
  44024. if (_this.onAudioUnlocked) {
  44025. _this.onAudioUnlocked();
  44026. }
  44027. }
  44028. }, 0);
  44029. };
  44030. window.addEventListener('touchend', unlockaudio, false);
  44031. };
  44032. AudioEngine.prototype._initializeAudioContext = function () {
  44033. try {
  44034. if (this.canUseWebAudio) {
  44035. this._audioContext = new AudioContext();
  44036. // create a global volume gain node
  44037. this.masterGain = this._audioContext.createGain();
  44038. this.masterGain.gain.value = 1;
  44039. this.masterGain.connect(this._audioContext.destination);
  44040. this._audioContextInitialized = true;
  44041. }
  44042. }
  44043. catch (e) {
  44044. this.canUseWebAudio = false;
  44045. BABYLON.Tools.Error("Web Audio: " + e.message);
  44046. }
  44047. };
  44048. AudioEngine.prototype.dispose = function () {
  44049. if (this.canUseWebAudio && this._audioContextInitialized) {
  44050. if (this._connectedAnalyser) {
  44051. this._connectedAnalyser.stopDebugCanvas();
  44052. this._connectedAnalyser.dispose();
  44053. this.masterGain.disconnect();
  44054. this.masterGain.connect(this._audioContext.destination);
  44055. this._connectedAnalyser = null;
  44056. }
  44057. this.masterGain.gain.value = 1;
  44058. }
  44059. this.WarnedWebAudioUnsupported = false;
  44060. };
  44061. AudioEngine.prototype.getGlobalVolume = function () {
  44062. if (this.canUseWebAudio && this._audioContextInitialized) {
  44063. return this.masterGain.gain.value;
  44064. }
  44065. else {
  44066. return -1;
  44067. }
  44068. };
  44069. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44070. if (this.canUseWebAudio && this._audioContextInitialized) {
  44071. this.masterGain.gain.value = newVolume;
  44072. }
  44073. };
  44074. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44075. if (this._connectedAnalyser) {
  44076. this._connectedAnalyser.stopDebugCanvas();
  44077. }
  44078. if (this.canUseWebAudio && this._audioContextInitialized) {
  44079. this._connectedAnalyser = analyser;
  44080. this.masterGain.disconnect();
  44081. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44082. }
  44083. };
  44084. return AudioEngine;
  44085. }());
  44086. BABYLON.AudioEngine = AudioEngine;
  44087. })(BABYLON || (BABYLON = {}));
  44088. //# sourceMappingURL=babylon.audioEngine.js.map
  44089. var BABYLON;
  44090. (function (BABYLON) {
  44091. var Sound = (function () {
  44092. /**
  44093. * Create a sound and attach it to a scene
  44094. * @param name Name of your sound
  44095. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44096. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44097. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44098. */
  44099. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44100. var _this = this;
  44101. this.autoplay = false;
  44102. this.loop = false;
  44103. this.useCustomAttenuation = false;
  44104. this.spatialSound = false;
  44105. this.refDistance = 1;
  44106. this.rolloffFactor = 1;
  44107. this.maxDistance = 100;
  44108. this.distanceModel = "linear";
  44109. this._panningModel = "equalpower";
  44110. this._playbackRate = 1;
  44111. this._streaming = false;
  44112. this._startTime = 0;
  44113. this._startOffset = 0;
  44114. this._position = BABYLON.Vector3.Zero();
  44115. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44116. this._volume = 1;
  44117. this._isLoaded = false;
  44118. this._isReadyToPlay = false;
  44119. this.isPlaying = false;
  44120. this.isPaused = false;
  44121. this._isDirectional = false;
  44122. // Used if you'd like to create a directional sound.
  44123. // If not set, the sound will be omnidirectional
  44124. this._coneInnerAngle = 360;
  44125. this._coneOuterAngle = 360;
  44126. this._coneOuterGain = 0;
  44127. this._isOutputConnected = false;
  44128. this._urlType = "Unknown";
  44129. this.name = name;
  44130. this._scene = scene;
  44131. this._readyToPlayCallback = readyToPlayCallback;
  44132. // Default custom attenuation function is a linear attenuation
  44133. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44134. if (currentDistance < maxDistance) {
  44135. return currentVolume * (1 - currentDistance / maxDistance);
  44136. }
  44137. else {
  44138. return 0;
  44139. }
  44140. };
  44141. if (options) {
  44142. this.autoplay = options.autoplay || false;
  44143. this.loop = options.loop || false;
  44144. // if volume === 0, we need another way to check this option
  44145. if (options.volume !== undefined) {
  44146. this._volume = options.volume;
  44147. }
  44148. this.spatialSound = options.spatialSound || false;
  44149. this.maxDistance = options.maxDistance || 100;
  44150. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44151. this.rolloffFactor = options.rolloffFactor || 1;
  44152. this.refDistance = options.refDistance || 1;
  44153. this.distanceModel = options.distanceModel || "linear";
  44154. this._playbackRate = options.playbackRate || 1;
  44155. this._streaming = options.streaming || false;
  44156. }
  44157. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44158. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44159. this._soundGain.gain.value = this._volume;
  44160. this._inputAudioNode = this._soundGain;
  44161. this._ouputAudioNode = this._soundGain;
  44162. if (this.spatialSound) {
  44163. this._createSpatialParameters();
  44164. }
  44165. this._scene.mainSoundTrack.AddSound(this);
  44166. var validParameter = true;
  44167. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44168. if (urlOrArrayBuffer) {
  44169. if (typeof (urlOrArrayBuffer) === "string")
  44170. this._urlType = "String";
  44171. if (Array.isArray(urlOrArrayBuffer))
  44172. this._urlType = "Array";
  44173. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44174. this._urlType = "ArrayBuffer";
  44175. var urls = [];
  44176. var codecSupportedFound = false;
  44177. switch (this._urlType) {
  44178. case "ArrayBuffer":
  44179. if (urlOrArrayBuffer.byteLength > 0) {
  44180. codecSupportedFound = true;
  44181. this._soundLoaded(urlOrArrayBuffer);
  44182. }
  44183. break;
  44184. case "String":
  44185. urls.push(urlOrArrayBuffer);
  44186. case "Array":
  44187. if (urls.length === 0)
  44188. urls = urlOrArrayBuffer;
  44189. // If we found a supported format, we load it immediately and stop the loop
  44190. for (var i = 0; i < urls.length; i++) {
  44191. var url = urls[i];
  44192. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44193. codecSupportedFound = true;
  44194. }
  44195. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44196. codecSupportedFound = true;
  44197. }
  44198. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44199. codecSupportedFound = true;
  44200. }
  44201. if (codecSupportedFound) {
  44202. // Loading sound using XHR2
  44203. if (!this._streaming) {
  44204. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44205. }
  44206. else {
  44207. this._htmlAudioElement = new Audio(url);
  44208. this._htmlAudioElement.controls = false;
  44209. this._htmlAudioElement.loop = this.loop;
  44210. this._htmlAudioElement.crossOrigin = "anonymous";
  44211. this._htmlAudioElement.preload = "auto";
  44212. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44213. _this._isReadyToPlay = true;
  44214. if (_this.autoplay) {
  44215. _this.play();
  44216. }
  44217. if (_this._readyToPlayCallback) {
  44218. _this._readyToPlayCallback();
  44219. }
  44220. });
  44221. document.body.appendChild(this._htmlAudioElement);
  44222. }
  44223. break;
  44224. }
  44225. }
  44226. break;
  44227. default:
  44228. validParameter = false;
  44229. break;
  44230. }
  44231. if (!validParameter) {
  44232. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44233. }
  44234. else {
  44235. if (!codecSupportedFound) {
  44236. this._isReadyToPlay = true;
  44237. // Simulating a ready to play event to avoid breaking code path
  44238. if (this._readyToPlayCallback) {
  44239. window.setTimeout(function () {
  44240. _this._readyToPlayCallback();
  44241. }, 1000);
  44242. }
  44243. }
  44244. }
  44245. }
  44246. }
  44247. else {
  44248. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44249. this._scene.mainSoundTrack.AddSound(this);
  44250. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44251. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44252. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44253. }
  44254. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44255. if (this._readyToPlayCallback) {
  44256. window.setTimeout(function () {
  44257. _this._readyToPlayCallback();
  44258. }, 1000);
  44259. }
  44260. }
  44261. }
  44262. Sound.prototype.dispose = function () {
  44263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44264. if (this.isPlaying) {
  44265. this.stop();
  44266. }
  44267. this._isReadyToPlay = false;
  44268. if (this.soundTrackId === -1) {
  44269. this._scene.mainSoundTrack.RemoveSound(this);
  44270. }
  44271. else {
  44272. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44273. }
  44274. if (this._soundGain) {
  44275. this._soundGain.disconnect();
  44276. this._soundGain = null;
  44277. }
  44278. if (this._soundPanner) {
  44279. this._soundPanner.disconnect();
  44280. this._soundPanner = null;
  44281. }
  44282. if (this._soundSource) {
  44283. this._soundSource.disconnect();
  44284. this._soundSource = null;
  44285. }
  44286. this._audioBuffer = null;
  44287. if (this._htmlAudioElement) {
  44288. this._htmlAudioElement.pause();
  44289. this._htmlAudioElement.src = "";
  44290. document.body.removeChild(this._htmlAudioElement);
  44291. }
  44292. if (this._connectedMesh) {
  44293. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44294. this._connectedMesh = null;
  44295. }
  44296. }
  44297. };
  44298. Sound.prototype.isReady = function () {
  44299. return this._isReadyToPlay;
  44300. };
  44301. Sound.prototype._soundLoaded = function (audioData) {
  44302. var _this = this;
  44303. this._isLoaded = true;
  44304. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44305. _this._audioBuffer = buffer;
  44306. _this._isReadyToPlay = true;
  44307. if (_this.autoplay) {
  44308. _this.play();
  44309. }
  44310. if (_this._readyToPlayCallback) {
  44311. _this._readyToPlayCallback();
  44312. }
  44313. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44314. };
  44315. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44316. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44317. this._audioBuffer = audioBuffer;
  44318. this._isReadyToPlay = true;
  44319. }
  44320. };
  44321. Sound.prototype.updateOptions = function (options) {
  44322. if (options) {
  44323. this.loop = options.loop || this.loop;
  44324. this.maxDistance = options.maxDistance || this.maxDistance;
  44325. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44326. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44327. this.refDistance = options.refDistance || this.refDistance;
  44328. this.distanceModel = options.distanceModel || this.distanceModel;
  44329. this._playbackRate = options.playbackRate || this._playbackRate;
  44330. this._updateSpatialParameters();
  44331. if (this.isPlaying) {
  44332. if (this._streaming) {
  44333. this._htmlAudioElement.playbackRate = this._playbackRate;
  44334. }
  44335. else {
  44336. this._soundSource.playbackRate.value = this._playbackRate;
  44337. }
  44338. }
  44339. }
  44340. };
  44341. Sound.prototype._createSpatialParameters = function () {
  44342. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44343. if (this._scene.headphone) {
  44344. this._panningModel = "HRTF";
  44345. }
  44346. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44347. this._updateSpatialParameters();
  44348. this._soundPanner.connect(this._ouputAudioNode);
  44349. this._inputAudioNode = this._soundPanner;
  44350. }
  44351. };
  44352. Sound.prototype._updateSpatialParameters = function () {
  44353. if (this.spatialSound) {
  44354. if (this.useCustomAttenuation) {
  44355. // Tricks to disable in a way embedded Web Audio attenuation
  44356. this._soundPanner.distanceModel = "linear";
  44357. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44358. this._soundPanner.refDistance = 1;
  44359. this._soundPanner.rolloffFactor = 1;
  44360. this._soundPanner.panningModel = this._panningModel;
  44361. }
  44362. else {
  44363. this._soundPanner.distanceModel = this.distanceModel;
  44364. this._soundPanner.maxDistance = this.maxDistance;
  44365. this._soundPanner.refDistance = this.refDistance;
  44366. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44367. this._soundPanner.panningModel = this._panningModel;
  44368. }
  44369. }
  44370. };
  44371. Sound.prototype.switchPanningModelToHRTF = function () {
  44372. this._panningModel = "HRTF";
  44373. this._switchPanningModel();
  44374. };
  44375. Sound.prototype.switchPanningModelToEqualPower = function () {
  44376. this._panningModel = "equalpower";
  44377. this._switchPanningModel();
  44378. };
  44379. Sound.prototype._switchPanningModel = function () {
  44380. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44381. this._soundPanner.panningModel = this._panningModel;
  44382. }
  44383. };
  44384. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44385. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44386. if (this._isOutputConnected) {
  44387. this._ouputAudioNode.disconnect();
  44388. }
  44389. this._ouputAudioNode.connect(soundTrackAudioNode);
  44390. this._isOutputConnected = true;
  44391. }
  44392. };
  44393. /**
  44394. * Transform this sound into a directional source
  44395. * @param coneInnerAngle Size of the inner cone in degree
  44396. * @param coneOuterAngle Size of the outer cone in degree
  44397. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44398. */
  44399. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44400. if (coneOuterAngle < coneInnerAngle) {
  44401. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44402. return;
  44403. }
  44404. this._coneInnerAngle = coneInnerAngle;
  44405. this._coneOuterAngle = coneOuterAngle;
  44406. this._coneOuterGain = coneOuterGain;
  44407. this._isDirectional = true;
  44408. if (this.isPlaying && this.loop) {
  44409. this.stop();
  44410. this.play();
  44411. }
  44412. };
  44413. Sound.prototype.setPosition = function (newPosition) {
  44414. this._position = newPosition;
  44415. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44416. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44417. }
  44418. };
  44419. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44420. this._localDirection = newLocalDirection;
  44421. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44422. this._updateDirection();
  44423. }
  44424. };
  44425. Sound.prototype._updateDirection = function () {
  44426. var mat = this._connectedMesh.getWorldMatrix();
  44427. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44428. direction.normalize();
  44429. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44430. };
  44431. Sound.prototype.updateDistanceFromListener = function () {
  44432. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44433. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44434. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44435. }
  44436. };
  44437. Sound.prototype.setAttenuationFunction = function (callback) {
  44438. this._customAttenuationFunction = callback;
  44439. };
  44440. /**
  44441. * Play the sound
  44442. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44443. * @param offset (optional) Start the sound setting it at a specific time
  44444. */
  44445. Sound.prototype.play = function (time, offset) {
  44446. var _this = this;
  44447. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44448. try {
  44449. if (this._startOffset < 0) {
  44450. time = -this._startOffset;
  44451. this._startOffset = 0;
  44452. }
  44453. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44454. if (!this._soundSource || !this._streamingSource) {
  44455. if (this.spatialSound) {
  44456. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44457. if (this._isDirectional) {
  44458. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  44459. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  44460. this._soundPanner.coneOuterGain = this._coneOuterGain;
  44461. if (this._connectedMesh) {
  44462. this._updateDirection();
  44463. }
  44464. else {
  44465. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  44466. }
  44467. }
  44468. }
  44469. }
  44470. if (this._streaming) {
  44471. if (!this._streamingSource) {
  44472. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44473. this._htmlAudioElement.onended = function () { _this._onended(); };
  44474. this._htmlAudioElement.playbackRate = this._playbackRate;
  44475. }
  44476. this._streamingSource.disconnect();
  44477. this._streamingSource.connect(this._inputAudioNode);
  44478. this._htmlAudioElement.play();
  44479. }
  44480. else {
  44481. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44482. this._soundSource.buffer = this._audioBuffer;
  44483. this._soundSource.connect(this._inputAudioNode);
  44484. this._soundSource.loop = this.loop;
  44485. this._soundSource.playbackRate.value = this._playbackRate;
  44486. this._soundSource.onended = function () { _this._onended(); };
  44487. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44488. }
  44489. this._startTime = startTime;
  44490. this.isPlaying = true;
  44491. this.isPaused = false;
  44492. }
  44493. catch (ex) {
  44494. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44495. }
  44496. }
  44497. };
  44498. Sound.prototype._onended = function () {
  44499. this.isPlaying = false;
  44500. if (this.onended) {
  44501. this.onended();
  44502. }
  44503. };
  44504. /**
  44505. * Stop the sound
  44506. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44507. */
  44508. Sound.prototype.stop = function (time) {
  44509. if (this.isPlaying) {
  44510. if (this._streaming) {
  44511. this._htmlAudioElement.pause();
  44512. // Test needed for Firefox or it will generate an Invalid State Error
  44513. if (this._htmlAudioElement.currentTime > 0) {
  44514. this._htmlAudioElement.currentTime = 0;
  44515. }
  44516. }
  44517. else {
  44518. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44519. this._soundSource.stop(stopTime);
  44520. this._soundSource.onended = null;
  44521. if (!this.isPaused) {
  44522. this._startOffset = 0;
  44523. }
  44524. }
  44525. this.isPlaying = false;
  44526. }
  44527. };
  44528. Sound.prototype.pause = function () {
  44529. if (this.isPlaying) {
  44530. this.isPaused = true;
  44531. if (this._streaming) {
  44532. this._htmlAudioElement.pause();
  44533. }
  44534. else {
  44535. this.stop(0);
  44536. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44537. }
  44538. }
  44539. };
  44540. Sound.prototype.setVolume = function (newVolume, time) {
  44541. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44542. if (time) {
  44543. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44544. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44545. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44546. }
  44547. else {
  44548. this._soundGain.gain.value = newVolume;
  44549. }
  44550. }
  44551. this._volume = newVolume;
  44552. };
  44553. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44554. this._playbackRate = newPlaybackRate;
  44555. if (this.isPlaying) {
  44556. if (this._streaming) {
  44557. this._htmlAudioElement.playbackRate = this._playbackRate;
  44558. }
  44559. else {
  44560. this._soundSource.playbackRate.value = this._playbackRate;
  44561. }
  44562. }
  44563. };
  44564. Sound.prototype.getVolume = function () {
  44565. return this._volume;
  44566. };
  44567. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44568. var _this = this;
  44569. if (this._connectedMesh) {
  44570. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44571. this._registerFunc = null;
  44572. }
  44573. this._connectedMesh = meshToConnectTo;
  44574. if (!this.spatialSound) {
  44575. this.spatialSound = true;
  44576. this._createSpatialParameters();
  44577. if (this.isPlaying && this.loop) {
  44578. this.stop();
  44579. this.play();
  44580. }
  44581. }
  44582. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44583. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44584. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44585. };
  44586. Sound.prototype.detachFromMesh = function () {
  44587. if (this._connectedMesh) {
  44588. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44589. this._registerFunc = null;
  44590. this._connectedMesh = null;
  44591. }
  44592. };
  44593. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44594. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44595. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44596. this._updateDirection();
  44597. }
  44598. };
  44599. Sound.prototype.clone = function () {
  44600. var _this = this;
  44601. if (!this._streaming) {
  44602. var setBufferAndRun = function () {
  44603. if (_this._isReadyToPlay) {
  44604. clonedSound._audioBuffer = _this.getAudioBuffer();
  44605. clonedSound._isReadyToPlay = true;
  44606. if (clonedSound.autoplay) {
  44607. clonedSound.play();
  44608. }
  44609. }
  44610. else {
  44611. window.setTimeout(setBufferAndRun, 300);
  44612. }
  44613. };
  44614. var currentOptions = {
  44615. autoplay: this.autoplay, loop: this.loop,
  44616. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44617. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44618. refDistance: this.refDistance, distanceModel: this.distanceModel
  44619. };
  44620. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44621. if (this.useCustomAttenuation) {
  44622. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44623. }
  44624. clonedSound.setPosition(this._position);
  44625. clonedSound.setPlaybackRate(this._playbackRate);
  44626. setBufferAndRun();
  44627. return clonedSound;
  44628. }
  44629. else {
  44630. return null;
  44631. }
  44632. };
  44633. Sound.prototype.getAudioBuffer = function () {
  44634. return this._audioBuffer;
  44635. };
  44636. Sound.prototype.serialize = function () {
  44637. var serializationObject = {
  44638. name: this.name,
  44639. url: this.name,
  44640. autoplay: this.autoplay,
  44641. loop: this.loop,
  44642. volume: this._volume,
  44643. spatialSound: this.spatialSound,
  44644. maxDistance: this.maxDistance,
  44645. rolloffFactor: this.rolloffFactor,
  44646. refDistance: this.refDistance,
  44647. distanceModel: this.distanceModel,
  44648. playbackRate: this._playbackRate,
  44649. panningModel: this._panningModel,
  44650. soundTrackId: this.soundTrackId
  44651. };
  44652. if (this.spatialSound) {
  44653. if (this._connectedMesh)
  44654. serializationObject.connectedMeshId = this._connectedMesh.id;
  44655. serializationObject.position = this._position.asArray();
  44656. serializationObject.refDistance = this.refDistance;
  44657. serializationObject.distanceModel = this.distanceModel;
  44658. serializationObject.isDirectional = this._isDirectional;
  44659. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44660. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44661. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44662. serializationObject.coneOuterGain = this._coneOuterGain;
  44663. }
  44664. return serializationObject;
  44665. };
  44666. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44667. var soundName = parsedSound.name;
  44668. var soundUrl;
  44669. if (parsedSound.url) {
  44670. soundUrl = rootUrl + parsedSound.url;
  44671. }
  44672. else {
  44673. soundUrl = rootUrl + soundName;
  44674. }
  44675. var options = {
  44676. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44677. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44678. rolloffFactor: parsedSound.rolloffFactor,
  44679. refDistance: parsedSound.refDistance,
  44680. distanceModel: parsedSound.distanceModel,
  44681. playbackRate: parsedSound.playbackRate
  44682. };
  44683. var newSound;
  44684. if (!sourceSound) {
  44685. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44686. scene._addPendingData(newSound);
  44687. }
  44688. else {
  44689. var setBufferAndRun = function () {
  44690. if (sourceSound._isReadyToPlay) {
  44691. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44692. newSound._isReadyToPlay = true;
  44693. if (newSound.autoplay) {
  44694. newSound.play();
  44695. }
  44696. }
  44697. else {
  44698. window.setTimeout(setBufferAndRun, 300);
  44699. }
  44700. };
  44701. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44702. setBufferAndRun();
  44703. }
  44704. if (parsedSound.position) {
  44705. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44706. newSound.setPosition(soundPosition);
  44707. }
  44708. if (parsedSound.isDirectional) {
  44709. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44710. if (parsedSound.localDirectionToMesh) {
  44711. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44712. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44713. }
  44714. }
  44715. if (parsedSound.connectedMeshId) {
  44716. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44717. if (connectedMesh) {
  44718. newSound.attachToMesh(connectedMesh);
  44719. }
  44720. }
  44721. return newSound;
  44722. };
  44723. return Sound;
  44724. }());
  44725. BABYLON.Sound = Sound;
  44726. })(BABYLON || (BABYLON = {}));
  44727. //# sourceMappingURL=babylon.sound.js.map
  44728. var BABYLON;
  44729. (function (BABYLON) {
  44730. var SoundTrack = (function () {
  44731. function SoundTrack(scene, options) {
  44732. this.id = -1;
  44733. this._isMainTrack = false;
  44734. this._isInitialized = false;
  44735. this._scene = scene;
  44736. this.soundCollection = new Array();
  44737. this._options = options;
  44738. if (!this._isMainTrack) {
  44739. this._scene.soundTracks.push(this);
  44740. this.id = this._scene.soundTracks.length - 1;
  44741. }
  44742. }
  44743. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44744. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44745. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44746. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44747. if (this._options) {
  44748. if (this._options.volume) {
  44749. this._outputAudioNode.gain.value = this._options.volume;
  44750. }
  44751. if (this._options.mainTrack) {
  44752. this._isMainTrack = this._options.mainTrack;
  44753. }
  44754. }
  44755. this._isInitialized = true;
  44756. }
  44757. };
  44758. SoundTrack.prototype.dispose = function () {
  44759. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44760. if (this._connectedAnalyser) {
  44761. this._connectedAnalyser.stopDebugCanvas();
  44762. }
  44763. while (this.soundCollection.length) {
  44764. this.soundCollection[0].dispose();
  44765. }
  44766. if (this._outputAudioNode) {
  44767. this._outputAudioNode.disconnect();
  44768. }
  44769. this._outputAudioNode = null;
  44770. }
  44771. };
  44772. SoundTrack.prototype.AddSound = function (sound) {
  44773. if (!this._isInitialized) {
  44774. this._initializeSoundTrackAudioGraph();
  44775. }
  44776. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44777. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44778. }
  44779. if (sound.soundTrackId) {
  44780. if (sound.soundTrackId === -1) {
  44781. this._scene.mainSoundTrack.RemoveSound(sound);
  44782. }
  44783. else {
  44784. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44785. }
  44786. }
  44787. this.soundCollection.push(sound);
  44788. sound.soundTrackId = this.id;
  44789. };
  44790. SoundTrack.prototype.RemoveSound = function (sound) {
  44791. var index = this.soundCollection.indexOf(sound);
  44792. if (index !== -1) {
  44793. this.soundCollection.splice(index, 1);
  44794. }
  44795. };
  44796. SoundTrack.prototype.setVolume = function (newVolume) {
  44797. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44798. this._outputAudioNode.gain.value = newVolume;
  44799. }
  44800. };
  44801. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44802. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44803. for (var i = 0; i < this.soundCollection.length; i++) {
  44804. this.soundCollection[i].switchPanningModelToHRTF();
  44805. }
  44806. }
  44807. };
  44808. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44809. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44810. for (var i = 0; i < this.soundCollection.length; i++) {
  44811. this.soundCollection[i].switchPanningModelToEqualPower();
  44812. }
  44813. }
  44814. };
  44815. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44816. if (this._connectedAnalyser) {
  44817. this._connectedAnalyser.stopDebugCanvas();
  44818. }
  44819. this._connectedAnalyser = analyser;
  44820. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44821. this._outputAudioNode.disconnect();
  44822. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44823. }
  44824. };
  44825. return SoundTrack;
  44826. }());
  44827. BABYLON.SoundTrack = SoundTrack;
  44828. })(BABYLON || (BABYLON = {}));
  44829. //# sourceMappingURL=babylon.soundtrack.js.map
  44830. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  44831. /// <reference path="..\Math\babylon.math.ts" />
  44832. var BABYLON;
  44833. (function (BABYLON) {
  44834. /**
  44835. * Special Glow Blur post process only blurring the alpha channel
  44836. * It enforces keeping the most luminous color in the color channel.
  44837. */
  44838. var GlowBlurPostProcess = (function (_super) {
  44839. __extends(GlowBlurPostProcess, _super);
  44840. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44842. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  44843. _this.direction = direction;
  44844. _this.blurWidth = blurWidth;
  44845. _this.onApplyObservable.add(function (effect) {
  44846. effect.setFloat2("screenSize", _this.width, _this.height);
  44847. effect.setVector2("direction", _this.direction);
  44848. effect.setFloat("blurWidth", _this.blurWidth);
  44849. });
  44850. return _this;
  44851. }
  44852. return GlowBlurPostProcess;
  44853. }(BABYLON.PostProcess));
  44854. /**
  44855. * The highlight layer Helps adding a glow effect around a mesh.
  44856. *
  44857. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  44858. * glowy meshes to your scene.
  44859. *
  44860. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  44861. */
  44862. var HighlightLayer = (function () {
  44863. /**
  44864. * Instantiates a new highlight Layer and references it to the scene..
  44865. * @param name The name of the layer
  44866. * @param scene The scene to use the layer in
  44867. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  44868. */
  44869. function HighlightLayer(name, scene, options) {
  44870. this.name = name;
  44871. this._vertexBuffers = {};
  44872. this._mainTextureDesiredSize = { width: 0, height: 0 };
  44873. this._meshes = {};
  44874. this._maxSize = 0;
  44875. this._shouldRender = false;
  44876. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  44877. this._excludedMeshes = {};
  44878. /**
  44879. * Specifies whether or not the inner glow is ACTIVE in the layer.
  44880. */
  44881. this.innerGlow = true;
  44882. /**
  44883. * Specifies whether or not the outer glow is ACTIVE in the layer.
  44884. */
  44885. this.outerGlow = true;
  44886. /**
  44887. * Specifies wether the highlight layer is enabled or not.
  44888. */
  44889. this.isEnabled = true;
  44890. /**
  44891. * An event triggered when the highlight layer has been disposed.
  44892. * @type {BABYLON.Observable}
  44893. */
  44894. this.onDisposeObservable = new BABYLON.Observable();
  44895. /**
  44896. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  44897. * @type {BABYLON.Observable}
  44898. */
  44899. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  44900. /**
  44901. * An event triggered when the highlight layer is being blurred.
  44902. * @type {BABYLON.Observable}
  44903. */
  44904. this.onBeforeBlurObservable = new BABYLON.Observable();
  44905. /**
  44906. * An event triggered when the highlight layer has been blurred.
  44907. * @type {BABYLON.Observable}
  44908. */
  44909. this.onAfterBlurObservable = new BABYLON.Observable();
  44910. /**
  44911. * An event triggered when the glowing blurred texture is being merged in the scene.
  44912. * @type {BABYLON.Observable}
  44913. */
  44914. this.onBeforeComposeObservable = new BABYLON.Observable();
  44915. /**
  44916. * An event triggered when the glowing blurred texture has been merged in the scene.
  44917. * @type {BABYLON.Observable}
  44918. */
  44919. this.onAfterComposeObservable = new BABYLON.Observable();
  44920. /**
  44921. * An event triggered when the highlight layer changes its size.
  44922. * @type {BABYLON.Observable}
  44923. */
  44924. this.onSizeChangedObservable = new BABYLON.Observable();
  44925. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44926. var engine = scene.getEngine();
  44927. this._engine = engine;
  44928. this._maxSize = this._engine.getCaps().maxTextureSize;
  44929. this._scene.highlightLayers.push(this);
  44930. // Warn on stencil.
  44931. if (!this._engine.isStencilEnable) {
  44932. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  44933. }
  44934. // Adapt options
  44935. this._options = options || {
  44936. mainTextureRatio: 0.25,
  44937. blurTextureSizeRatio: 0.5,
  44938. blurHorizontalSize: 1,
  44939. blurVerticalSize: 1,
  44940. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  44941. };
  44942. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  44943. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  44944. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  44945. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  44946. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  44947. // VBO
  44948. var vertices = [];
  44949. vertices.push(1, 1);
  44950. vertices.push(-1, 1);
  44951. vertices.push(-1, -1);
  44952. vertices.push(1, -1);
  44953. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44954. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  44955. // Indices
  44956. var indices = [];
  44957. indices.push(0);
  44958. indices.push(1);
  44959. indices.push(2);
  44960. indices.push(0);
  44961. indices.push(2);
  44962. indices.push(3);
  44963. this._indexBuffer = engine.createIndexBuffer(indices);
  44964. // Effect
  44965. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  44966. // Render target
  44967. this.setMainTextureSize();
  44968. // Create Textures and post processes
  44969. this.createTextureAndPostProcesses();
  44970. }
  44971. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  44972. /**
  44973. * Gets the horizontal size of the blur.
  44974. */
  44975. get: function () {
  44976. return this._horizontalBlurPostprocess.blurWidth;
  44977. },
  44978. /**
  44979. * Specifies the horizontal size of the blur.
  44980. */
  44981. set: function (value) {
  44982. this._horizontalBlurPostprocess.blurWidth = value;
  44983. },
  44984. enumerable: true,
  44985. configurable: true
  44986. });
  44987. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  44988. /**
  44989. * Gets the vertical size of the blur.
  44990. */
  44991. get: function () {
  44992. return this._verticalBlurPostprocess.blurWidth;
  44993. },
  44994. /**
  44995. * Specifies the vertical size of the blur.
  44996. */
  44997. set: function (value) {
  44998. this._verticalBlurPostprocess.blurWidth = value;
  44999. },
  45000. enumerable: true,
  45001. configurable: true
  45002. });
  45003. Object.defineProperty(HighlightLayer.prototype, "camera", {
  45004. /**
  45005. * Gets the camera attached to the layer.
  45006. */
  45007. get: function () {
  45008. return this._options.camera;
  45009. },
  45010. enumerable: true,
  45011. configurable: true
  45012. });
  45013. /**
  45014. * Creates the render target textures and post processes used in the highlight layer.
  45015. */
  45016. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  45017. var _this = this;
  45018. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  45019. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  45020. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  45021. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  45022. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  45023. width: this._mainTextureDesiredSize.width,
  45024. height: this._mainTextureDesiredSize.height
  45025. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45026. this._mainTexture.activeCamera = this._options.camera;
  45027. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45028. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45029. this._mainTexture.anisotropicFilteringLevel = 1;
  45030. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45031. this._mainTexture.renderParticles = false;
  45032. this._mainTexture.renderList = null;
  45033. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  45034. width: blurTextureWidth,
  45035. height: blurTextureHeight
  45036. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45037. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45038. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45039. this._blurTexture.anisotropicFilteringLevel = 16;
  45040. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45041. this._blurTexture.renderParticles = false;
  45042. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  45043. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  45044. effect.setTexture("textureSampler", _this._mainTexture);
  45045. });
  45046. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  45047. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  45048. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  45049. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  45050. });
  45051. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  45052. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  45053. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  45054. });
  45055. }
  45056. else {
  45057. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  45058. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  45059. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  45060. });
  45061. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  45062. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  45063. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  45064. });
  45065. }
  45066. this._mainTexture.onAfterUnbindObservable.add(function () {
  45067. _this.onBeforeBlurObservable.notifyObservers(_this);
  45068. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  45069. _this.onAfterBlurObservable.notifyObservers(_this);
  45070. });
  45071. // Custom render function
  45072. var renderSubMesh = function (subMesh) {
  45073. var mesh = subMesh.getRenderingMesh();
  45074. var scene = _this._scene;
  45075. var engine = scene.getEngine();
  45076. // Culling
  45077. engine.setState(subMesh.getMaterial().backFaceCulling);
  45078. // Managing instances
  45079. var batch = mesh._getInstancesRenderList(subMesh._id);
  45080. if (batch.mustReturn) {
  45081. return;
  45082. }
  45083. // Excluded Mesh
  45084. if (_this._excludedMeshes[mesh.uniqueId]) {
  45085. return;
  45086. }
  45087. ;
  45088. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  45089. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  45090. var material = subMesh.getMaterial();
  45091. var emissiveTexture = null;
  45092. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  45093. emissiveTexture = material.emissiveTexture;
  45094. }
  45095. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  45096. engine.enableEffect(_this._glowMapGenerationEffect);
  45097. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  45098. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  45099. if (highlightLayerMesh) {
  45100. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  45101. }
  45102. else {
  45103. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  45104. }
  45105. // Alpha test
  45106. if (material && material.needAlphaTesting()) {
  45107. var alphaTexture = material.getAlphaTestTexture();
  45108. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  45109. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45110. }
  45111. // Glow emissive only
  45112. if (emissiveTexture) {
  45113. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  45114. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  45115. }
  45116. // Bones
  45117. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45118. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45119. }
  45120. // Draw
  45121. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  45122. }
  45123. else {
  45124. // Need to reset refresh rate of the shadowMap
  45125. _this._mainTexture.resetRefreshCounter();
  45126. }
  45127. };
  45128. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  45129. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  45130. var index;
  45131. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45132. renderSubMesh(opaqueSubMeshes.data[index]);
  45133. }
  45134. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45135. renderSubMesh(alphaTestSubMeshes.data[index]);
  45136. }
  45137. for (index = 0; index < transparentSubMeshes.length; index++) {
  45138. renderSubMesh(transparentSubMeshes.data[index]);
  45139. }
  45140. };
  45141. this._mainTexture.onClearObservable.add(function (engine) {
  45142. engine.clear(HighlightLayer.neutralColor, true, true, true);
  45143. });
  45144. };
  45145. /**
  45146. * Checks for the readiness of the element composing the layer.
  45147. * @param subMesh the mesh to check for
  45148. * @param useInstances specify wether or not to use instances to render the mesh
  45149. * @param emissiveTexture the associated emissive texture used to generate the glow
  45150. * @return true if ready otherwise, false
  45151. */
  45152. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  45153. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  45154. return false;
  45155. }
  45156. var defines = [];
  45157. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45158. var mesh = subMesh.getMesh();
  45159. var material = subMesh.getMaterial();
  45160. var uv1 = false;
  45161. var uv2 = false;
  45162. // Alpha test
  45163. if (material && material.needAlphaTesting()) {
  45164. var alphaTexture = material.getAlphaTestTexture();
  45165. if (alphaTexture) {
  45166. defines.push("#define ALPHATEST");
  45167. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  45168. alphaTexture.coordinatesIndex === 1) {
  45169. defines.push("#define DIFFUSEUV2");
  45170. uv2 = true;
  45171. }
  45172. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45173. defines.push("#define DIFFUSEUV1");
  45174. uv1 = true;
  45175. }
  45176. }
  45177. }
  45178. // Emissive
  45179. if (emissiveTexture) {
  45180. defines.push("#define EMISSIVE");
  45181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  45182. emissiveTexture.coordinatesIndex === 1) {
  45183. defines.push("#define EMISSIVEUV2");
  45184. uv2 = true;
  45185. }
  45186. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45187. defines.push("#define EMISSIVEUV1");
  45188. uv1 = true;
  45189. }
  45190. }
  45191. if (uv1) {
  45192. attribs.push(BABYLON.VertexBuffer.UVKind);
  45193. defines.push("#define UV1");
  45194. }
  45195. if (uv2) {
  45196. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45197. defines.push("#define UV2");
  45198. }
  45199. // Bones
  45200. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45201. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45202. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45203. if (mesh.numBoneInfluencers > 4) {
  45204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45206. }
  45207. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45208. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45209. }
  45210. else {
  45211. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45212. }
  45213. // Instances
  45214. if (useInstances) {
  45215. defines.push("#define INSTANCES");
  45216. attribs.push("world0");
  45217. attribs.push("world1");
  45218. attribs.push("world2");
  45219. attribs.push("world3");
  45220. }
  45221. // Get correct effect
  45222. var join = defines.join("\n");
  45223. if (this._cachedDefines !== join) {
  45224. this._cachedDefines = join;
  45225. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  45226. }
  45227. return this._glowMapGenerationEffect.isReady();
  45228. };
  45229. /**
  45230. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  45231. */
  45232. HighlightLayer.prototype.render = function () {
  45233. var currentEffect = this._glowMapMergeEffect;
  45234. // Check
  45235. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  45236. return;
  45237. var engine = this._scene.getEngine();
  45238. this.onBeforeComposeObservable.notifyObservers(this);
  45239. // Render
  45240. engine.enableEffect(currentEffect);
  45241. engine.setState(false);
  45242. // Cache
  45243. var previousStencilBuffer = engine.getStencilBuffer();
  45244. var previousStencilFunction = engine.getStencilFunction();
  45245. var previousStencilMask = engine.getStencilMask();
  45246. var previousAlphaMode = engine.getAlphaMode();
  45247. // Texture
  45248. currentEffect.setTexture("textureSampler", this._blurTexture);
  45249. // VBOs
  45250. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  45251. // Draw order
  45252. engine.setAlphaMode(this._options.alphaBlendingMode);
  45253. engine.setStencilMask(0x00);
  45254. engine.setStencilBuffer(true);
  45255. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  45256. if (this.outerGlow) {
  45257. currentEffect.setFloat("offset", 0);
  45258. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  45259. engine.draw(true, 0, 6);
  45260. }
  45261. if (this.innerGlow) {
  45262. currentEffect.setFloat("offset", 1);
  45263. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  45264. engine.draw(true, 0, 6);
  45265. }
  45266. // Restore Cache
  45267. engine.setStencilFunction(previousStencilFunction);
  45268. engine.setStencilMask(previousStencilMask);
  45269. engine.setAlphaMode(previousAlphaMode);
  45270. engine.setStencilBuffer(previousStencilBuffer);
  45271. this.onAfterComposeObservable.notifyObservers(this);
  45272. // Handle size changes.
  45273. var size = this._mainTexture.getSize();
  45274. this.setMainTextureSize();
  45275. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  45276. // Recreate RTT and post processes on size change.
  45277. this.onSizeChangedObservable.notifyObservers(this);
  45278. this.disposeTextureAndPostProcesses();
  45279. this.createTextureAndPostProcesses();
  45280. }
  45281. };
  45282. /**
  45283. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  45284. * @param mesh The mesh to exclude from the highlight layer
  45285. */
  45286. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  45287. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  45288. if (!meshExcluded) {
  45289. this._excludedMeshes[mesh.uniqueId] = {
  45290. mesh: mesh,
  45291. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  45292. mesh.getEngine().setStencilBuffer(false);
  45293. }),
  45294. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  45295. mesh.getEngine().setStencilBuffer(true);
  45296. }),
  45297. };
  45298. }
  45299. };
  45300. /**
  45301. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  45302. * @param mesh The mesh to highlight
  45303. */
  45304. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  45305. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  45306. if (meshExcluded) {
  45307. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  45308. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  45309. }
  45310. this._excludedMeshes[mesh.uniqueId] = undefined;
  45311. };
  45312. /**
  45313. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  45314. * @param mesh The mesh to highlight
  45315. * @param color The color of the highlight
  45316. * @param glowEmissiveOnly Extract the glow from the emissive texture
  45317. */
  45318. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  45319. var _this = this;
  45320. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  45321. var meshHighlight = this._meshes[mesh.uniqueId];
  45322. if (meshHighlight) {
  45323. meshHighlight.color = color;
  45324. }
  45325. else {
  45326. this._meshes[mesh.uniqueId] = {
  45327. mesh: mesh,
  45328. color: color,
  45329. // Lambda required for capture due to Observable this context
  45330. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  45331. if (_this._excludedMeshes[mesh.uniqueId]) {
  45332. _this.defaultStencilReference(mesh);
  45333. }
  45334. else {
  45335. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  45336. }
  45337. }),
  45338. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  45339. glowEmissiveOnly: glowEmissiveOnly
  45340. };
  45341. }
  45342. this._shouldRender = true;
  45343. };
  45344. /**
  45345. * Remove a mesh from the highlight layer in order to make it stop glowing.
  45346. * @param mesh The mesh to highlight
  45347. */
  45348. HighlightLayer.prototype.removeMesh = function (mesh) {
  45349. var meshHighlight = this._meshes[mesh.uniqueId];
  45350. if (meshHighlight) {
  45351. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  45352. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  45353. }
  45354. this._meshes[mesh.uniqueId] = undefined;
  45355. this._shouldRender = false;
  45356. for (var meshHighlightToCheck in this._meshes) {
  45357. if (meshHighlightToCheck) {
  45358. this._shouldRender = true;
  45359. break;
  45360. }
  45361. }
  45362. };
  45363. /**
  45364. * Returns true if the layer contains information to display, otherwise false.
  45365. */
  45366. HighlightLayer.prototype.shouldRender = function () {
  45367. return this.isEnabled && this._shouldRender;
  45368. };
  45369. /**
  45370. * Sets the main texture desired size which is the closest power of two
  45371. * of the engine canvas size.
  45372. */
  45373. HighlightLayer.prototype.setMainTextureSize = function () {
  45374. if (this._options.mainTextureFixedSize) {
  45375. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  45376. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  45377. }
  45378. else {
  45379. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  45380. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  45381. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  45382. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  45383. }
  45384. };
  45385. /**
  45386. * Force the stencil to the normal expected value for none glowing parts
  45387. */
  45388. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  45389. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  45390. };
  45391. /**
  45392. * Dispose only the render target textures and post process.
  45393. */
  45394. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  45395. this._blurTexture.dispose();
  45396. this._mainTexture.dispose();
  45397. this._downSamplePostprocess.dispose();
  45398. this._horizontalBlurPostprocess.dispose();
  45399. this._verticalBlurPostprocess.dispose();
  45400. };
  45401. /**
  45402. * Dispose the highlight layer and free resources.
  45403. */
  45404. HighlightLayer.prototype.dispose = function () {
  45405. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45406. if (vertexBuffer) {
  45407. vertexBuffer.dispose();
  45408. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45409. }
  45410. if (this._indexBuffer) {
  45411. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45412. this._indexBuffer = null;
  45413. }
  45414. // Clean textures and post processes
  45415. this.disposeTextureAndPostProcesses();
  45416. // Clean mesh references
  45417. for (var id in this._meshes) {
  45418. var meshHighlight = this._meshes[id];
  45419. if (meshHighlight && meshHighlight.mesh) {
  45420. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  45421. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  45422. }
  45423. }
  45424. this._meshes = null;
  45425. for (var id in this._excludedMeshes) {
  45426. var meshHighlight = this._excludedMeshes[id];
  45427. if (meshHighlight) {
  45428. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  45429. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  45430. }
  45431. }
  45432. this._excludedMeshes = null;
  45433. // Remove from scene
  45434. var index = this._scene.highlightLayers.indexOf(this, 0);
  45435. if (index > -1) {
  45436. this._scene.highlightLayers.splice(index, 1);
  45437. }
  45438. // Callback
  45439. this.onDisposeObservable.notifyObservers(this);
  45440. this.onDisposeObservable.clear();
  45441. this.onBeforeRenderMainTextureObservable.clear();
  45442. this.onBeforeBlurObservable.clear();
  45443. this.onBeforeComposeObservable.clear();
  45444. this.onAfterComposeObservable.clear();
  45445. this.onSizeChangedObservable.clear();
  45446. };
  45447. return HighlightLayer;
  45448. }());
  45449. /**
  45450. * The neutral color used during the preparation of the glow effect.
  45451. * This is black by default as the blend operation is a blend operation.
  45452. */
  45453. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  45454. /**
  45455. * Stencil value used for glowing meshes.
  45456. */
  45457. HighlightLayer.glowingMeshStencilReference = 0x02;
  45458. /**
  45459. * Stencil value used for the other meshes in the scene.
  45460. */
  45461. HighlightLayer.normalMeshStencilReference = 0x01;
  45462. BABYLON.HighlightLayer = HighlightLayer;
  45463. })(BABYLON || (BABYLON = {}));
  45464. //# sourceMappingURL=babylon.highlightlayer.js.map
  45465. var BABYLON;
  45466. (function (BABYLON) {
  45467. var SIMDVector3 = (function () {
  45468. function SIMDVector3() {
  45469. }
  45470. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  45471. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  45472. };
  45473. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  45474. var m = transformation.m;
  45475. var m0 = SIMD.Float32x4.load(m, 0);
  45476. var m1 = SIMD.Float32x4.load(m, 4);
  45477. var m2 = SIMD.Float32x4.load(m, 8);
  45478. var m3 = SIMD.Float32x4.load(m, 12);
  45479. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  45480. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  45481. result.x = SIMD.Float32x4.extractLane(r, 0);
  45482. result.y = SIMD.Float32x4.extractLane(r, 1);
  45483. result.z = SIMD.Float32x4.extractLane(r, 2);
  45484. };
  45485. return SIMDVector3;
  45486. }());
  45487. var SIMDMatrix = (function () {
  45488. function SIMDMatrix() {
  45489. }
  45490. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  45491. var tm = this.m;
  45492. var om = other.m;
  45493. var m0 = SIMD.Float32x4.load(om, 0);
  45494. var m1 = SIMD.Float32x4.load(om, 4);
  45495. var m2 = SIMD.Float32x4.load(om, 8);
  45496. var m3 = SIMD.Float32x4.load(om, 12);
  45497. for (var i = 0; i < 16; i += 4) {
  45498. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  45499. }
  45500. return this;
  45501. };
  45502. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  45503. var src = this.m;
  45504. var dest = other.m;
  45505. // Load the 4 rows
  45506. var src0 = SIMD.Float32x4.load(src, 0);
  45507. var src1 = SIMD.Float32x4.load(src, 4);
  45508. var src2 = SIMD.Float32x4.load(src, 8);
  45509. var src3 = SIMD.Float32x4.load(src, 12);
  45510. // Transpose the source matrix. Sort of. Not a true transpose operation
  45511. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  45512. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  45513. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  45514. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  45515. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  45516. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  45517. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  45518. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  45519. // This is a true transposition, but it will lead to an incorrect result
  45520. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  45521. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  45522. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  45523. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  45524. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  45525. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  45526. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  45527. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  45528. // ----
  45529. tmp1 = SIMD.Float32x4.mul(row2, row3);
  45530. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45531. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  45532. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  45533. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45534. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  45535. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  45536. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  45537. // ----
  45538. tmp1 = SIMD.Float32x4.mul(row1, row2);
  45539. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45540. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  45541. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  45542. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45543. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  45544. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  45545. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  45546. // ----
  45547. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  45548. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45549. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  45550. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  45551. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  45552. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45553. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  45554. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  45555. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  45556. // ----
  45557. tmp1 = SIMD.Float32x4.mul(row0, row1);
  45558. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45559. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  45560. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  45561. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45562. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  45563. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  45564. // ----
  45565. tmp1 = SIMD.Float32x4.mul(row0, row3);
  45566. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45567. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  45568. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  45569. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45570. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  45571. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  45572. // ----
  45573. tmp1 = SIMD.Float32x4.mul(row0, row2);
  45574. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  45575. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  45576. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  45577. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  45578. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  45579. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  45580. // Compute determinant
  45581. var det = SIMD.Float32x4.mul(row0, minor0);
  45582. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  45583. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  45584. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  45585. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  45586. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  45587. // These shuffles aren't necessary if the faulty transposition is done
  45588. // up at the top of this function.
  45589. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  45590. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  45591. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  45592. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  45593. // Compute final values by multiplying with 1/det
  45594. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  45595. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  45596. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  45597. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  45598. return this;
  45599. };
  45600. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  45601. var out = result.m;
  45602. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  45603. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  45604. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  45605. // cc.kmVec3Subtract(f, pCenter, pEye);
  45606. var f = SIMD.Float32x4.sub(center, eye);
  45607. // cc.kmVec3Normalize(f, f);
  45608. var tmp = SIMD.Float32x4.mul(f, f);
  45609. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45610. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45611. // cc.kmVec3Assign(up, pUp);
  45612. // cc.kmVec3Normalize(up, up);
  45613. tmp = SIMD.Float32x4.mul(up, up);
  45614. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45615. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45616. // cc.kmVec3Cross(s, f, up);
  45617. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  45618. // cc.kmVec3Normalize(s, s);
  45619. tmp = SIMD.Float32x4.mul(s, s);
  45620. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45621. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45622. // cc.kmVec3Cross(u, s, f);
  45623. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  45624. // cc.kmVec3Normalize(s, s);
  45625. tmp = SIMD.Float32x4.mul(s, s);
  45626. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  45627. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  45628. var zero = SIMD.Float32x4.splat(0.0);
  45629. s = SIMD.Float32x4.neg(s);
  45630. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  45631. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  45632. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  45633. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  45634. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  45635. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  45636. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  45637. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  45638. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  45639. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  45640. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  45641. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  45642. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  45643. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  45644. };
  45645. return SIMDMatrix;
  45646. }());
  45647. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  45648. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  45649. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  45650. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  45651. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  45652. var SIMDHelper = (function () {
  45653. function SIMDHelper() {
  45654. }
  45655. Object.defineProperty(SIMDHelper, "IsEnabled", {
  45656. get: function () {
  45657. return SIMDHelper._isEnabled;
  45658. },
  45659. enumerable: true,
  45660. configurable: true
  45661. });
  45662. SIMDHelper.DisableSIMD = function () {
  45663. // Replace functions
  45664. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  45665. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  45666. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  45667. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  45668. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  45669. SIMDHelper._isEnabled = false;
  45670. };
  45671. SIMDHelper.EnableSIMD = function () {
  45672. if (self.SIMD === undefined) {
  45673. return;
  45674. }
  45675. // check if polyfills needed
  45676. if (!self.Math.fround) {
  45677. self.Math.fround = (function (array) { return function (x) {
  45678. return array[0] = x, array[0];
  45679. }; })(new Float32Array(1));
  45680. }
  45681. if (!self.Math.imul) {
  45682. self.Math.imul = function (a, b) {
  45683. var ah = (a >>> 16) & 0xffff;
  45684. var al = a & 0xffff;
  45685. var bh = (b >>> 16) & 0xffff;
  45686. var bl = b & 0xffff;
  45687. // the shift by 0 fixes the sign on the high part
  45688. // the final |0 converts the unsigned value into a signed value
  45689. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  45690. };
  45691. }
  45692. // Replace functions
  45693. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  45694. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  45695. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  45696. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  45697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  45698. SIMDHelper._isEnabled = true;
  45699. };
  45700. return SIMDHelper;
  45701. }());
  45702. SIMDHelper._isEnabled = false;
  45703. BABYLON.SIMDHelper = SIMDHelper;
  45704. })(BABYLON || (BABYLON = {}));
  45705. //# sourceMappingURL=babylon.math.SIMD.js.map
  45706. var BABYLON;
  45707. (function (BABYLON) {
  45708. /**
  45709. * This class describe a rectangle that were added to the map.
  45710. * You have access to its coordinates either in pixel or normalized (UV)
  45711. */
  45712. var PackedRect = (function () {
  45713. function PackedRect(root, parent, pos, size) {
  45714. this._pos = pos;
  45715. this._size = size;
  45716. this._root = root;
  45717. this._parent = parent;
  45718. this._contentSize = null;
  45719. this._bottomNode = null;
  45720. this._leftNode = null;
  45721. this._initialSize = null;
  45722. this._rightNode = null;
  45723. }
  45724. Object.defineProperty(PackedRect.prototype, "pos", {
  45725. /**
  45726. * @returns the position of this node into the map
  45727. */
  45728. get: function () {
  45729. return this._pos;
  45730. },
  45731. enumerable: true,
  45732. configurable: true
  45733. });
  45734. Object.defineProperty(PackedRect.prototype, "contentSize", {
  45735. /**
  45736. * @returns the size of the rectangle this node handles
  45737. */
  45738. get: function () {
  45739. return this._contentSize;
  45740. },
  45741. enumerable: true,
  45742. configurable: true
  45743. });
  45744. /**
  45745. * Retrieve the inner position (considering the margin) and stores it into the res object
  45746. * @param res must be a valid Vector2 that will contain the inner position after this call
  45747. */
  45748. PackedRect.prototype.getInnerPosToRef = function (res) {
  45749. var m = this._root._margin;
  45750. res.x = this._pos.x + m;
  45751. res.y = this._pos.y + m;
  45752. };
  45753. /**
  45754. * Retrieve the inner size (considering the margin) and stores it into the res object
  45755. * @param res must be a valid Size that will contain the inner size after this call
  45756. */
  45757. PackedRect.prototype.getInnerSizeToRef = function (res) {
  45758. var m = this._root._margin;
  45759. res.width = this._contentSize.width - (m * 2);
  45760. res.height = this._contentSize.height - (m * 2);
  45761. };
  45762. Object.defineProperty(PackedRect.prototype, "UVs", {
  45763. /**
  45764. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  45765. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  45766. */
  45767. get: function () {
  45768. if (!this._contentSize) {
  45769. throw new Error("Can't compute UVs for this object because it's nor allocated");
  45770. }
  45771. return this.getUVsForCustomSize(this._contentSize);
  45772. },
  45773. enumerable: true,
  45774. configurable: true
  45775. });
  45776. /**
  45777. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  45778. * and then using only a part of the PackRect.
  45779. * This method will return the UVs for this part by given the custom size of what you really use
  45780. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  45781. */
  45782. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  45783. var mainWidth = this._root._size.width;
  45784. var mainHeight = this._root._size.height;
  45785. var margin = this._root._margin;
  45786. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  45787. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  45788. var uvs = new Array();
  45789. uvs.push(topLeft);
  45790. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  45791. uvs.push(rightBottom);
  45792. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  45793. return uvs;
  45794. };
  45795. /**
  45796. * Free this rectangle from the map.
  45797. * Call this method when you no longer need the rectangle to be in the map.
  45798. */
  45799. PackedRect.prototype.freeContent = function () {
  45800. if (!this.contentSize) {
  45801. return;
  45802. }
  45803. this._contentSize = null;
  45804. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  45805. this.attemptDefrag();
  45806. };
  45807. Object.defineProperty(PackedRect.prototype, "isUsed", {
  45808. get: function () {
  45809. return this._contentSize != null || this._leftNode != null;
  45810. },
  45811. enumerable: true,
  45812. configurable: true
  45813. });
  45814. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  45815. var node = this.findNode(contentSize);
  45816. // Not enough space...
  45817. if (!node) {
  45818. return null;
  45819. }
  45820. node.splitNode(contentSize);
  45821. return node;
  45822. };
  45823. PackedRect.prototype.findNode = function (size) {
  45824. var resNode = null;
  45825. var margin = this._root._margin * 2;
  45826. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  45827. if (this.isUsed) {
  45828. if (this._leftNode) {
  45829. resNode = this._leftNode.findNode(size);
  45830. }
  45831. if (!resNode && this._rightNode) {
  45832. resNode = this._rightNode.findNode(size);
  45833. }
  45834. if (!resNode && this._bottomNode) {
  45835. resNode = this._bottomNode.findNode(size);
  45836. }
  45837. }
  45838. else if (this._initialSize) {
  45839. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  45840. resNode = this;
  45841. }
  45842. else {
  45843. return null;
  45844. }
  45845. }
  45846. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  45847. resNode = this;
  45848. }
  45849. return resNode;
  45850. };
  45851. PackedRect.prototype.splitNode = function (contentSize) {
  45852. var cs = PackedRect.TpsSize;
  45853. var margin = this._root._margin * 2;
  45854. cs.copyFrom(contentSize);
  45855. cs.width += margin;
  45856. cs.height += margin;
  45857. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  45858. if (!this._contentSize && this._initialSize) {
  45859. this._contentSize = cs.clone();
  45860. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  45861. return this._leftNode.splitNode(contentSize);
  45862. }
  45863. else {
  45864. this._contentSize = cs.clone();
  45865. this._initialSize = cs.clone();
  45866. if (cs.width !== this._size.width) {
  45867. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  45868. }
  45869. if (cs.height !== this._size.height) {
  45870. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  45871. }
  45872. return this;
  45873. }
  45874. };
  45875. PackedRect.prototype.attemptDefrag = function () {
  45876. if (!this.isUsed && this.isRecursiveFree) {
  45877. this.clearNode();
  45878. if (this._parent) {
  45879. this._parent.attemptDefrag();
  45880. }
  45881. }
  45882. };
  45883. PackedRect.prototype.clearNode = function () {
  45884. this._initialSize = null;
  45885. this._rightNode = null;
  45886. this._bottomNode = null;
  45887. };
  45888. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  45889. get: function () {
  45890. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  45891. },
  45892. enumerable: true,
  45893. configurable: true
  45894. });
  45895. PackedRect.prototype.evalFreeSize = function (size) {
  45896. var levelSize = 0;
  45897. if (!this.isUsed) {
  45898. var margin = this._root._margin;
  45899. var is = this._initialSize;
  45900. if (is) {
  45901. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  45902. }
  45903. else {
  45904. var size_1 = this._size;
  45905. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  45906. }
  45907. }
  45908. if (this._rightNode) {
  45909. levelSize += this._rightNode.evalFreeSize(0);
  45910. }
  45911. if (this._bottomNode) {
  45912. levelSize += this._bottomNode.evalFreeSize(0);
  45913. }
  45914. return levelSize + size;
  45915. };
  45916. return PackedRect;
  45917. }());
  45918. PackedRect.TpsSize = BABYLON.Size.Zero();
  45919. BABYLON.PackedRect = PackedRect;
  45920. /**
  45921. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  45922. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  45923. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  45924. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  45925. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  45926. */
  45927. var RectPackingMap = (function (_super) {
  45928. __extends(RectPackingMap, _super);
  45929. /**
  45930. * Create an instance of the object with a dimension using the given size
  45931. * @param size The dimension of the rectangle that will contain all the sub ones.
  45932. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  45933. */
  45934. function RectPackingMap(size, margin) {
  45935. if (margin === void 0) { margin = 0; }
  45936. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  45937. _this._margin = margin;
  45938. _this._root = _this;
  45939. return _this;
  45940. }
  45941. /**
  45942. * Add a rectangle, finding the best location to store it into the map
  45943. * @param size the dimension of the rectangle to store
  45944. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  45945. */
  45946. RectPackingMap.prototype.addRect = function (size) {
  45947. var node = this.findAndSplitNode(size);
  45948. return node;
  45949. };
  45950. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  45951. /**
  45952. * Return the current space free normalized between [0;1]
  45953. * @returns {}
  45954. */
  45955. get: function () {
  45956. var freeSize = 0;
  45957. freeSize = this.evalFreeSize(freeSize);
  45958. return freeSize / (this._size.width * this._size.height);
  45959. },
  45960. enumerable: true,
  45961. configurable: true
  45962. });
  45963. return RectPackingMap;
  45964. }(PackedRect));
  45965. BABYLON.RectPackingMap = RectPackingMap;
  45966. })(BABYLON || (BABYLON = {}));
  45967. //# sourceMappingURL=babylon.rectPackingMap.js.map
  45968. var BABYLON;
  45969. (function (BABYLON) {
  45970. var DynamicFloatArrayElementInfo = (function () {
  45971. function DynamicFloatArrayElementInfo() {
  45972. }
  45973. return DynamicFloatArrayElementInfo;
  45974. }());
  45975. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  45976. /**
  45977. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  45978. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  45979. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  45980. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  45981. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  45982. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  45983. */
  45984. var DynamicFloatArray = (function () {
  45985. /**
  45986. * Construct an instance of the dynamic float array
  45987. * @param stride size of one element in float (i.e. not bytes!)
  45988. * @param initialElementCount the number of available entries at construction
  45989. */
  45990. function DynamicFloatArray(stride, initialElementCount) {
  45991. this.compareValueOffset = null;
  45992. this.sortingAscending = true;
  45993. this._stride = stride;
  45994. this.buffer = new Float32Array(stride * initialElementCount);
  45995. this._lastUsed = 0;
  45996. this._firstFree = 0;
  45997. this._allEntries = new Array(initialElementCount);
  45998. this._freeEntries = new Array(initialElementCount);
  45999. for (var i = 0; i < initialElementCount; i++) {
  46000. var element = new DynamicFloatArrayElementInfo();
  46001. element.offset = i * stride;
  46002. this._allEntries[i] = element;
  46003. this._freeEntries[initialElementCount - i - 1] = element;
  46004. }
  46005. }
  46006. /**
  46007. * Allocate an element in the array.
  46008. * @return the element info instance that contains the offset into the main buffer of the element's location.
  46009. * Beware, this offset may change when you call pack()
  46010. */
  46011. DynamicFloatArray.prototype.allocElement = function () {
  46012. if (this._freeEntries.length === 0) {
  46013. this._growBuffer();
  46014. }
  46015. var el = this._freeEntries.pop();
  46016. this._lastUsed = Math.max(el.offset, this._lastUsed);
  46017. if (el.offset === this._firstFree) {
  46018. if (this._freeEntries.length > 0) {
  46019. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  46020. }
  46021. else {
  46022. this._firstFree += this._stride;
  46023. }
  46024. }
  46025. return el;
  46026. };
  46027. /**
  46028. * Free the element corresponding to the given element info
  46029. * @param elInfo the element that describe the allocated element
  46030. */
  46031. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  46032. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  46033. this._freeEntries.push(elInfo);
  46034. };
  46035. /**
  46036. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  46037. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  46038. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  46039. */
  46040. DynamicFloatArray.prototype.pack = function () {
  46041. // no free slot? no need to pack
  46042. if (this._freeEntries.length === 0) {
  46043. return this.buffer;
  46044. }
  46045. // If the buffer is already packed the last used will always be lower than the first free
  46046. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  46047. if (this._lastUsed < this._firstFree) {
  46048. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  46049. return elementsBuffer_1;
  46050. }
  46051. var s = this._stride;
  46052. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  46053. var lastFree = new DynamicFloatArrayElementInfo();
  46054. lastFree.offset = this.totalElementCount * s;
  46055. this._freeEntries.push(lastFree);
  46056. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  46057. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  46058. var firstFreeSlotOffset = sortedFree[0].offset;
  46059. var freeZoneSize = 1;
  46060. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  46061. var prevOffset = sortedFree[0].offset;
  46062. for (var i = 1; i < sortedFree.length; i++) {
  46063. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  46064. if (firstFreeSlotOffset >= occupiedZoneSize) {
  46065. break;
  46066. }
  46067. var curFree = sortedFree[i];
  46068. var curOffset = curFree.offset;
  46069. // Compute the distance between this offset and the previous
  46070. var distance = curOffset - prevOffset;
  46071. // If the distance is the stride size, they are adjacent, it good, move to the next
  46072. if (distance === s) {
  46073. // Free zone is one element bigger
  46074. ++freeZoneSize;
  46075. // as we're about to iterate to the next, the cur becomes the previous...
  46076. prevOffset = curOffset;
  46077. continue;
  46078. }
  46079. // Distance is bigger, which means there's x element between the previous free and this one
  46080. var usedRange = (distance / s) - 1;
  46081. // Two cases the free zone is smaller than the data to move or bigger
  46082. // Copy what can fit in the free zone
  46083. var curMoveOffset = curOffset - s;
  46084. var copyCount = Math.min(freeZoneSize, usedRange);
  46085. for (var j = 0; j < copyCount; j++) {
  46086. var freeI = firstFreeSlotOffset / s;
  46087. var curI = curMoveOffset / s;
  46088. var moveEl = sortedAll[curI];
  46089. this._moveElement(moveEl, firstFreeSlotOffset);
  46090. var replacedEl = sortedAll[freeI];
  46091. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  46092. replacedEl.offset = curMoveOffset;
  46093. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  46094. sortedAll[freeI] = moveEl;
  46095. sortedAll[curI] = replacedEl;
  46096. curMoveOffset -= s;
  46097. firstFreeSlotOffset += s;
  46098. }
  46099. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  46100. if (freeZoneSize <= usedRange) {
  46101. firstFreeSlotOffset = curMoveOffset + s;
  46102. freeZoneSize = 1 + copyCount;
  46103. }
  46104. else {
  46105. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  46106. }
  46107. // as we're about to iterate to the next, the cur becomes the previous...
  46108. prevOffset = curOffset;
  46109. }
  46110. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  46111. this._lastUsed = firstFreeSlotOffset - s;
  46112. this._firstFree = firstFreeSlotOffset;
  46113. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  46114. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  46115. this._allEntries = sortedAll;
  46116. return elementsBuffer;
  46117. };
  46118. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  46119. for (var i = 0; i < this._stride; i++) {
  46120. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  46121. }
  46122. element.offset = destOffset;
  46123. };
  46124. DynamicFloatArray.prototype._growBuffer = function () {
  46125. // Allocate the new buffer with 50% more entries, copy the content of the current one
  46126. var newElCount = Math.floor(this.totalElementCount * 1.5);
  46127. var newBuffer = new Float32Array(newElCount * this._stride);
  46128. newBuffer.set(this.buffer);
  46129. var curCount = this.totalElementCount;
  46130. var addedCount = newElCount - this.totalElementCount;
  46131. for (var i = 0; i < addedCount; i++) {
  46132. var element = new DynamicFloatArrayElementInfo();
  46133. element.offset = (curCount + i) * this.stride;
  46134. this._allEntries.push(element);
  46135. this._freeEntries[addedCount - i - 1] = element;
  46136. }
  46137. this._firstFree = curCount * this.stride;
  46138. this.buffer = newBuffer;
  46139. };
  46140. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  46141. /**
  46142. * Get the total count of entries that can fit in the current buffer
  46143. * @returns the elements count
  46144. */
  46145. get: function () {
  46146. return this._allEntries.length;
  46147. },
  46148. enumerable: true,
  46149. configurable: true
  46150. });
  46151. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  46152. /**
  46153. * Get the count of free entries that can still be allocated without resizing the buffer
  46154. * @returns the free elements count
  46155. */
  46156. get: function () {
  46157. return this._freeEntries.length;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  46163. /**
  46164. * Get the count of allocated elements
  46165. * @returns the allocated elements count
  46166. */
  46167. get: function () {
  46168. return this._allEntries.length - this._freeEntries.length;
  46169. },
  46170. enumerable: true,
  46171. configurable: true
  46172. });
  46173. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  46174. /**
  46175. * Return the size of one element in float
  46176. * @returns the size in float
  46177. */
  46178. get: function () {
  46179. return this._stride;
  46180. },
  46181. enumerable: true,
  46182. configurable: true
  46183. });
  46184. DynamicFloatArray.prototype.sort = function () {
  46185. var _this = this;
  46186. if (!this.compareValueOffset) {
  46187. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  46188. }
  46189. var count = this.usedElementCount;
  46190. // Do we have to (re)create the sort table?
  46191. if (!this._sortTable || this._sortTable.length < count) {
  46192. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  46193. var newCount = Math.min(this.totalElementCount, count * 2);
  46194. this._sortTable = new Array(newCount);
  46195. }
  46196. if (!this._sortedTable || this._sortedTable.length !== count) {
  46197. this._sortedTable = new Array(count);
  46198. }
  46199. // Because, you know...
  46200. this.pack();
  46201. //let stride = this.stride;
  46202. //for (let i = 0; i < count; i++) {
  46203. // let si = this._sortTable[i];
  46204. // if (!si) {
  46205. // si = new SortInfo();
  46206. // this._sortTable[i] = si;
  46207. // }
  46208. // si.entry = this._allEntries[i];
  46209. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  46210. // si.swapedOffset = null;
  46211. // this._sortedTable[i] = si;
  46212. //}
  46213. var curOffset = 0;
  46214. var stride = this.stride;
  46215. for (var i = 0; i < count; i++, curOffset += stride) {
  46216. var si = this._sortTable[i];
  46217. if (!si) {
  46218. si = new SortInfo();
  46219. this._sortTable[i] = si;
  46220. }
  46221. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  46222. si.offset = curOffset;
  46223. si.swapedOffset = null;
  46224. this._sortedTable[i] = si;
  46225. }
  46226. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  46227. if (this.sortingAscending) {
  46228. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  46229. }
  46230. else {
  46231. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  46232. }
  46233. var swapElements = function (src, dst) {
  46234. for (var i = 0; i < stride; i++) {
  46235. var tps = _this.buffer[dst + i];
  46236. _this.buffer[dst + i] = _this.buffer[src + i];
  46237. _this.buffer[src + i] = tps;
  46238. }
  46239. };
  46240. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  46241. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  46242. // and I still want something with a good algorithm complexity.
  46243. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  46244. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  46245. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  46246. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  46247. // until we find a SortInfo object without a swapedOffset which means we got the right location
  46248. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  46249. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  46250. for (var i = 0; i < count; i++) {
  46251. // Get the element to move
  46252. var sourceSI = this._sortedTable[i];
  46253. var destSI = this._sortTable[i];
  46254. var sourceOff = sourceSI.offset;
  46255. // If the source changed location, find the new one
  46256. if (sourceSI.swapedOffset) {
  46257. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  46258. var curSI = sourceSI;
  46259. while (curSI.swapedOffset) {
  46260. curSI = this._sortTable[curSI.swapedOffset / stride];
  46261. }
  46262. // Finally get the right location
  46263. sourceOff = curSI.offset;
  46264. }
  46265. // Tag the element being replaced with its new location
  46266. destSI.swapedOffset = sourceOff;
  46267. // Swap elements (only if needed)
  46268. if (sourceOff !== destSI.offset) {
  46269. swapElements(sourceOff, destSI.offset);
  46270. }
  46271. // Update the offset in the corresponding DFAE
  46272. //sourceSI.entry.offset = destSI.entry.offset;
  46273. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  46274. }
  46275. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  46276. return true;
  46277. };
  46278. return DynamicFloatArray;
  46279. }());
  46280. BABYLON.DynamicFloatArray = DynamicFloatArray;
  46281. var SortInfo = (function () {
  46282. function SortInfo() {
  46283. this.compareData = this.offset = this.swapedOffset = null;
  46284. }
  46285. return SortInfo;
  46286. }());
  46287. })(BABYLON || (BABYLON = {}));
  46288. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  46289. var BABYLON;
  46290. (function (BABYLON) {
  46291. var MapTexture = (function (_super) {
  46292. __extends(MapTexture, _super);
  46293. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  46294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46295. if (useMipMap === void 0) { useMipMap = false; }
  46296. if (margin === void 0) { margin = 0; }
  46297. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  46298. _this.name = name;
  46299. _this._size = size;
  46300. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46301. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46302. // Create the rectPackMap that will allocate portion of the texture
  46303. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  46304. // Create the texture that will store the content
  46305. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  46306. return _this;
  46307. }
  46308. /**
  46309. * Allocate a rectangle of a given size in the texture map
  46310. * @param size the size of the rectangle to allocation
  46311. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  46312. */
  46313. MapTexture.prototype.allocateRect = function (size) {
  46314. return this._rectPackingMap.addRect(size);
  46315. };
  46316. /**
  46317. * Free a given rectangle from the texture map
  46318. * @param rectInfo the instance corresponding to the rect to free.
  46319. */
  46320. MapTexture.prototype.freeRect = function (rectInfo) {
  46321. if (rectInfo) {
  46322. rectInfo.freeContent();
  46323. }
  46324. };
  46325. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  46326. /**
  46327. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  46328. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  46329. * @returns {}
  46330. */
  46331. get: function () {
  46332. return this._rectPackingMap.freeSpace;
  46333. },
  46334. enumerable: true,
  46335. configurable: true
  46336. });
  46337. /**
  46338. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  46339. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  46340. * Don't forget to call unbindTexture when you're done rendering
  46341. * @param rect the zone to render to
  46342. * @param clear true to clear the portion's color/depth data
  46343. */
  46344. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  46345. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  46346. };
  46347. /**
  46348. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  46349. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  46350. * Don't forget to call unbindTexture when you're done rendering
  46351. * @param pos the position into the texture
  46352. * @param size the portion to fit the clip space to
  46353. * @param clear true to clear the portion's color/depth data
  46354. */
  46355. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  46356. var engine = this.getScene().getEngine();
  46357. engine.bindFramebuffer(this._texture);
  46358. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  46359. if (clear) {
  46360. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  46361. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  46362. }
  46363. };
  46364. /**
  46365. * Unbind the texture map from the rendering engine.
  46366. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  46367. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  46368. */
  46369. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  46370. // Dump ?
  46371. if (dumpForDebug) {
  46372. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  46373. }
  46374. var engine = this.getScene().getEngine();
  46375. if (this._replacedViewport) {
  46376. engine.setViewport(this._replacedViewport);
  46377. this._replacedViewport = null;
  46378. }
  46379. engine.unBindFramebuffer(this._texture);
  46380. };
  46381. Object.defineProperty(MapTexture.prototype, "canRescale", {
  46382. get: function () {
  46383. return false;
  46384. },
  46385. enumerable: true,
  46386. configurable: true
  46387. });
  46388. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  46389. // Anyway, there's not much point to use this method for this kind of texture I guess
  46390. MapTexture.prototype.clone = function () {
  46391. return null;
  46392. };
  46393. return MapTexture;
  46394. }(BABYLON.Texture));
  46395. BABYLON.MapTexture = MapTexture;
  46396. })(BABYLON || (BABYLON = {}));
  46397. //# sourceMappingURL=babylon.mapTexture.js.map
  46398. var BABYLON;
  46399. (function (BABYLON) {
  46400. var ShaderMaterial = (function (_super) {
  46401. __extends(ShaderMaterial, _super);
  46402. function ShaderMaterial(name, scene, shaderPath, options) {
  46403. var _this = _super.call(this, name, scene) || this;
  46404. _this._textures = {};
  46405. _this._textureArrays = {};
  46406. _this._floats = {};
  46407. _this._floatsArrays = {};
  46408. _this._colors3 = {};
  46409. _this._colors4 = {};
  46410. _this._vectors2 = {};
  46411. _this._vectors3 = {};
  46412. _this._vectors4 = {};
  46413. _this._matrices = {};
  46414. _this._matrices3x3 = {};
  46415. _this._matrices2x2 = {};
  46416. _this._vectors3Arrays = {};
  46417. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46418. _this._shaderPath = shaderPath;
  46419. options.needAlphaBlending = options.needAlphaBlending || false;
  46420. options.needAlphaTesting = options.needAlphaTesting || false;
  46421. options.attributes = options.attributes || ["position", "normal", "uv"];
  46422. options.uniforms = options.uniforms || ["worldViewProjection"];
  46423. options.samplers = options.samplers || [];
  46424. options.defines = options.defines || [];
  46425. _this._options = options;
  46426. return _this;
  46427. }
  46428. ShaderMaterial.prototype.getClassName = function () {
  46429. return "ShaderMaterial";
  46430. };
  46431. ShaderMaterial.prototype.needAlphaBlending = function () {
  46432. return this._options.needAlphaBlending;
  46433. };
  46434. ShaderMaterial.prototype.needAlphaTesting = function () {
  46435. return this._options.needAlphaTesting;
  46436. };
  46437. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46438. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46439. this._options.uniforms.push(uniformName);
  46440. }
  46441. };
  46442. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46443. if (this._options.samplers.indexOf(name) === -1) {
  46444. this._options.samplers.push(name);
  46445. }
  46446. this._textures[name] = texture;
  46447. return this;
  46448. };
  46449. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46450. if (this._options.samplers.indexOf(name) === -1) {
  46451. this._options.samplers.push(name);
  46452. }
  46453. this._checkUniform(name);
  46454. this._textureArrays[name] = textures;
  46455. return this;
  46456. };
  46457. ShaderMaterial.prototype.setFloat = function (name, value) {
  46458. this._checkUniform(name);
  46459. this._floats[name] = value;
  46460. return this;
  46461. };
  46462. ShaderMaterial.prototype.setFloats = function (name, value) {
  46463. this._checkUniform(name);
  46464. this._floatsArrays[name] = value;
  46465. return this;
  46466. };
  46467. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46468. this._checkUniform(name);
  46469. this._colors3[name] = value;
  46470. return this;
  46471. };
  46472. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46473. this._checkUniform(name);
  46474. this._colors4[name] = value;
  46475. return this;
  46476. };
  46477. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46478. this._checkUniform(name);
  46479. this._vectors2[name] = value;
  46480. return this;
  46481. };
  46482. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46483. this._checkUniform(name);
  46484. this._vectors3[name] = value;
  46485. return this;
  46486. };
  46487. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46488. this._checkUniform(name);
  46489. this._vectors4[name] = value;
  46490. return this;
  46491. };
  46492. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46493. this._checkUniform(name);
  46494. this._matrices[name] = value;
  46495. return this;
  46496. };
  46497. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46498. this._checkUniform(name);
  46499. this._matrices3x3[name] = value;
  46500. return this;
  46501. };
  46502. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46503. this._checkUniform(name);
  46504. this._matrices2x2[name] = value;
  46505. return this;
  46506. };
  46507. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46508. this._checkUniform(name);
  46509. this._vectors3Arrays[name] = value;
  46510. return this;
  46511. };
  46512. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46513. if (!mesh) {
  46514. return true;
  46515. }
  46516. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46517. return false;
  46518. }
  46519. return false;
  46520. };
  46521. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46522. var scene = this.getScene();
  46523. var engine = scene.getEngine();
  46524. if (!this.checkReadyOnEveryCall) {
  46525. if (this._renderId === scene.getRenderId()) {
  46526. if (this._checkCache(scene, mesh, useInstances)) {
  46527. return true;
  46528. }
  46529. }
  46530. }
  46531. // Instances
  46532. var defines = [];
  46533. var fallbacks = new BABYLON.EffectFallbacks();
  46534. if (useInstances) {
  46535. defines.push("#define INSTANCES");
  46536. }
  46537. for (var index = 0; index < this._options.defines.length; index++) {
  46538. defines.push(this._options.defines[index]);
  46539. }
  46540. // Bones
  46541. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  46542. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46543. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46544. fallbacks.addCPUSkinningFallback(0, mesh);
  46545. }
  46546. // Textures
  46547. for (var name in this._textures) {
  46548. if (!this._textures[name].isReady()) {
  46549. return false;
  46550. }
  46551. }
  46552. // Alpha test
  46553. if (engine.getAlphaTesting()) {
  46554. defines.push("#define ALPHATEST");
  46555. }
  46556. var previousEffect = this._effect;
  46557. var join = defines.join("\n");
  46558. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  46559. if (!this._effect.isReady()) {
  46560. return false;
  46561. }
  46562. if (previousEffect !== this._effect) {
  46563. scene.resetCachedMaterial();
  46564. }
  46565. this._renderId = scene.getRenderId();
  46566. return true;
  46567. };
  46568. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46569. var scene = this.getScene();
  46570. if (this._options.uniforms.indexOf("world") !== -1) {
  46571. this._effect.setMatrix("world", world);
  46572. }
  46573. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46574. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46575. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46576. }
  46577. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46578. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46579. }
  46580. };
  46581. ShaderMaterial.prototype.bind = function (world, mesh) {
  46582. // Std values
  46583. this.bindOnlyWorldMatrix(world);
  46584. if (this.getScene().getCachedMaterial() !== this) {
  46585. if (this._options.uniforms.indexOf("view") !== -1) {
  46586. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46587. }
  46588. if (this._options.uniforms.indexOf("projection") !== -1) {
  46589. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46590. }
  46591. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46592. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46593. }
  46594. // Bones
  46595. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46596. var name;
  46597. // Texture
  46598. for (name in this._textures) {
  46599. this._effect.setTexture(name, this._textures[name]);
  46600. }
  46601. // Texture arrays
  46602. for (name in this._textureArrays) {
  46603. this._effect.setTextureArray(name, this._textureArrays[name]);
  46604. }
  46605. // Float
  46606. for (name in this._floats) {
  46607. this._effect.setFloat(name, this._floats[name]);
  46608. }
  46609. // Float s
  46610. for (name in this._floatsArrays) {
  46611. this._effect.setArray(name, this._floatsArrays[name]);
  46612. }
  46613. // Color3
  46614. for (name in this._colors3) {
  46615. this._effect.setColor3(name, this._colors3[name]);
  46616. }
  46617. // Color4
  46618. for (name in this._colors4) {
  46619. var color = this._colors4[name];
  46620. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46621. }
  46622. // Vector2
  46623. for (name in this._vectors2) {
  46624. this._effect.setVector2(name, this._vectors2[name]);
  46625. }
  46626. // Vector3
  46627. for (name in this._vectors3) {
  46628. this._effect.setVector3(name, this._vectors3[name]);
  46629. }
  46630. // Vector4
  46631. for (name in this._vectors4) {
  46632. this._effect.setVector4(name, this._vectors4[name]);
  46633. }
  46634. // Matrix
  46635. for (name in this._matrices) {
  46636. this._effect.setMatrix(name, this._matrices[name]);
  46637. }
  46638. // Matrix 3x3
  46639. for (name in this._matrices3x3) {
  46640. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46641. }
  46642. // Matrix 2x2
  46643. for (name in this._matrices2x2) {
  46644. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46645. }
  46646. // Vector3Array
  46647. for (name in this._vectors3Arrays) {
  46648. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46649. }
  46650. }
  46651. this._afterBind(mesh);
  46652. };
  46653. ShaderMaterial.prototype.clone = function (name) {
  46654. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46655. return newShaderMaterial;
  46656. };
  46657. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46658. if (forceDisposeTextures) {
  46659. var name;
  46660. for (name in this._textures) {
  46661. this._textures[name].dispose();
  46662. }
  46663. for (name in this._textureArrays) {
  46664. var array = this._textureArrays[name];
  46665. for (var index = 0; index < array.length; index++) {
  46666. array[index].dispose();
  46667. }
  46668. }
  46669. }
  46670. this._textures = {};
  46671. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46672. };
  46673. ShaderMaterial.prototype.serialize = function () {
  46674. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46675. serializationObject.customType = "BABYLON.ShaderMaterial";
  46676. serializationObject.options = this._options;
  46677. serializationObject.shaderPath = this._shaderPath;
  46678. var name;
  46679. // Texture
  46680. serializationObject.textures = {};
  46681. for (name in this._textures) {
  46682. serializationObject.textures[name] = this._textures[name].serialize();
  46683. }
  46684. // Texture arrays
  46685. serializationObject.textureArrays = {};
  46686. for (name in this._textureArrays) {
  46687. serializationObject.textureArrays[name] = [];
  46688. var array = this._textureArrays[name];
  46689. for (var index = 0; index < array.length; index++) {
  46690. serializationObject.textureArrays[name].push(array[index].serialize());
  46691. }
  46692. }
  46693. // Float
  46694. serializationObject.floats = {};
  46695. for (name in this._floats) {
  46696. serializationObject.floats[name] = this._floats[name];
  46697. }
  46698. // Float s
  46699. serializationObject.floatArrays = {};
  46700. for (name in this._floatsArrays) {
  46701. serializationObject.floatArrays[name] = this._floatsArrays[name];
  46702. }
  46703. // Color3
  46704. serializationObject.colors3 = {};
  46705. for (name in this._colors3) {
  46706. serializationObject.colors3[name] = this._colors3[name].asArray();
  46707. }
  46708. // Color4
  46709. serializationObject.colors4 = {};
  46710. for (name in this._colors4) {
  46711. serializationObject.colors4[name] = this._colors4[name].asArray();
  46712. }
  46713. // Vector2
  46714. serializationObject.vectors2 = {};
  46715. for (name in this._vectors2) {
  46716. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46717. }
  46718. // Vector3
  46719. serializationObject.vectors3 = {};
  46720. for (name in this._vectors3) {
  46721. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46722. }
  46723. // Vector4
  46724. serializationObject.vectors4 = {};
  46725. for (name in this._vectors4) {
  46726. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46727. }
  46728. // Matrix
  46729. serializationObject.matrices = {};
  46730. for (name in this._matrices) {
  46731. serializationObject.matrices[name] = this._matrices[name].asArray();
  46732. }
  46733. // Matrix 3x3
  46734. serializationObject.matrices3x3 = {};
  46735. for (name in this._matrices3x3) {
  46736. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46737. }
  46738. // Matrix 2x2
  46739. serializationObject.matrices2x2 = {};
  46740. for (name in this._matrices2x2) {
  46741. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46742. }
  46743. // Vector3Array
  46744. serializationObject.vectors3Arrays = {};
  46745. for (name in this._vectors3Arrays) {
  46746. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46747. }
  46748. return serializationObject;
  46749. };
  46750. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46751. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46752. var name;
  46753. // Texture
  46754. for (name in source.textures) {
  46755. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46756. }
  46757. // Texture arrays
  46758. for (name in source.textureArrays) {
  46759. var array = source.textureArrays[name];
  46760. var textureArray = new Array();
  46761. for (var index = 0; index < array.length; index++) {
  46762. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46763. }
  46764. material.setTextureArray(name, textureArray);
  46765. }
  46766. // Float
  46767. for (name in source.floats) {
  46768. material.setFloat(name, source.floats[name]);
  46769. }
  46770. // Float s
  46771. for (name in source.floatsArrays) {
  46772. material.setFloats(name, source.floatsArrays[name]);
  46773. }
  46774. // Color3
  46775. for (name in source.colors3) {
  46776. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46777. }
  46778. // Color4
  46779. for (name in source.colors4) {
  46780. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46781. }
  46782. // Vector2
  46783. for (name in source.vectors2) {
  46784. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46785. }
  46786. // Vector3
  46787. for (name in source.vectors3) {
  46788. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46789. }
  46790. // Vector4
  46791. for (name in source.vectors4) {
  46792. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46793. }
  46794. // Matrix
  46795. for (name in source.matrices) {
  46796. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46797. }
  46798. // Matrix 3x3
  46799. for (name in source.matrices3x3) {
  46800. material.setMatrix3x3(name, source.matrices3x3[name]);
  46801. }
  46802. // Matrix 2x2
  46803. for (name in source.matrices2x2) {
  46804. material.setMatrix2x2(name, source.matrices2x2[name]);
  46805. }
  46806. // Vector3Array
  46807. for (name in source.vectors3Arrays) {
  46808. material.setArray3(name, source.vectors3Arrays[name]);
  46809. }
  46810. return material;
  46811. };
  46812. return ShaderMaterial;
  46813. }(BABYLON.Material));
  46814. BABYLON.ShaderMaterial = ShaderMaterial;
  46815. })(BABYLON || (BABYLON = {}));
  46816. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46817. var BABYLON;
  46818. (function (BABYLON) {
  46819. var Internals;
  46820. (function (Internals) {
  46821. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  46822. // All values and structures referenced from:
  46823. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  46824. var DDS_MAGIC = 0x20534444;
  46825. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  46826. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  46827. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  46828. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  46829. function FourCCToInt32(value) {
  46830. return value.charCodeAt(0) +
  46831. (value.charCodeAt(1) << 8) +
  46832. (value.charCodeAt(2) << 16) +
  46833. (value.charCodeAt(3) << 24);
  46834. }
  46835. function Int32ToFourCC(value) {
  46836. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  46837. }
  46838. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  46839. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  46840. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  46841. var headerLengthInt = 31; // The header length in 32 bit ints
  46842. // Offsets into the header array
  46843. var off_magic = 0;
  46844. var off_size = 1;
  46845. var off_flags = 2;
  46846. var off_height = 3;
  46847. var off_width = 4;
  46848. var off_mipmapCount = 7;
  46849. var off_pfFlags = 20;
  46850. var off_pfFourCC = 21;
  46851. var off_RGBbpp = 22;
  46852. var off_RMask = 23;
  46853. var off_GMask = 24;
  46854. var off_BMask = 25;
  46855. var off_AMask = 26;
  46856. var off_caps1 = 27;
  46857. var off_caps2 = 28;
  46858. ;
  46859. var DDSTools = (function () {
  46860. function DDSTools() {
  46861. }
  46862. DDSTools.GetDDSInfo = function (arrayBuffer) {
  46863. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  46864. var mipmapCount = 1;
  46865. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  46866. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46867. }
  46868. return {
  46869. width: header[off_width],
  46870. height: header[off_height],
  46871. mipmapCount: mipmapCount,
  46872. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  46873. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  46874. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  46875. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  46876. };
  46877. };
  46878. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46879. var byteArray = new Uint8Array(dataLength);
  46880. var srcData = new Uint8Array(arrayBuffer);
  46881. var index = 0;
  46882. for (var y = height - 1; y >= 0; y--) {
  46883. for (var x = 0; x < width; x++) {
  46884. var srcPos = dataOffset + (x + y * width) * 4;
  46885. byteArray[index + 2] = srcData[srcPos];
  46886. byteArray[index + 1] = srcData[srcPos + 1];
  46887. byteArray[index] = srcData[srcPos + 2];
  46888. byteArray[index + 3] = srcData[srcPos + 3];
  46889. index += 4;
  46890. }
  46891. }
  46892. return byteArray;
  46893. };
  46894. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46895. var byteArray = new Uint8Array(dataLength);
  46896. var srcData = new Uint8Array(arrayBuffer);
  46897. var index = 0;
  46898. for (var y = height - 1; y >= 0; y--) {
  46899. for (var x = 0; x < width; x++) {
  46900. var srcPos = dataOffset + (x + y * width) * 3;
  46901. byteArray[index + 2] = srcData[srcPos];
  46902. byteArray[index + 1] = srcData[srcPos + 1];
  46903. byteArray[index] = srcData[srcPos + 2];
  46904. index += 3;
  46905. }
  46906. }
  46907. return byteArray;
  46908. };
  46909. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  46910. var byteArray = new Uint8Array(dataLength);
  46911. var srcData = new Uint8Array(arrayBuffer);
  46912. var index = 0;
  46913. for (var y = height - 1; y >= 0; y--) {
  46914. for (var x = 0; x < width; x++) {
  46915. var srcPos = dataOffset + (x + y * width);
  46916. byteArray[index] = srcData[srcPos];
  46917. index++;
  46918. }
  46919. }
  46920. return byteArray;
  46921. };
  46922. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  46923. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  46924. if (header[off_magic] != DDS_MAGIC) {
  46925. BABYLON.Tools.Error("Invalid magic number in DDS header");
  46926. return;
  46927. }
  46928. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  46929. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  46930. return;
  46931. }
  46932. if (info.isFourCC) {
  46933. fourCC = header[off_pfFourCC];
  46934. switch (fourCC) {
  46935. case FOURCC_DXT1:
  46936. blockBytes = 8;
  46937. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  46938. break;
  46939. case FOURCC_DXT3:
  46940. blockBytes = 16;
  46941. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  46942. break;
  46943. case FOURCC_DXT5:
  46944. blockBytes = 16;
  46945. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  46946. break;
  46947. default:
  46948. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  46949. return;
  46950. }
  46951. }
  46952. mipmapCount = 1;
  46953. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  46954. mipmapCount = Math.max(1, header[off_mipmapCount]);
  46955. }
  46956. var bpp = header[off_RGBbpp];
  46957. for (var face = 0; face < faces; face++) {
  46958. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  46959. width = header[off_width];
  46960. height = header[off_height];
  46961. dataOffset = header[off_size] + 4;
  46962. for (i = 0; i < mipmapCount; ++i) {
  46963. if (info.isRGB) {
  46964. if (bpp === 24) {
  46965. dataLength = width * height * 3;
  46966. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46967. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  46968. }
  46969. else {
  46970. dataLength = width * height * 4;
  46971. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46972. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  46973. }
  46974. }
  46975. else if (info.isLuminance) {
  46976. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  46977. var unpaddedRowSize = width;
  46978. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  46979. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  46980. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  46981. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  46982. }
  46983. else {
  46984. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  46985. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  46986. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  46987. }
  46988. dataOffset += dataLength;
  46989. width *= 0.5;
  46990. height *= 0.5;
  46991. width = Math.max(1.0, width);
  46992. height = Math.max(1.0, height);
  46993. }
  46994. }
  46995. };
  46996. return DDSTools;
  46997. }());
  46998. Internals.DDSTools = DDSTools;
  46999. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47000. })(BABYLON || (BABYLON = {}));
  47001. //# sourceMappingURL=babylon.dds.js.map
  47002. var BABYLON;
  47003. (function (BABYLON) {
  47004. var Internals;
  47005. (function (Internals) {
  47006. /**
  47007. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  47008. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  47009. */
  47010. var KhronosTextureContainer = (function () {
  47011. /**
  47012. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  47013. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  47014. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  47015. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  47016. */
  47017. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  47018. this.arrayBuffer = arrayBuffer;
  47019. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  47020. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  47021. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  47022. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  47023. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  47024. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  47025. BABYLON.Tools.Error("texture missing KTX identifier");
  47026. return;
  47027. }
  47028. // load the reset of the header in native 32 bit int
  47029. var header = new Int32Array(this.arrayBuffer, 12, 13);
  47030. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  47031. var oppositeEndianess = header[0] === 0x01020304;
  47032. // read all the header elements in order they exist in the file, without modification (sans endainness)
  47033. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  47034. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  47035. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  47036. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  47037. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  47038. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  47039. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  47040. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  47041. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  47042. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  47043. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  47044. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  47045. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  47046. if (this.glType !== 0) {
  47047. BABYLON.Tools.Error("only compressed formats currently supported");
  47048. return;
  47049. }
  47050. else {
  47051. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  47052. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  47053. }
  47054. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  47055. BABYLON.Tools.Error("only 2D textures currently supported");
  47056. return;
  47057. }
  47058. if (this.numberOfArrayElements !== 0) {
  47059. BABYLON.Tools.Error("texture arrays not currently supported");
  47060. return;
  47061. }
  47062. if (this.numberOfFaces !== facesExpected) {
  47063. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  47064. return;
  47065. }
  47066. // we now have a completely validated file, so could use existence of loadType as success
  47067. // would need to make this more elaborate & adjust checks above to support more than one load type
  47068. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  47069. }
  47070. // not as fast hardware based, but will probably never need to use
  47071. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  47072. return ((val & 0xFF) << 24)
  47073. | ((val & 0xFF00) << 8)
  47074. | ((val >> 8) & 0xFF00)
  47075. | ((val >> 24) & 0xFF);
  47076. };
  47077. /**
  47078. * It is assumed that the texture has already been created & is currently bound
  47079. */
  47080. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  47081. switch (this.loadType) {
  47082. case KhronosTextureContainer.COMPRESSED_2D:
  47083. this._upload2DCompressedLevels(gl, loadMipmaps);
  47084. break;
  47085. case KhronosTextureContainer.TEX_2D:
  47086. case KhronosTextureContainer.COMPRESSED_3D:
  47087. case KhronosTextureContainer.TEX_3D:
  47088. }
  47089. };
  47090. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  47091. // initialize width & height for level 1
  47092. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  47093. var width = this.pixelWidth;
  47094. var height = this.pixelHeight;
  47095. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  47096. for (var level = 0; level < mipmapCount; level++) {
  47097. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  47098. for (var face = 0; face < this.numberOfFaces; face++) {
  47099. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  47100. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  47101. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  47102. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  47103. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  47104. }
  47105. width = Math.max(1.0, width * 0.5);
  47106. height = Math.max(1.0, height * 0.5);
  47107. }
  47108. };
  47109. return KhronosTextureContainer;
  47110. }());
  47111. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  47112. // load types
  47113. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  47114. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  47115. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  47116. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  47117. Internals.KhronosTextureContainer = KhronosTextureContainer;
  47118. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47119. })(BABYLON || (BABYLON = {}));
  47120. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  47121. var BABYLON;
  47122. (function (BABYLON) {
  47123. var CannonJSPlugin = (function () {
  47124. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  47125. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  47126. if (iterations === void 0) { iterations = 10; }
  47127. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  47128. this.name = "CannonJSPlugin";
  47129. this._physicsMaterials = [];
  47130. this._fixedTimeStep = 1 / 60;
  47131. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47132. this._currentCollisionGroup = 2;
  47133. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  47134. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  47135. this._tmpPosition = BABYLON.Vector3.Zero();
  47136. this._tmpQuaternion = new BABYLON.Quaternion();
  47137. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  47138. this._tmpDeltaRotation = new BABYLON.Quaternion();
  47139. this._tmpUnityRotation = new BABYLON.Quaternion();
  47140. if (!this.isSupported()) {
  47141. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  47142. return;
  47143. }
  47144. this.world = new CANNON.World();
  47145. this.world.broadphase = new CANNON.NaiveBroadphase();
  47146. this.world.solver.iterations = iterations;
  47147. }
  47148. CannonJSPlugin.prototype.setGravity = function (gravity) {
  47149. this.world.gravity.copy(gravity);
  47150. };
  47151. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  47152. this._fixedTimeStep = timeStep;
  47153. };
  47154. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  47155. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  47156. };
  47157. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47158. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47159. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47160. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47161. };
  47162. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47163. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47164. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47165. impostor.physicsBody.applyForce(impulse, worldPoint);
  47166. };
  47167. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47168. //parent-child relationship. Does this impostor has a parent impostor?
  47169. if (impostor.parent) {
  47170. if (impostor.physicsBody) {
  47171. this.removePhysicsBody(impostor);
  47172. //TODO is that needed?
  47173. impostor.forceUpdate();
  47174. }
  47175. return;
  47176. }
  47177. //should a new body be created for this impostor?
  47178. if (impostor.isBodyInitRequired()) {
  47179. var shape = this._createShape(impostor);
  47180. //unregister events, if body is being changed
  47181. var oldBody = impostor.physicsBody;
  47182. if (oldBody) {
  47183. this.removePhysicsBody(impostor);
  47184. }
  47185. //create the body and material
  47186. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  47187. var bodyCreationObject = {
  47188. mass: impostor.getParam("mass"),
  47189. material: material
  47190. };
  47191. // A simple extend, in case native options were used.
  47192. var nativeOptions = impostor.getParam("nativeOptions");
  47193. for (var key in nativeOptions) {
  47194. if (nativeOptions.hasOwnProperty(key)) {
  47195. bodyCreationObject[key] = nativeOptions[key];
  47196. }
  47197. }
  47198. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  47199. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  47200. this.world.addEventListener("preStep", impostor.beforeStep);
  47201. this.world.addEventListener("postStep", impostor.afterStep);
  47202. impostor.physicsBody.addShape(shape);
  47203. this.world.add(impostor.physicsBody);
  47204. //try to keep the body moving in the right direction by taking old properties.
  47205. //Should be tested!
  47206. if (oldBody) {
  47207. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  47208. impostor.physicsBody[param].copy(oldBody[param]);
  47209. });
  47210. }
  47211. this._processChildMeshes(impostor);
  47212. }
  47213. //now update the body's transformation
  47214. this._updatePhysicsBodyTransformation(impostor);
  47215. };
  47216. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  47217. var _this = this;
  47218. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  47219. if (meshChildren.length) {
  47220. var processMesh = function (localPosition, mesh) {
  47221. var childImpostor = mesh.getPhysicsImpostor();
  47222. if (childImpostor) {
  47223. var parent = childImpostor.parent;
  47224. if (parent !== mainImpostor) {
  47225. var localPosition = mesh.position;
  47226. if (childImpostor.physicsBody) {
  47227. _this.removePhysicsBody(childImpostor);
  47228. childImpostor.physicsBody = null;
  47229. }
  47230. childImpostor.parent = mainImpostor;
  47231. childImpostor.resetUpdateFlags();
  47232. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  47233. //Add the mass of the children.
  47234. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  47235. }
  47236. }
  47237. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  47238. };
  47239. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  47240. }
  47241. };
  47242. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47243. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  47244. this.world.removeEventListener("preStep", impostor.beforeStep);
  47245. this.world.removeEventListener("postStep", impostor.afterStep);
  47246. this.world.remove(impostor.physicsBody);
  47247. };
  47248. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47249. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47250. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47251. if (!mainBody || !connectedBody) {
  47252. return;
  47253. }
  47254. var constraint;
  47255. var jointData = impostorJoint.joint.jointData;
  47256. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47257. var constraintData = {
  47258. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  47259. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  47260. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  47261. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  47262. maxForce: jointData.nativeParams.maxForce,
  47263. collideConnected: !!jointData.collision
  47264. };
  47265. switch (impostorJoint.joint.type) {
  47266. case BABYLON.PhysicsJoint.HingeJoint:
  47267. case BABYLON.PhysicsJoint.Hinge2Joint:
  47268. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  47269. break;
  47270. case BABYLON.PhysicsJoint.DistanceJoint:
  47271. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  47272. break;
  47273. case BABYLON.PhysicsJoint.SpringJoint:
  47274. var springData = jointData;
  47275. constraint = new CANNON.Spring(mainBody, connectedBody, {
  47276. restLength: springData.length,
  47277. stiffness: springData.stiffness,
  47278. damping: springData.damping,
  47279. localAnchorA: constraintData.pivotA,
  47280. localAnchorB: constraintData.pivotB
  47281. });
  47282. break;
  47283. case BABYLON.PhysicsJoint.LockJoint:
  47284. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  47285. break;
  47286. case BABYLON.PhysicsJoint.PointToPointJoint:
  47287. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47288. default:
  47289. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  47290. break;
  47291. }
  47292. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  47293. constraint.collideConnected = !!jointData.collision;
  47294. impostorJoint.joint.physicsJoint = constraint;
  47295. //don't add spring as constraint, as it is not one.
  47296. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  47297. this.world.addConstraint(constraint);
  47298. }
  47299. else {
  47300. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  47301. constraint.applyForce();
  47302. });
  47303. }
  47304. };
  47305. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47306. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  47307. };
  47308. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  47309. var index;
  47310. var mat;
  47311. for (index = 0; index < this._physicsMaterials.length; index++) {
  47312. mat = this._physicsMaterials[index];
  47313. if (mat.friction === friction && mat.restitution === restitution) {
  47314. return mat;
  47315. }
  47316. }
  47317. var currentMat = new CANNON.Material(name);
  47318. currentMat.friction = friction;
  47319. currentMat.restitution = restitution;
  47320. this._physicsMaterials.push(currentMat);
  47321. return currentMat;
  47322. };
  47323. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  47324. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  47325. };
  47326. CannonJSPlugin.prototype._createShape = function (impostor) {
  47327. var object = impostor.object;
  47328. var returnValue;
  47329. var extendSize = impostor.getObjectExtendSize();
  47330. switch (impostor.type) {
  47331. case BABYLON.PhysicsImpostor.SphereImpostor:
  47332. var radiusX = extendSize.x;
  47333. var radiusY = extendSize.y;
  47334. var radiusZ = extendSize.z;
  47335. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  47336. break;
  47337. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  47338. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47339. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  47340. break;
  47341. case BABYLON.PhysicsImpostor.BoxImpostor:
  47342. var box = extendSize.scale(0.5);
  47343. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  47344. break;
  47345. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47346. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  47347. returnValue = new CANNON.Plane();
  47348. break;
  47349. case BABYLON.PhysicsImpostor.MeshImpostor:
  47350. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  47351. var rawFaces = object.getIndices ? object.getIndices() : [];
  47352. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  47353. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  47354. break;
  47355. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  47356. returnValue = this._createHeightmap(object);
  47357. break;
  47358. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47359. returnValue = new CANNON.Particle();
  47360. break;
  47361. }
  47362. return returnValue;
  47363. };
  47364. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  47365. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47366. var matrix = [];
  47367. //For now pointDepth will not be used and will be automatically calculated.
  47368. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  47369. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  47370. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  47371. var elementSize = dim * 2 / arraySize;
  47372. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  47373. for (var i = 0; i < pos.length; i = i + 3) {
  47374. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  47375. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  47376. var y = pos[i + 1] + minY;
  47377. if (!matrix[x]) {
  47378. matrix[x] = [];
  47379. }
  47380. if (!matrix[x][z]) {
  47381. matrix[x][z] = y;
  47382. }
  47383. matrix[x][z] = Math.max(y, matrix[x][z]);
  47384. }
  47385. for (var x = 0; x <= arraySize; ++x) {
  47386. if (!matrix[x]) {
  47387. var loc = 1;
  47388. while (!matrix[(x + loc) % arraySize]) {
  47389. loc++;
  47390. }
  47391. matrix[x] = matrix[(x + loc) % arraySize].slice();
  47392. //console.log("missing x", x);
  47393. }
  47394. for (var z = 0; z <= arraySize; ++z) {
  47395. if (!matrix[x][z]) {
  47396. var loc = 1;
  47397. var newValue;
  47398. while (newValue === undefined) {
  47399. newValue = matrix[x][(z + loc++) % arraySize];
  47400. }
  47401. matrix[x][z] = newValue;
  47402. }
  47403. }
  47404. }
  47405. var shape = new CANNON.Heightfield(matrix, {
  47406. elementSize: elementSize
  47407. });
  47408. //For future reference, needed for body transformation
  47409. shape.minY = minY;
  47410. return shape;
  47411. };
  47412. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  47413. var object = impostor.object;
  47414. //make sure it is updated...
  47415. object.computeWorldMatrix && object.computeWorldMatrix(true);
  47416. // The delta between the mesh position and the mesh bounding box center
  47417. var center = impostor.getObjectCenter();
  47418. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  47419. this._tmpPosition.copyFrom(center);
  47420. var quaternion = object.rotationQuaternion;
  47421. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  47422. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  47423. //-90 DEG in X, precalculated
  47424. quaternion = quaternion.multiply(this._minus90X);
  47425. //Invert! (Precalculated, 90 deg in X)
  47426. //No need to clone. this will never change.
  47427. impostor.setDeltaRotation(this._plus90X);
  47428. }
  47429. //If it is a heightfield, if should be centered.
  47430. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  47431. var mesh = object;
  47432. //calculate the correct body position:
  47433. var rotationQuaternion = mesh.rotationQuaternion;
  47434. mesh.rotationQuaternion = this._tmpUnityRotation;
  47435. mesh.computeWorldMatrix(true);
  47436. //get original center with no rotation
  47437. var c = center.clone();
  47438. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  47439. //rotation is back
  47440. mesh.rotationQuaternion = rotationQuaternion;
  47441. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  47442. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  47443. mesh.setPivotMatrix(p);
  47444. mesh.computeWorldMatrix(true);
  47445. //calculate the translation
  47446. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  47447. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  47448. //add it inverted to the delta
  47449. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  47450. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  47451. mesh.setPivotMatrix(oldPivot);
  47452. mesh.computeWorldMatrix(true);
  47453. }
  47454. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  47455. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  47456. this._tmpPosition.copyFrom(object.position);
  47457. }
  47458. impostor.setDeltaPosition(this._tmpDeltaPosition);
  47459. //Now update the impostor object
  47460. impostor.physicsBody.position.copy(this._tmpPosition);
  47461. impostor.physicsBody.quaternion.copy(quaternion);
  47462. };
  47463. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47464. impostor.object.position.copyFrom(impostor.physicsBody.position);
  47465. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  47466. };
  47467. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47468. impostor.physicsBody.position.copy(newPosition);
  47469. impostor.physicsBody.quaternion.copy(newRotation);
  47470. };
  47471. CannonJSPlugin.prototype.isSupported = function () {
  47472. return window.CANNON !== undefined;
  47473. };
  47474. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47475. impostor.physicsBody.velocity.copy(velocity);
  47476. };
  47477. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47478. impostor.physicsBody.angularVelocity.copy(velocity);
  47479. };
  47480. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47481. var v = impostor.physicsBody.velocity;
  47482. if (!v)
  47483. return null;
  47484. return new BABYLON.Vector3(v.x, v.y, v.z);
  47485. };
  47486. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47487. var v = impostor.physicsBody.angularVelocity;
  47488. if (!v)
  47489. return null;
  47490. return new BABYLON.Vector3(v.x, v.y, v.z);
  47491. };
  47492. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47493. impostor.physicsBody.mass = mass;
  47494. impostor.physicsBody.updateMassProperties();
  47495. };
  47496. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  47497. impostor.physicsBody.sleep();
  47498. };
  47499. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  47500. impostor.physicsBody.wakeUp();
  47501. };
  47502. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47503. joint.physicsJoint.distance = maxDistance;
  47504. };
  47505. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  47506. if (!motorIndex) {
  47507. joint.physicsJoint.enableMotor();
  47508. }
  47509. };
  47510. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  47511. if (!motorIndex) {
  47512. joint.physicsJoint.disableMotor();
  47513. }
  47514. };
  47515. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47516. if (!motorIndex) {
  47517. joint.physicsJoint.enableMotor();
  47518. joint.physicsJoint.setMotorSpeed(speed);
  47519. if (maxForce) {
  47520. this.setLimit(joint, maxForce);
  47521. }
  47522. }
  47523. };
  47524. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  47525. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  47526. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  47527. };
  47528. CannonJSPlugin.prototype.dispose = function () {
  47529. //nothing to do, actually.
  47530. };
  47531. return CannonJSPlugin;
  47532. }());
  47533. BABYLON.CannonJSPlugin = CannonJSPlugin;
  47534. })(BABYLON || (BABYLON = {}));
  47535. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  47536. var BABYLON;
  47537. (function (BABYLON) {
  47538. var OimoJSPlugin = (function () {
  47539. function OimoJSPlugin(iterations) {
  47540. this.name = "OimoJSPlugin";
  47541. this._tmpImpostorsArray = [];
  47542. this._tmpPositionVector = BABYLON.Vector3.Zero();
  47543. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  47544. this.world.worldscale(1);
  47545. this.world.clear();
  47546. //making sure no stats are calculated
  47547. this.world.isNoStat = true;
  47548. }
  47549. OimoJSPlugin.prototype.setGravity = function (gravity) {
  47550. this.world.gravity.copy(gravity);
  47551. };
  47552. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  47553. this.world.timeStep = timeStep;
  47554. };
  47555. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  47556. var _this = this;
  47557. impostors.forEach(function (impostor) {
  47558. impostor.beforeStep();
  47559. });
  47560. this.world.step();
  47561. impostors.forEach(function (impostor) {
  47562. impostor.afterStep();
  47563. //update the ordered impostors array
  47564. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  47565. });
  47566. //check for collisions
  47567. var contact = this.world.contacts;
  47568. while (contact !== null) {
  47569. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  47570. contact = contact.next;
  47571. continue;
  47572. }
  47573. //is this body colliding with any other? get the impostor
  47574. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  47575. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  47576. if (!mainImpostor || !collidingImpostor) {
  47577. contact = contact.next;
  47578. continue;
  47579. }
  47580. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  47581. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  47582. contact = contact.next;
  47583. }
  47584. };
  47585. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47586. var mass = impostor.physicsBody.massInfo.mass;
  47587. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  47588. };
  47589. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47590. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  47591. this.applyImpulse(impostor, force, contactPoint);
  47592. };
  47593. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47594. var _this = this;
  47595. //parent-child relationship. Does this impostor has a parent impostor?
  47596. if (impostor.parent) {
  47597. if (impostor.physicsBody) {
  47598. this.removePhysicsBody(impostor);
  47599. //TODO is that needed?
  47600. impostor.forceUpdate();
  47601. }
  47602. return;
  47603. }
  47604. if (impostor.isBodyInitRequired()) {
  47605. var bodyConfig = {
  47606. name: impostor.uniqueId,
  47607. //Oimo must have mass, also for static objects.
  47608. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  47609. size: [],
  47610. type: [],
  47611. pos: [],
  47612. rot: [],
  47613. move: impostor.getParam("mass") !== 0,
  47614. //Supporting older versions of Oimo
  47615. world: this.world
  47616. };
  47617. var impostors = [impostor];
  47618. var addToArray = function (parent) {
  47619. if (!parent.getChildMeshes)
  47620. return;
  47621. parent.getChildMeshes().forEach(function (m) {
  47622. if (m.physicsImpostor) {
  47623. impostors.push(m.physicsImpostor);
  47624. m.physicsImpostor._init();
  47625. }
  47626. });
  47627. };
  47628. addToArray(impostor.object);
  47629. var checkWithEpsilon_1 = function (value) {
  47630. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  47631. };
  47632. impostors.forEach(function (i) {
  47633. //get the correct bounding box
  47634. var oldQuaternion = i.object.rotationQuaternion;
  47635. var rot = new OIMO.Euler().setFromQuaternion({
  47636. x: impostor.object.rotationQuaternion.x,
  47637. y: impostor.object.rotationQuaternion.y,
  47638. z: impostor.object.rotationQuaternion.z,
  47639. s: impostor.object.rotationQuaternion.w
  47640. });
  47641. var extendSize = i.getObjectExtendSize();
  47642. if (i === impostor) {
  47643. var center = impostor.getObjectCenter();
  47644. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  47645. //Can also use Array.prototype.push.apply
  47646. bodyConfig.pos.push(center.x);
  47647. bodyConfig.pos.push(center.y);
  47648. bodyConfig.pos.push(center.z);
  47649. //tmp solution
  47650. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  47651. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  47652. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  47653. }
  47654. else {
  47655. bodyConfig.pos.push(i.object.position.x);
  47656. bodyConfig.pos.push(i.object.position.y);
  47657. bodyConfig.pos.push(i.object.position.z);
  47658. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  47659. bodyConfig.rot.push(0);
  47660. bodyConfig.rot.push(0);
  47661. bodyConfig.rot.push(0);
  47662. }
  47663. // register mesh
  47664. switch (i.type) {
  47665. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47666. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  47667. case BABYLON.PhysicsImpostor.SphereImpostor:
  47668. var radiusX = extendSize.x;
  47669. var radiusY = extendSize.y;
  47670. var radiusZ = extendSize.z;
  47671. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  47672. bodyConfig.type.push('sphere');
  47673. //due to the way oimo works with compounds, add 3 times
  47674. bodyConfig.size.push(size);
  47675. bodyConfig.size.push(size);
  47676. bodyConfig.size.push(size);
  47677. break;
  47678. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47679. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  47680. var sizeY = checkWithEpsilon_1(extendSize.y);
  47681. bodyConfig.type.push('cylinder');
  47682. bodyConfig.size.push(sizeX);
  47683. bodyConfig.size.push(sizeY);
  47684. //due to the way oimo works with compounds, add one more value.
  47685. bodyConfig.size.push(sizeY);
  47686. break;
  47687. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47688. case BABYLON.PhysicsImpostor.BoxImpostor:
  47689. default:
  47690. var sizeX = checkWithEpsilon_1(extendSize.x);
  47691. var sizeY = checkWithEpsilon_1(extendSize.y);
  47692. var sizeZ = checkWithEpsilon_1(extendSize.z);
  47693. bodyConfig.type.push('box');
  47694. bodyConfig.size.push(sizeX);
  47695. bodyConfig.size.push(sizeY);
  47696. bodyConfig.size.push(sizeZ);
  47697. break;
  47698. }
  47699. //actually not needed, but hey...
  47700. i.object.rotationQuaternion = oldQuaternion;
  47701. });
  47702. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  47703. }
  47704. else {
  47705. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  47706. }
  47707. impostor.setDeltaPosition(this._tmpPositionVector);
  47708. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  47709. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  47710. };
  47711. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47712. //impostor.physicsBody.dispose();
  47713. //Same as : (older oimo versions)
  47714. this.world.removeRigidBody(impostor.physicsBody);
  47715. };
  47716. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47717. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47718. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47719. if (!mainBody || !connectedBody) {
  47720. return;
  47721. }
  47722. var jointData = impostorJoint.joint.jointData;
  47723. var options = jointData.nativeParams || {};
  47724. var type;
  47725. var nativeJointData = {
  47726. body1: mainBody,
  47727. body2: connectedBody,
  47728. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  47729. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  47730. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  47731. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  47732. min: options.min,
  47733. max: options.max,
  47734. collision: options.collision || jointData.collision,
  47735. spring: options.spring,
  47736. //supporting older version of Oimo
  47737. world: this.world
  47738. };
  47739. switch (impostorJoint.joint.type) {
  47740. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47741. type = "jointBall";
  47742. break;
  47743. case BABYLON.PhysicsJoint.SpringJoint:
  47744. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  47745. var springData = jointData;
  47746. nativeJointData.min = springData.length || nativeJointData.min;
  47747. //Max should also be set, just make sure it is at least min
  47748. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  47749. case BABYLON.PhysicsJoint.DistanceJoint:
  47750. type = "jointDistance";
  47751. nativeJointData.max = jointData.maxDistance;
  47752. break;
  47753. case BABYLON.PhysicsJoint.PrismaticJoint:
  47754. type = "jointPrisme";
  47755. break;
  47756. case BABYLON.PhysicsJoint.SliderJoint:
  47757. type = "jointSlide";
  47758. break;
  47759. case BABYLON.PhysicsJoint.WheelJoint:
  47760. type = "jointWheel";
  47761. break;
  47762. case BABYLON.PhysicsJoint.HingeJoint:
  47763. default:
  47764. type = "jointHinge";
  47765. break;
  47766. }
  47767. nativeJointData.type = type;
  47768. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  47769. };
  47770. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47771. //Bug in Oimo prevents us from disposing a joint in the playground
  47772. //joint.joint.physicsJoint.dispose();
  47773. //So we will bruteforce it!
  47774. try {
  47775. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  47776. }
  47777. catch (e) {
  47778. BABYLON.Tools.Warn(e);
  47779. }
  47780. };
  47781. OimoJSPlugin.prototype.isSupported = function () {
  47782. return OIMO !== undefined;
  47783. };
  47784. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47785. if (!impostor.physicsBody.sleeping) {
  47786. //TODO check that
  47787. if (impostor.physicsBody.shapes.next) {
  47788. var parentShape = this._getLastShape(impostor.physicsBody);
  47789. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  47790. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  47791. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  47792. }
  47793. else {
  47794. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  47795. }
  47796. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  47797. impostor.object.rotationQuaternion.normalize();
  47798. }
  47799. };
  47800. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47801. var body = impostor.physicsBody;
  47802. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  47803. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  47804. body.syncShapes();
  47805. body.awake();
  47806. };
  47807. OimoJSPlugin.prototype._getLastShape = function (body) {
  47808. var lastShape = body.shapes;
  47809. while (lastShape.next) {
  47810. lastShape = lastShape.next;
  47811. }
  47812. return lastShape;
  47813. };
  47814. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47815. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  47816. };
  47817. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47818. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  47819. };
  47820. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  47821. var v = impostor.physicsBody.linearVelocity;
  47822. if (!v)
  47823. return null;
  47824. return new BABYLON.Vector3(v.x, v.y, v.z);
  47825. };
  47826. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  47827. var v = impostor.physicsBody.angularVelocity;
  47828. if (!v)
  47829. return null;
  47830. return new BABYLON.Vector3(v.x, v.y, v.z);
  47831. };
  47832. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  47833. var staticBody = mass === 0;
  47834. //this will actually set the body's density and not its mass.
  47835. //But this is how oimo treats the mass variable.
  47836. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  47837. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  47838. };
  47839. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  47840. impostor.physicsBody.sleep();
  47841. };
  47842. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  47843. impostor.physicsBody.awake();
  47844. };
  47845. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  47846. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  47847. if (minDistance !== void 0) {
  47848. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  47849. }
  47850. };
  47851. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  47852. //TODO separate rotational and transational motors.
  47853. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47854. if (motor) {
  47855. motor.setMotor(speed, maxForce);
  47856. }
  47857. };
  47858. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  47859. //TODO separate rotational and transational motors.
  47860. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  47861. if (motor) {
  47862. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  47863. }
  47864. };
  47865. OimoJSPlugin.prototype.dispose = function () {
  47866. this.world.clear();
  47867. };
  47868. return OimoJSPlugin;
  47869. }());
  47870. BABYLON.OimoJSPlugin = OimoJSPlugin;
  47871. })(BABYLON || (BABYLON = {}));
  47872. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  47873. var BABYLON;
  47874. (function (BABYLON) {
  47875. var DisplayPassPostProcess = (function (_super) {
  47876. __extends(DisplayPassPostProcess, _super);
  47877. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  47878. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  47879. }
  47880. return DisplayPassPostProcess;
  47881. }(BABYLON.PostProcess));
  47882. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  47883. })(BABYLON || (BABYLON = {}));
  47884. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  47885. var BABYLON;
  47886. (function (BABYLON) {
  47887. var SimplificationSettings = (function () {
  47888. function SimplificationSettings(quality, distance, optimizeMesh) {
  47889. this.quality = quality;
  47890. this.distance = distance;
  47891. this.optimizeMesh = optimizeMesh;
  47892. }
  47893. return SimplificationSettings;
  47894. }());
  47895. BABYLON.SimplificationSettings = SimplificationSettings;
  47896. var SimplificationQueue = (function () {
  47897. function SimplificationQueue() {
  47898. this.running = false;
  47899. this._simplificationArray = [];
  47900. }
  47901. SimplificationQueue.prototype.addTask = function (task) {
  47902. this._simplificationArray.push(task);
  47903. };
  47904. SimplificationQueue.prototype.executeNext = function () {
  47905. var task = this._simplificationArray.pop();
  47906. if (task) {
  47907. this.running = true;
  47908. this.runSimplification(task);
  47909. }
  47910. else {
  47911. this.running = false;
  47912. }
  47913. };
  47914. SimplificationQueue.prototype.runSimplification = function (task) {
  47915. var _this = this;
  47916. if (task.parallelProcessing) {
  47917. //parallel simplifier
  47918. task.settings.forEach(function (setting) {
  47919. var simplifier = _this.getSimplifier(task);
  47920. simplifier.simplify(setting, function (newMesh) {
  47921. task.mesh.addLODLevel(setting.distance, newMesh);
  47922. newMesh.isVisible = true;
  47923. //check if it is the last
  47924. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  47925. //all done, run the success callback.
  47926. task.successCallback();
  47927. }
  47928. _this.executeNext();
  47929. });
  47930. });
  47931. }
  47932. else {
  47933. //single simplifier.
  47934. var simplifier = this.getSimplifier(task);
  47935. var runDecimation = function (setting, callback) {
  47936. simplifier.simplify(setting, function (newMesh) {
  47937. task.mesh.addLODLevel(setting.distance, newMesh);
  47938. newMesh.isVisible = true;
  47939. //run the next quality level
  47940. callback();
  47941. });
  47942. };
  47943. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  47944. runDecimation(task.settings[loop.index], function () {
  47945. loop.executeNext();
  47946. });
  47947. }, function () {
  47948. //execution ended, run the success callback.
  47949. if (task.successCallback) {
  47950. task.successCallback();
  47951. }
  47952. _this.executeNext();
  47953. });
  47954. }
  47955. };
  47956. SimplificationQueue.prototype.getSimplifier = function (task) {
  47957. switch (task.simplificationType) {
  47958. case SimplificationType.QUADRATIC:
  47959. default:
  47960. return new QuadraticErrorSimplification(task.mesh);
  47961. }
  47962. };
  47963. return SimplificationQueue;
  47964. }());
  47965. BABYLON.SimplificationQueue = SimplificationQueue;
  47966. /**
  47967. * The implemented types of simplification.
  47968. * At the moment only Quadratic Error Decimation is implemented.
  47969. */
  47970. var SimplificationType;
  47971. (function (SimplificationType) {
  47972. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  47973. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  47974. var DecimationTriangle = (function () {
  47975. function DecimationTriangle(vertices) {
  47976. this.vertices = vertices;
  47977. this.error = new Array(4);
  47978. this.deleted = false;
  47979. this.isDirty = false;
  47980. this.deletePending = false;
  47981. this.borderFactor = 0;
  47982. }
  47983. return DecimationTriangle;
  47984. }());
  47985. BABYLON.DecimationTriangle = DecimationTriangle;
  47986. var DecimationVertex = (function () {
  47987. function DecimationVertex(position, id) {
  47988. this.position = position;
  47989. this.id = id;
  47990. this.isBorder = true;
  47991. this.q = new QuadraticMatrix();
  47992. this.triangleCount = 0;
  47993. this.triangleStart = 0;
  47994. this.originalOffsets = [];
  47995. }
  47996. DecimationVertex.prototype.updatePosition = function (newPosition) {
  47997. this.position.copyFrom(newPosition);
  47998. };
  47999. return DecimationVertex;
  48000. }());
  48001. BABYLON.DecimationVertex = DecimationVertex;
  48002. var QuadraticMatrix = (function () {
  48003. function QuadraticMatrix(data) {
  48004. this.data = new Array(10);
  48005. for (var i = 0; i < 10; ++i) {
  48006. if (data && data[i]) {
  48007. this.data[i] = data[i];
  48008. }
  48009. else {
  48010. this.data[i] = 0;
  48011. }
  48012. }
  48013. }
  48014. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  48015. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  48016. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  48017. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  48018. return det;
  48019. };
  48020. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  48021. for (var i = 0; i < 10; ++i) {
  48022. this.data[i] += matrix.data[i];
  48023. }
  48024. };
  48025. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  48026. for (var i = 0; i < 10; ++i) {
  48027. this.data[i] += data[i];
  48028. }
  48029. };
  48030. QuadraticMatrix.prototype.add = function (matrix) {
  48031. var m = new QuadraticMatrix();
  48032. for (var i = 0; i < 10; ++i) {
  48033. m.data[i] = this.data[i] + matrix.data[i];
  48034. }
  48035. return m;
  48036. };
  48037. QuadraticMatrix.FromData = function (a, b, c, d) {
  48038. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  48039. };
  48040. //returning an array to avoid garbage collection
  48041. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  48042. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  48043. };
  48044. return QuadraticMatrix;
  48045. }());
  48046. BABYLON.QuadraticMatrix = QuadraticMatrix;
  48047. var Reference = (function () {
  48048. function Reference(vertexId, triangleId) {
  48049. this.vertexId = vertexId;
  48050. this.triangleId = triangleId;
  48051. }
  48052. return Reference;
  48053. }());
  48054. BABYLON.Reference = Reference;
  48055. /**
  48056. * An implementation of the Quadratic Error simplification algorithm.
  48057. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  48058. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  48059. * @author RaananW
  48060. */
  48061. var QuadraticErrorSimplification = (function () {
  48062. function QuadraticErrorSimplification(_mesh) {
  48063. this._mesh = _mesh;
  48064. this.initialized = false;
  48065. this.syncIterations = 5000;
  48066. this.aggressiveness = 7;
  48067. this.decimationIterations = 100;
  48068. this.boundingBoxEpsilon = BABYLON.Epsilon;
  48069. }
  48070. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  48071. var _this = this;
  48072. this.initDecimatedMesh();
  48073. //iterating through the submeshes array, one after the other.
  48074. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  48075. _this.initWithMesh(loop.index, function () {
  48076. _this.runDecimation(settings, loop.index, function () {
  48077. loop.executeNext();
  48078. });
  48079. }, settings.optimizeMesh);
  48080. }, function () {
  48081. setTimeout(function () {
  48082. successCallback(_this._reconstructedMesh);
  48083. }, 0);
  48084. });
  48085. };
  48086. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  48087. var _this = this;
  48088. var gCount = 0;
  48089. triangle.vertices.forEach(function (vertex) {
  48090. var count = 0;
  48091. var vPos = vertex.position;
  48092. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  48093. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  48094. ++count;
  48095. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  48096. ++count;
  48097. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  48098. ++count;
  48099. if (count > 1) {
  48100. ++gCount;
  48101. }
  48102. ;
  48103. });
  48104. if (gCount > 1) {
  48105. console.log(triangle, gCount);
  48106. }
  48107. return gCount > 1;
  48108. };
  48109. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  48110. var _this = this;
  48111. var targetCount = ~~(this.triangles.length * settings.quality);
  48112. var deletedTriangles = 0;
  48113. var triangleCount = this.triangles.length;
  48114. var iterationFunction = function (iteration, callback) {
  48115. setTimeout(function () {
  48116. if (iteration % 5 === 0) {
  48117. _this.updateMesh(iteration === 0);
  48118. }
  48119. for (var i = 0; i < _this.triangles.length; ++i) {
  48120. _this.triangles[i].isDirty = false;
  48121. }
  48122. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  48123. var trianglesIterator = function (i) {
  48124. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  48125. var t = _this.triangles[tIdx];
  48126. if (!t)
  48127. return;
  48128. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  48129. return;
  48130. }
  48131. for (var j = 0; j < 3; ++j) {
  48132. if (t.error[j] < threshold) {
  48133. var deleted0 = [];
  48134. var deleted1 = [];
  48135. var v0 = t.vertices[j];
  48136. var v1 = t.vertices[(j + 1) % 3];
  48137. if (v0.isBorder || v1.isBorder)
  48138. continue;
  48139. var p = BABYLON.Vector3.Zero();
  48140. var n = BABYLON.Vector3.Zero();
  48141. var uv = BABYLON.Vector2.Zero();
  48142. var color = new BABYLON.Color4(0, 0, 0, 1);
  48143. _this.calculateError(v0, v1, p, n, uv, color);
  48144. var delTr = [];
  48145. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  48146. continue;
  48147. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  48148. continue;
  48149. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  48150. continue;
  48151. var uniqueArray = [];
  48152. delTr.forEach(function (deletedT) {
  48153. if (uniqueArray.indexOf(deletedT) === -1) {
  48154. deletedT.deletePending = true;
  48155. uniqueArray.push(deletedT);
  48156. }
  48157. });
  48158. if (uniqueArray.length % 2 !== 0) {
  48159. continue;
  48160. }
  48161. v0.q = v1.q.add(v0.q);
  48162. v0.updatePosition(p);
  48163. var tStart = _this.references.length;
  48164. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  48165. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  48166. var tCount = _this.references.length - tStart;
  48167. if (tCount <= v0.triangleCount) {
  48168. if (tCount) {
  48169. for (var c = 0; c < tCount; c++) {
  48170. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  48171. }
  48172. }
  48173. }
  48174. else {
  48175. v0.triangleStart = tStart;
  48176. }
  48177. v0.triangleCount = tCount;
  48178. break;
  48179. }
  48180. }
  48181. };
  48182. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  48183. }, 0);
  48184. };
  48185. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  48186. if (triangleCount - deletedTriangles <= targetCount)
  48187. loop.breakLoop();
  48188. else {
  48189. iterationFunction(loop.index, function () {
  48190. loop.executeNext();
  48191. });
  48192. }
  48193. }, function () {
  48194. setTimeout(function () {
  48195. //reconstruct this part of the mesh
  48196. _this.reconstructMesh(submeshIndex);
  48197. successCallback();
  48198. }, 0);
  48199. });
  48200. };
  48201. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  48202. var _this = this;
  48203. this.vertices = [];
  48204. this.triangles = [];
  48205. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48206. var indices = this._mesh.getIndices();
  48207. var submesh = this._mesh.subMeshes[submeshIndex];
  48208. var findInVertices = function (positionToSearch) {
  48209. if (optimizeMesh) {
  48210. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  48211. if (_this.vertices[ii].position.equals(positionToSearch)) {
  48212. return _this.vertices[ii];
  48213. }
  48214. }
  48215. }
  48216. return null;
  48217. };
  48218. var vertexReferences = [];
  48219. var vertexInit = function (i) {
  48220. var offset = i + submesh.verticesStart;
  48221. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  48222. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  48223. vertex.originalOffsets.push(offset);
  48224. if (vertex.id === _this.vertices.length) {
  48225. _this.vertices.push(vertex);
  48226. }
  48227. vertexReferences.push(vertex.id);
  48228. };
  48229. //var totalVertices = mesh.getTotalVertices();
  48230. var totalVertices = submesh.verticesCount;
  48231. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  48232. var indicesInit = function (i) {
  48233. var offset = (submesh.indexStart / 3) + i;
  48234. var pos = (offset * 3);
  48235. var i0 = indices[pos + 0];
  48236. var i1 = indices[pos + 1];
  48237. var i2 = indices[pos + 2];
  48238. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  48239. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  48240. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  48241. var triangle = new DecimationTriangle([v0, v1, v2]);
  48242. triangle.originalOffset = pos;
  48243. _this.triangles.push(triangle);
  48244. };
  48245. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  48246. _this.init(callback);
  48247. });
  48248. });
  48249. };
  48250. QuadraticErrorSimplification.prototype.init = function (callback) {
  48251. var _this = this;
  48252. var triangleInit1 = function (i) {
  48253. var t = _this.triangles[i];
  48254. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  48255. for (var j = 0; j < 3; j++) {
  48256. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  48257. }
  48258. };
  48259. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  48260. var triangleInit2 = function (i) {
  48261. var t = _this.triangles[i];
  48262. for (var j = 0; j < 3; ++j) {
  48263. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  48264. }
  48265. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48266. };
  48267. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  48268. _this.initialized = true;
  48269. callback();
  48270. });
  48271. });
  48272. };
  48273. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  48274. var newTriangles = [];
  48275. var i;
  48276. for (i = 0; i < this.vertices.length; ++i) {
  48277. this.vertices[i].triangleCount = 0;
  48278. }
  48279. var t;
  48280. var j;
  48281. for (i = 0; i < this.triangles.length; ++i) {
  48282. if (!this.triangles[i].deleted) {
  48283. t = this.triangles[i];
  48284. for (j = 0; j < 3; ++j) {
  48285. t.vertices[j].triangleCount = 1;
  48286. }
  48287. newTriangles.push(t);
  48288. }
  48289. }
  48290. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  48291. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  48292. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  48293. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  48294. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48295. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48296. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48297. var vertexCount = 0;
  48298. for (i = 0; i < this.vertices.length; ++i) {
  48299. var vertex = this.vertices[i];
  48300. vertex.id = vertexCount;
  48301. if (vertex.triangleCount) {
  48302. vertex.originalOffsets.forEach(function (originalOffset) {
  48303. newPositionData.push(vertex.position.x);
  48304. newPositionData.push(vertex.position.y);
  48305. newPositionData.push(vertex.position.z);
  48306. newNormalData.push(normalData[originalOffset * 3]);
  48307. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  48308. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  48309. if (uvs && uvs.length) {
  48310. newUVsData.push(uvs[(originalOffset * 2)]);
  48311. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  48312. }
  48313. else if (colorsData && colorsData.length) {
  48314. newColorsData.push(colorsData[(originalOffset * 4)]);
  48315. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  48316. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  48317. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  48318. }
  48319. ++vertexCount;
  48320. });
  48321. }
  48322. }
  48323. var startingIndex = this._reconstructedMesh.getTotalIndices();
  48324. var startingVertex = this._reconstructedMesh.getTotalVertices();
  48325. var submeshesArray = this._reconstructedMesh.subMeshes;
  48326. this._reconstructedMesh.subMeshes = [];
  48327. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  48328. var originalIndices = this._mesh.getIndices();
  48329. for (i = 0; i < newTriangles.length; ++i) {
  48330. t = newTriangles[i]; //now get the new referencing point for each vertex
  48331. [0, 1, 2].forEach(function (idx) {
  48332. var id = originalIndices[t.originalOffset + idx];
  48333. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  48334. if (offset < 0)
  48335. offset = 0;
  48336. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  48337. });
  48338. }
  48339. //overwriting the old vertex buffers and indices.
  48340. this._reconstructedMesh.setIndices(newIndicesArray);
  48341. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  48342. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  48343. if (newUVsData.length > 0)
  48344. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  48345. if (newColorsData.length > 0)
  48346. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  48347. //create submesh
  48348. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  48349. if (submeshIndex > 0) {
  48350. this._reconstructedMesh.subMeshes = [];
  48351. submeshesArray.forEach(function (submesh) {
  48352. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  48353. });
  48354. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  48355. }
  48356. };
  48357. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  48358. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  48359. this._reconstructedMesh.material = this._mesh.material;
  48360. this._reconstructedMesh.parent = this._mesh.parent;
  48361. this._reconstructedMesh.isVisible = false;
  48362. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  48363. };
  48364. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  48365. for (var i = 0; i < vertex1.triangleCount; ++i) {
  48366. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  48367. if (t.deleted)
  48368. continue;
  48369. var s = this.references[vertex1.triangleStart + i].vertexId;
  48370. var v1 = t.vertices[(s + 1) % 3];
  48371. var v2 = t.vertices[(s + 2) % 3];
  48372. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  48373. deletedArray[i] = true;
  48374. delTr.push(t);
  48375. continue;
  48376. }
  48377. var d1 = v1.position.subtract(point);
  48378. d1 = d1.normalize();
  48379. var d2 = v2.position.subtract(point);
  48380. d2 = d2.normalize();
  48381. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  48382. return true;
  48383. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  48384. deletedArray[i] = false;
  48385. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  48386. return true;
  48387. }
  48388. return false;
  48389. };
  48390. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  48391. var newDeleted = deletedTriangles;
  48392. for (var i = 0; i < vertex.triangleCount; ++i) {
  48393. var ref = this.references[vertex.triangleStart + i];
  48394. var t = this.triangles[ref.triangleId];
  48395. if (t.deleted)
  48396. continue;
  48397. if (deletedArray[i] && t.deletePending) {
  48398. t.deleted = true;
  48399. newDeleted++;
  48400. continue;
  48401. }
  48402. t.vertices[ref.vertexId] = origVertex;
  48403. t.isDirty = true;
  48404. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  48405. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  48406. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  48407. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48408. this.references.push(ref);
  48409. }
  48410. return newDeleted;
  48411. };
  48412. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  48413. for (var i = 0; i < this.vertices.length; ++i) {
  48414. var vCount = [];
  48415. var vId = [];
  48416. var v = this.vertices[i];
  48417. var j;
  48418. for (j = 0; j < v.triangleCount; ++j) {
  48419. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  48420. for (var ii = 0; ii < 3; ii++) {
  48421. var ofs = 0;
  48422. var vv = triangle.vertices[ii];
  48423. while (ofs < vCount.length) {
  48424. if (vId[ofs] === vv.id)
  48425. break;
  48426. ++ofs;
  48427. }
  48428. if (ofs === vCount.length) {
  48429. vCount.push(1);
  48430. vId.push(vv.id);
  48431. }
  48432. else {
  48433. vCount[ofs]++;
  48434. }
  48435. }
  48436. }
  48437. for (j = 0; j < vCount.length; ++j) {
  48438. if (vCount[j] === 1) {
  48439. this.vertices[vId[j]].isBorder = true;
  48440. }
  48441. else {
  48442. this.vertices[vId[j]].isBorder = false;
  48443. }
  48444. }
  48445. }
  48446. };
  48447. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  48448. if (identifyBorders === void 0) { identifyBorders = false; }
  48449. var i;
  48450. if (!identifyBorders) {
  48451. var newTrianglesVector = [];
  48452. for (i = 0; i < this.triangles.length; ++i) {
  48453. if (!this.triangles[i].deleted) {
  48454. newTrianglesVector.push(this.triangles[i]);
  48455. }
  48456. }
  48457. this.triangles = newTrianglesVector;
  48458. }
  48459. for (i = 0; i < this.vertices.length; ++i) {
  48460. this.vertices[i].triangleCount = 0;
  48461. this.vertices[i].triangleStart = 0;
  48462. }
  48463. var t;
  48464. var j;
  48465. var v;
  48466. for (i = 0; i < this.triangles.length; ++i) {
  48467. t = this.triangles[i];
  48468. for (j = 0; j < 3; ++j) {
  48469. v = t.vertices[j];
  48470. v.triangleCount++;
  48471. }
  48472. }
  48473. var tStart = 0;
  48474. for (i = 0; i < this.vertices.length; ++i) {
  48475. this.vertices[i].triangleStart = tStart;
  48476. tStart += this.vertices[i].triangleCount;
  48477. this.vertices[i].triangleCount = 0;
  48478. }
  48479. var newReferences = new Array(this.triangles.length * 3);
  48480. for (i = 0; i < this.triangles.length; ++i) {
  48481. t = this.triangles[i];
  48482. for (j = 0; j < 3; ++j) {
  48483. v = t.vertices[j];
  48484. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  48485. v.triangleCount++;
  48486. }
  48487. }
  48488. this.references = newReferences;
  48489. if (identifyBorders) {
  48490. this.identifyBorder();
  48491. }
  48492. };
  48493. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  48494. var x = point.x;
  48495. var y = point.y;
  48496. var z = point.z;
  48497. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
  48498. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  48499. };
  48500. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  48501. var q = vertex1.q.add(vertex2.q);
  48502. var border = vertex1.isBorder && vertex2.isBorder;
  48503. var error = 0;
  48504. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  48505. if (qDet !== 0 && !border) {
  48506. if (!pointResult) {
  48507. pointResult = BABYLON.Vector3.Zero();
  48508. }
  48509. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  48510. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  48511. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  48512. error = this.vertexError(q, pointResult);
  48513. }
  48514. else {
  48515. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  48516. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  48517. var error1 = this.vertexError(q, vertex1.position);
  48518. var error2 = this.vertexError(q, vertex2.position);
  48519. var error3 = this.vertexError(q, p3);
  48520. error = Math.min(error1, error2, error3);
  48521. if (error === error1) {
  48522. if (pointResult) {
  48523. pointResult.copyFrom(vertex1.position);
  48524. }
  48525. }
  48526. else if (error === error2) {
  48527. if (pointResult) {
  48528. pointResult.copyFrom(vertex2.position);
  48529. }
  48530. }
  48531. else {
  48532. if (pointResult) {
  48533. pointResult.copyFrom(p3);
  48534. }
  48535. }
  48536. }
  48537. return error;
  48538. };
  48539. return QuadraticErrorSimplification;
  48540. }());
  48541. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  48542. })(BABYLON || (BABYLON = {}));
  48543. //# sourceMappingURL=babylon.meshSimplification.js.map
  48544. var BABYLON;
  48545. (function (BABYLON) {
  48546. var serializedGeometries = [];
  48547. var serializeGeometry = function (geometry, serializationGeometries) {
  48548. if (serializedGeometries[geometry.id]) {
  48549. return;
  48550. }
  48551. if (geometry.doNotSerialize) {
  48552. return;
  48553. }
  48554. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  48555. serializationGeometries.boxes.push(geometry.serialize());
  48556. }
  48557. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  48558. serializationGeometries.spheres.push(geometry.serialize());
  48559. }
  48560. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  48561. serializationGeometries.cylinders.push(geometry.serialize());
  48562. }
  48563. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  48564. serializationGeometries.toruses.push(geometry.serialize());
  48565. }
  48566. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  48567. serializationGeometries.grounds.push(geometry.serialize());
  48568. }
  48569. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  48570. serializationGeometries.planes.push(geometry.serialize());
  48571. }
  48572. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  48573. serializationGeometries.torusKnots.push(geometry.serialize());
  48574. }
  48575. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  48576. throw new Error("Unknown primitive type");
  48577. }
  48578. else {
  48579. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  48580. }
  48581. serializedGeometries[geometry.id] = true;
  48582. };
  48583. var serializeMesh = function (mesh, serializationScene) {
  48584. var serializationObject = {};
  48585. // Geometry
  48586. var geometry = mesh._geometry;
  48587. if (geometry) {
  48588. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  48589. // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  48590. serializeGeometry(geometry, serializationScene.geometries);
  48591. }
  48592. }
  48593. // Custom
  48594. if (mesh.serialize) {
  48595. mesh.serialize(serializationObject);
  48596. }
  48597. return serializationObject;
  48598. };
  48599. var finalizeSingleMesh = function (mesh, serializationObject) {
  48600. //only works if the mesh is already loaded
  48601. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48602. //serialize material
  48603. if (mesh.material) {
  48604. if (mesh.material instanceof BABYLON.StandardMaterial) {
  48605. serializationObject.materials = serializationObject.materials || [];
  48606. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48607. serializationObject.materials.push(mesh.material.serialize());
  48608. }
  48609. }
  48610. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  48611. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  48612. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  48613. serializationObject.multiMaterials.push(mesh.material.serialize());
  48614. }
  48615. }
  48616. }
  48617. //serialize geometry
  48618. var geometry = mesh._geometry;
  48619. if (geometry) {
  48620. if (!serializationObject.geometries) {
  48621. serializationObject.geometries = {};
  48622. serializationObject.geometries.boxes = [];
  48623. serializationObject.geometries.spheres = [];
  48624. serializationObject.geometries.cylinders = [];
  48625. serializationObject.geometries.toruses = [];
  48626. serializationObject.geometries.grounds = [];
  48627. serializationObject.geometries.planes = [];
  48628. serializationObject.geometries.torusKnots = [];
  48629. serializationObject.geometries.vertexData = [];
  48630. }
  48631. serializeGeometry(geometry, serializationObject.geometries);
  48632. }
  48633. // Skeletons
  48634. if (mesh.skeleton) {
  48635. serializationObject.skeletons = serializationObject.skeletons || [];
  48636. serializationObject.skeletons.push(mesh.skeleton.serialize());
  48637. }
  48638. //serialize the actual mesh
  48639. serializationObject.meshes = serializationObject.meshes || [];
  48640. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48641. }
  48642. };
  48643. var SceneSerializer = (function () {
  48644. function SceneSerializer() {
  48645. }
  48646. SceneSerializer.ClearCache = function () {
  48647. serializedGeometries = [];
  48648. };
  48649. SceneSerializer.Serialize = function (scene) {
  48650. var serializationObject = {};
  48651. SceneSerializer.ClearCache();
  48652. // Scene
  48653. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  48654. serializationObject.autoClear = scene.autoClear;
  48655. serializationObject.clearColor = scene.clearColor.asArray();
  48656. serializationObject.ambientColor = scene.ambientColor.asArray();
  48657. serializationObject.gravity = scene.gravity.asArray();
  48658. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  48659. serializationObject.workerCollisions = scene.workerCollisions;
  48660. // Fog
  48661. if (scene.fogMode && scene.fogMode !== 0) {
  48662. serializationObject.fogMode = scene.fogMode;
  48663. serializationObject.fogColor = scene.fogColor.asArray();
  48664. serializationObject.fogStart = scene.fogStart;
  48665. serializationObject.fogEnd = scene.fogEnd;
  48666. serializationObject.fogDensity = scene.fogDensity;
  48667. }
  48668. //Physics
  48669. if (scene.isPhysicsEnabled()) {
  48670. serializationObject.physicsEnabled = true;
  48671. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  48672. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  48673. }
  48674. // Metadata
  48675. if (scene.metadata) {
  48676. serializationObject.metadata = scene.metadata;
  48677. }
  48678. // Morph targets
  48679. serializationObject.morphTargetManagers = [];
  48680. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  48681. var abstractMesh = _a[_i];
  48682. var manager = abstractMesh.morphTargetManager;
  48683. if (manager) {
  48684. serializationObject.morphTargetManagers.push(manager.serialize());
  48685. }
  48686. }
  48687. // Lights
  48688. serializationObject.lights = [];
  48689. var index;
  48690. var light;
  48691. for (index = 0; index < scene.lights.length; index++) {
  48692. light = scene.lights[index];
  48693. if (!light.doNotSerialize) {
  48694. serializationObject.lights.push(light.serialize());
  48695. }
  48696. }
  48697. // Cameras
  48698. serializationObject.cameras = [];
  48699. for (index = 0; index < scene.cameras.length; index++) {
  48700. var camera = scene.cameras[index];
  48701. if (!camera.doNotSerialize) {
  48702. serializationObject.cameras.push(camera.serialize());
  48703. }
  48704. }
  48705. if (scene.activeCamera) {
  48706. serializationObject.activeCameraID = scene.activeCamera.id;
  48707. }
  48708. // Animations
  48709. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  48710. // Materials
  48711. serializationObject.materials = [];
  48712. serializationObject.multiMaterials = [];
  48713. var material;
  48714. for (index = 0; index < scene.materials.length; index++) {
  48715. material = scene.materials[index];
  48716. if (!material.doNotSerialize) {
  48717. serializationObject.materials.push(material.serialize());
  48718. }
  48719. }
  48720. // MultiMaterials
  48721. serializationObject.multiMaterials = [];
  48722. for (index = 0; index < scene.multiMaterials.length; index++) {
  48723. var multiMaterial = scene.multiMaterials[index];
  48724. serializationObject.multiMaterials.push(multiMaterial.serialize());
  48725. }
  48726. // Skeletons
  48727. serializationObject.skeletons = [];
  48728. for (index = 0; index < scene.skeletons.length; index++) {
  48729. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  48730. }
  48731. // Geometries
  48732. serializationObject.geometries = {};
  48733. serializationObject.geometries.boxes = [];
  48734. serializationObject.geometries.spheres = [];
  48735. serializationObject.geometries.cylinders = [];
  48736. serializationObject.geometries.toruses = [];
  48737. serializationObject.geometries.grounds = [];
  48738. serializationObject.geometries.planes = [];
  48739. serializationObject.geometries.torusKnots = [];
  48740. serializationObject.geometries.vertexData = [];
  48741. serializedGeometries = [];
  48742. var geometries = scene.getGeometries();
  48743. for (index = 0; index < geometries.length; index++) {
  48744. var geometry = geometries[index];
  48745. if (geometry.isReady()) {
  48746. serializeGeometry(geometry, serializationObject.geometries);
  48747. }
  48748. }
  48749. // Meshes
  48750. serializationObject.meshes = [];
  48751. for (index = 0; index < scene.meshes.length; index++) {
  48752. var abstractMesh = scene.meshes[index];
  48753. if (abstractMesh instanceof BABYLON.Mesh) {
  48754. var mesh = abstractMesh;
  48755. if (!mesh.doNotSerialize) {
  48756. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  48757. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  48758. }
  48759. }
  48760. }
  48761. }
  48762. // Particles Systems
  48763. serializationObject.particleSystems = [];
  48764. for (index = 0; index < scene.particleSystems.length; index++) {
  48765. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  48766. }
  48767. // Lens flares
  48768. serializationObject.lensFlareSystems = [];
  48769. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  48770. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  48771. }
  48772. // Shadows
  48773. serializationObject.shadowGenerators = [];
  48774. for (index = 0; index < scene.lights.length; index++) {
  48775. light = scene.lights[index];
  48776. var shadowGenerator = light.getShadowGenerator();
  48777. // Only support serialization for official generator so far.
  48778. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  48779. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  48780. }
  48781. }
  48782. // Action Manager
  48783. if (scene.actionManager) {
  48784. serializationObject.actions = scene.actionManager.serialize("scene");
  48785. }
  48786. // Audio
  48787. serializationObject.sounds = [];
  48788. for (index = 0; index < scene.soundTracks.length; index++) {
  48789. var soundtrack = scene.soundTracks[index];
  48790. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  48791. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  48792. }
  48793. }
  48794. return serializationObject;
  48795. };
  48796. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  48797. if (withParents === void 0) { withParents = false; }
  48798. if (withChildren === void 0) { withChildren = false; }
  48799. var serializationObject = {};
  48800. SceneSerializer.ClearCache();
  48801. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  48802. if (withParents || withChildren) {
  48803. //deliberate for loop! not for each, appended should be processed as well.
  48804. for (var i = 0; i < toSerialize.length; ++i) {
  48805. if (withChildren) {
  48806. toSerialize[i].getDescendants().forEach(function (node) {
  48807. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  48808. toSerialize.push(node);
  48809. }
  48810. });
  48811. }
  48812. //make sure the array doesn't contain the object already
  48813. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  48814. toSerialize.push(toSerialize[i].parent);
  48815. }
  48816. }
  48817. }
  48818. toSerialize.forEach(function (mesh) {
  48819. finalizeSingleMesh(mesh, serializationObject);
  48820. });
  48821. return serializationObject;
  48822. };
  48823. return SceneSerializer;
  48824. }());
  48825. BABYLON.SceneSerializer = SceneSerializer;
  48826. })(BABYLON || (BABYLON = {}));
  48827. //# sourceMappingURL=babylon.sceneSerializer.js.map
  48828. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  48829. // Huge respect for a such great lib.
  48830. // Earcut license:
  48831. // Copyright (c) 2016, Mapbox
  48832. //
  48833. // Permission to use, copy, modify, and/or distribute this software for any purpose
  48834. // with or without fee is hereby granted, provided that the above copyright notice
  48835. // and this permission notice appear in all copies.
  48836. //
  48837. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  48838. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  48839. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  48840. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  48841. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  48842. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  48843. // THIS SOFTWARE.
  48844. var Earcut;
  48845. (function (Earcut) {
  48846. /**
  48847. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  48848. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  48849. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  48850. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  48851. */
  48852. function earcut(data, holeIndices, dim) {
  48853. dim = dim || 2;
  48854. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  48855. if (!outerNode)
  48856. return triangles;
  48857. var minX, minY, maxX, maxY, x, y, size;
  48858. if (hasHoles)
  48859. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  48860. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  48861. if (data.length > 80 * dim) {
  48862. minX = maxX = data[0];
  48863. minY = maxY = data[1];
  48864. for (var i = dim; i < outerLen; i += dim) {
  48865. x = data[i];
  48866. y = data[i + 1];
  48867. if (x < minX)
  48868. minX = x;
  48869. if (y < minY)
  48870. minY = y;
  48871. if (x > maxX)
  48872. maxX = x;
  48873. if (y > maxY)
  48874. maxY = y;
  48875. }
  48876. // minX, minY and size are later used to transform coords into integers for z-order calculation
  48877. size = Math.max(maxX - minX, maxY - minY);
  48878. }
  48879. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  48880. return triangles;
  48881. }
  48882. Earcut.earcut = earcut;
  48883. // create a circular doubly linked list from polygon points in the specified winding order
  48884. function linkedList(data, start, end, dim, clockwise) {
  48885. var i, last;
  48886. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  48887. for (i = start; i < end; i += dim)
  48888. last = insertNode(i, data[i], data[i + 1], last);
  48889. }
  48890. else {
  48891. for (i = end - dim; i >= start; i -= dim)
  48892. last = insertNode(i, data[i], data[i + 1], last);
  48893. }
  48894. if (last && equals(last, last.next)) {
  48895. removeNode(last);
  48896. last = last.next;
  48897. }
  48898. return last;
  48899. }
  48900. // eliminate colinear or duplicate points
  48901. function filterPoints(start, end) {
  48902. if (!start)
  48903. return start;
  48904. if (!end)
  48905. end = start;
  48906. var p = start, again;
  48907. do {
  48908. again = false;
  48909. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  48910. removeNode(p);
  48911. p = end = p.prev;
  48912. if (p === p.next)
  48913. return null;
  48914. again = true;
  48915. }
  48916. else {
  48917. p = p.next;
  48918. }
  48919. } while (again || p !== end);
  48920. return end;
  48921. }
  48922. // main ear slicing loop which triangulates a polygon (given as a linked list)
  48923. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  48924. if (!ear)
  48925. return;
  48926. // interlink polygon nodes in z-order
  48927. if (!pass && size)
  48928. indexCurve(ear, minX, minY, size);
  48929. var stop = ear, prev, next;
  48930. // iterate through ears, slicing them one by one
  48931. while (ear.prev !== ear.next) {
  48932. prev = ear.prev;
  48933. next = ear.next;
  48934. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  48935. // cut off the triangle
  48936. triangles.push(prev.i / dim);
  48937. triangles.push(ear.i / dim);
  48938. triangles.push(next.i / dim);
  48939. removeNode(ear);
  48940. // skipping the next vertice leads to less sliver triangles
  48941. ear = next.next;
  48942. stop = next.next;
  48943. continue;
  48944. }
  48945. ear = next;
  48946. // if we looped through the whole remaining polygon and can't find any more ears
  48947. if (ear === stop) {
  48948. // try filtering points and slicing again
  48949. if (!pass) {
  48950. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  48951. // if this didn't work, try curing all small self-intersections locally
  48952. }
  48953. else if (pass === 1) {
  48954. ear = cureLocalIntersections(ear, triangles, dim);
  48955. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  48956. // as a last resort, try splitting the remaining polygon into two
  48957. }
  48958. else if (pass === 2) {
  48959. splitEarcut(ear, triangles, dim, minX, minY, size);
  48960. }
  48961. break;
  48962. }
  48963. }
  48964. }
  48965. // check whether a polygon node forms a valid ear with adjacent nodes
  48966. function isEar(ear) {
  48967. var a = ear.prev, b = ear, c = ear.next;
  48968. if (area(a, b, c) >= 0)
  48969. return false; // reflex, can't be an ear
  48970. // now make sure we don't have other points inside the potential ear
  48971. var p = ear.next.next;
  48972. while (p !== ear.prev) {
  48973. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48974. area(p.prev, p, p.next) >= 0)
  48975. return false;
  48976. p = p.next;
  48977. }
  48978. return true;
  48979. }
  48980. function isEarHashed(ear, minX, minY, size) {
  48981. var a = ear.prev, b = ear, c = ear.next;
  48982. if (area(a, b, c) >= 0)
  48983. return false; // reflex, can't be an ear
  48984. // triangle bbox; min & max are calculated like this for speed
  48985. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  48986. // z-order range for the current triangle bbox;
  48987. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  48988. // first look for points inside the triangle in increasing z-order
  48989. var p = ear.nextZ;
  48990. while (p && p.z <= maxZ) {
  48991. if (p !== ear.prev &&
  48992. p !== ear.next &&
  48993. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  48994. area(p.prev, p, p.next) >= 0)
  48995. return false;
  48996. p = p.nextZ;
  48997. }
  48998. // then look for points in decreasing z-order
  48999. p = ear.prevZ;
  49000. while (p && p.z >= minZ) {
  49001. if (p !== ear.prev &&
  49002. p !== ear.next &&
  49003. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49004. area(p.prev, p, p.next) >= 0)
  49005. return false;
  49006. p = p.prevZ;
  49007. }
  49008. return true;
  49009. }
  49010. // go through all polygon nodes and cure small local self-intersections
  49011. function cureLocalIntersections(start, triangles, dim) {
  49012. var p = start;
  49013. do {
  49014. var a = p.prev, b = p.next.next;
  49015. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  49016. triangles.push(a.i / dim);
  49017. triangles.push(p.i / dim);
  49018. triangles.push(b.i / dim);
  49019. // remove two nodes involved
  49020. removeNode(p);
  49021. removeNode(p.next);
  49022. p = start = b;
  49023. }
  49024. p = p.next;
  49025. } while (p !== start);
  49026. return p;
  49027. }
  49028. // try splitting polygon into two and triangulate them independently
  49029. function splitEarcut(start, triangles, dim, minX, minY, size) {
  49030. // look for a valid diagonal that divides the polygon into two
  49031. var a = start;
  49032. do {
  49033. var b = a.next.next;
  49034. while (b !== a.prev) {
  49035. if (a.i !== b.i && isValidDiagonal(a, b)) {
  49036. // split the polygon in two by the diagonal
  49037. var c = splitPolygon(a, b);
  49038. // filter colinear points around the cuts
  49039. a = filterPoints(a, a.next);
  49040. c = filterPoints(c, c.next);
  49041. // run earcut on each half
  49042. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  49043. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  49044. return;
  49045. }
  49046. b = b.next;
  49047. }
  49048. a = a.next;
  49049. } while (a !== start);
  49050. }
  49051. // link every hole into the outer loop, producing a single-ring polygon without holes
  49052. function eliminateHoles(data, holeIndices, outerNode, dim) {
  49053. var queue = [], i, len, start, end, list;
  49054. for (i = 0, len = holeIndices.length; i < len; i++) {
  49055. start = holeIndices[i] * dim;
  49056. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49057. list = linkedList(data, start, end, dim, false);
  49058. if (list === list.next)
  49059. list.steiner = true;
  49060. queue.push(getLeftmost(list));
  49061. }
  49062. queue.sort(compareX);
  49063. // process holes from left to right
  49064. for (i = 0; i < queue.length; i++) {
  49065. eliminateHole(queue[i], outerNode);
  49066. outerNode = filterPoints(outerNode, outerNode.next);
  49067. }
  49068. return outerNode;
  49069. }
  49070. function compareX(a, b) {
  49071. return a.x - b.x;
  49072. }
  49073. // find a bridge between vertices that connects hole with an outer ring and and link it
  49074. function eliminateHole(hole, outerNode) {
  49075. outerNode = findHoleBridge(hole, outerNode);
  49076. if (outerNode) {
  49077. var b = splitPolygon(outerNode, hole);
  49078. filterPoints(b, b.next);
  49079. }
  49080. }
  49081. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  49082. function findHoleBridge(hole, outerNode) {
  49083. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  49084. // find a segment intersected by a ray from the hole's leftmost point to the left;
  49085. // segment's endpoint with lesser x will be potential connection point
  49086. do {
  49087. if (hy <= p.y && hy >= p.next.y) {
  49088. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  49089. if (x <= hx && x > qx) {
  49090. qx = x;
  49091. if (x === hx) {
  49092. if (hy === p.y)
  49093. return p;
  49094. if (hy === p.next.y)
  49095. return p.next;
  49096. }
  49097. m = p.x < p.next.x ? p : p.next;
  49098. }
  49099. }
  49100. p = p.next;
  49101. } while (p !== outerNode);
  49102. if (!m)
  49103. return null;
  49104. if (hx === qx)
  49105. return m.prev; // hole touches outer segment; pick lower endpoint
  49106. // look for points inside the triangle of hole point, segment intersection and endpoint;
  49107. // if there are no points found, we have a valid connection;
  49108. // otherwise choose the point of the minimum angle with the ray as connection point
  49109. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  49110. p = m.next;
  49111. while (p !== stop) {
  49112. if (hx >= p.x &&
  49113. p.x >= mx &&
  49114. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  49115. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  49116. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  49117. m = p;
  49118. tanMin = tan;
  49119. }
  49120. }
  49121. p = p.next;
  49122. }
  49123. return m;
  49124. }
  49125. // interlink polygon nodes in z-order
  49126. function indexCurve(start, minX, minY, size) {
  49127. var p = start;
  49128. do {
  49129. if (p.z === null)
  49130. p.z = zOrder(p.x, p.y, minX, minY, size);
  49131. p.prevZ = p.prev;
  49132. p.nextZ = p.next;
  49133. p = p.next;
  49134. } while (p !== start);
  49135. p.prevZ.nextZ = null;
  49136. p.prevZ = null;
  49137. sortLinked(p);
  49138. }
  49139. // Simon Tatham's linked list merge sort algorithm
  49140. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  49141. function sortLinked(list) {
  49142. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  49143. do {
  49144. p = list;
  49145. list = null;
  49146. tail = null;
  49147. numMerges = 0;
  49148. while (p) {
  49149. numMerges++;
  49150. q = p;
  49151. pSize = 0;
  49152. for (i = 0; i < inSize; i++) {
  49153. pSize++;
  49154. q = q.nextZ;
  49155. if (!q)
  49156. break;
  49157. }
  49158. qSize = inSize;
  49159. while (pSize > 0 || (qSize > 0 && q)) {
  49160. if (pSize === 0) {
  49161. e = q;
  49162. q = q.nextZ;
  49163. qSize--;
  49164. }
  49165. else if (qSize === 0 || !q) {
  49166. e = p;
  49167. p = p.nextZ;
  49168. pSize--;
  49169. }
  49170. else if (p.z <= q.z) {
  49171. e = p;
  49172. p = p.nextZ;
  49173. pSize--;
  49174. }
  49175. else {
  49176. e = q;
  49177. q = q.nextZ;
  49178. qSize--;
  49179. }
  49180. if (tail)
  49181. tail.nextZ = e;
  49182. else
  49183. list = e;
  49184. e.prevZ = tail;
  49185. tail = e;
  49186. }
  49187. p = q;
  49188. }
  49189. tail.nextZ = null;
  49190. inSize *= 2;
  49191. } while (numMerges > 1);
  49192. return list;
  49193. }
  49194. // z-order of a point given coords and size of the data bounding box
  49195. function zOrder(x, y, minX, minY, size) {
  49196. // coords are transformed into non-negative 15-bit integer range
  49197. x = 32767 * (x - minX) / size;
  49198. y = 32767 * (y - minY) / size;
  49199. x = (x | (x << 8)) & 0x00FF00FF;
  49200. x = (x | (x << 4)) & 0x0F0F0F0F;
  49201. x = (x | (x << 2)) & 0x33333333;
  49202. x = (x | (x << 1)) & 0x55555555;
  49203. y = (y | (y << 8)) & 0x00FF00FF;
  49204. y = (y | (y << 4)) & 0x0F0F0F0F;
  49205. y = (y | (y << 2)) & 0x33333333;
  49206. y = (y | (y << 1)) & 0x55555555;
  49207. return x | (y << 1);
  49208. }
  49209. // find the leftmost node of a polygon ring
  49210. function getLeftmost(start) {
  49211. var p = start, leftmost = start;
  49212. do {
  49213. if (p.x < leftmost.x)
  49214. leftmost = p;
  49215. p = p.next;
  49216. } while (p !== start);
  49217. return leftmost;
  49218. }
  49219. // check if a point lies within a convex triangle
  49220. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  49221. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  49222. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  49223. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  49224. }
  49225. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  49226. function isValidDiagonal(a, b) {
  49227. return a.next.i !== b.i &&
  49228. a.prev.i !== b.i &&
  49229. !intersectsPolygon(a, b) &&
  49230. locallyInside(a, b) &&
  49231. locallyInside(b, a) &&
  49232. middleInside(a, b);
  49233. }
  49234. // signed area of a triangle
  49235. function area(p, q, r) {
  49236. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  49237. }
  49238. // check if two points are equal
  49239. function equals(p1, p2) {
  49240. return p1.x === p2.x && p1.y === p2.y;
  49241. }
  49242. // check if two segments intersect
  49243. function intersects(p1, q1, p2, q2) {
  49244. if ((equals(p1, q1) && equals(p2, q2)) ||
  49245. (equals(p1, q2) && equals(p2, q1)))
  49246. return true;
  49247. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  49248. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  49249. }
  49250. // check if a polygon diagonal intersects any polygon segments
  49251. function intersectsPolygon(a, b) {
  49252. var p = a;
  49253. do {
  49254. if (p.i !== a.i &&
  49255. p.next.i !== a.i &&
  49256. p.i !== b.i &&
  49257. p.next.i !== b.i &&
  49258. intersects(p, p.next, a, b))
  49259. return true;
  49260. p = p.next;
  49261. } while (p !== a);
  49262. return false;
  49263. }
  49264. // check if a polygon diagonal is locally inside the polygon
  49265. function locallyInside(a, b) {
  49266. return area(a.prev, a, a.next) < 0
  49267. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  49268. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  49269. }
  49270. // check if the middle point of a polygon diagonal is inside the polygon
  49271. function middleInside(a, b) {
  49272. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  49273. do {
  49274. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  49275. inside = !inside;
  49276. p = p.next;
  49277. } while (p !== a);
  49278. return inside;
  49279. }
  49280. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  49281. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  49282. function splitPolygon(a, b) {
  49283. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  49284. a.next = b;
  49285. b.prev = a;
  49286. a2.next = an;
  49287. an.prev = a2;
  49288. b2.next = a2;
  49289. a2.prev = b2;
  49290. bp.next = b2;
  49291. b2.prev = bp;
  49292. return b2;
  49293. }
  49294. // create a node and optionally link it with previous one (in a circular doubly linked list)
  49295. function insertNode(i, x, y, last) {
  49296. var p = new Node(i, x, y);
  49297. if (!last) {
  49298. p.prev = p;
  49299. p.next = p;
  49300. }
  49301. else {
  49302. p.next = last.next;
  49303. p.prev = last;
  49304. last.next.prev = p;
  49305. last.next = p;
  49306. }
  49307. return p;
  49308. }
  49309. function removeNode(p) {
  49310. p.next.prev = p.prev;
  49311. p.prev.next = p.next;
  49312. if (p.prevZ)
  49313. p.prevZ.nextZ = p.nextZ;
  49314. if (p.nextZ)
  49315. p.nextZ.prevZ = p.prevZ;
  49316. }
  49317. function Node(i, x, y) {
  49318. // vertice index in coordinates array
  49319. this.i = i;
  49320. // vertex coordinates
  49321. this.x = x;
  49322. this.y = y;
  49323. // previous and next vertice nodes in a polygon ring
  49324. this.prev = null;
  49325. this.next = null;
  49326. // z-order curve value
  49327. this.z = null;
  49328. // previous and next nodes in z-order
  49329. this.prevZ = null;
  49330. this.nextZ = null;
  49331. // indicates whether this is a steiner point
  49332. this.steiner = false;
  49333. }
  49334. /**
  49335. * return a percentage difference between the polygon area and its triangulation area;
  49336. * used to verify correctness of triangulation
  49337. */
  49338. function deviation(data, holeIndices, dim, triangles) {
  49339. var hasHoles = holeIndices && holeIndices.length;
  49340. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  49341. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  49342. if (hasHoles) {
  49343. for (var i = 0, len = holeIndices.length; i < len; i++) {
  49344. var start = holeIndices[i] * dim;
  49345. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49346. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  49347. }
  49348. }
  49349. var trianglesArea = 0;
  49350. for (i = 0; i < triangles.length; i += 3) {
  49351. var a = triangles[i] * dim;
  49352. var b = triangles[i + 1] * dim;
  49353. var c = triangles[i + 2] * dim;
  49354. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  49355. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  49356. }
  49357. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  49358. }
  49359. Earcut.deviation = deviation;
  49360. ;
  49361. function signedArea(data, start, end, dim) {
  49362. var sum = 0;
  49363. for (var i = start, j = end - dim; i < end; i += dim) {
  49364. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  49365. j = i;
  49366. }
  49367. return sum;
  49368. }
  49369. /**
  49370. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  49371. */
  49372. function flatten(data) {
  49373. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  49374. for (var i = 0; i < data.length; i++) {
  49375. for (var j = 0; j < data[i].length; j++) {
  49376. for (var d = 0; d < dim; d++)
  49377. result.vertices.push(data[i][j][d]);
  49378. }
  49379. if (i > 0) {
  49380. holeIndex += data[i - 1].length;
  49381. result.holes.push(holeIndex);
  49382. }
  49383. }
  49384. return result;
  49385. }
  49386. Earcut.flatten = flatten;
  49387. ;
  49388. })(Earcut || (Earcut = {}));
  49389. //# sourceMappingURL=babylon.earcut.js.map
  49390. var BABYLON;
  49391. (function (BABYLON) {
  49392. // Unique ID when we import meshes from Babylon to CSG
  49393. var currentCSGMeshId = 0;
  49394. // # class Vertex
  49395. // Represents a vertex of a polygon. Use your own vertex class instead of this
  49396. // one to provide additional features like texture coordinates and vertex
  49397. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  49398. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  49399. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  49400. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  49401. // is not used anywhere else.
  49402. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  49403. var Vertex = (function () {
  49404. function Vertex(pos, normal, uv) {
  49405. this.pos = pos;
  49406. this.normal = normal;
  49407. this.uv = uv;
  49408. }
  49409. Vertex.prototype.clone = function () {
  49410. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  49411. };
  49412. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  49413. // orientation of a polygon is flipped.
  49414. Vertex.prototype.flip = function () {
  49415. this.normal = this.normal.scale(-1);
  49416. };
  49417. // Create a new vertex between this vertex and `other` by linearly
  49418. // interpolating all properties using a parameter of `t`. Subclasses should
  49419. // override this to interpolate additional properties.
  49420. Vertex.prototype.interpolate = function (other, t) {
  49421. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  49422. };
  49423. return Vertex;
  49424. }());
  49425. // # class Plane
  49426. // Represents a plane in 3D space.
  49427. var Plane = (function () {
  49428. function Plane(normal, w) {
  49429. this.normal = normal;
  49430. this.w = w;
  49431. }
  49432. Plane.FromPoints = function (a, b, c) {
  49433. var v0 = c.subtract(a);
  49434. var v1 = b.subtract(a);
  49435. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  49436. return null;
  49437. }
  49438. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  49439. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  49440. };
  49441. Plane.prototype.clone = function () {
  49442. return new Plane(this.normal.clone(), this.w);
  49443. };
  49444. Plane.prototype.flip = function () {
  49445. this.normal.scaleInPlace(-1);
  49446. this.w = -this.w;
  49447. };
  49448. // Split `polygon` by this plane if needed, then put the polygon or polygon
  49449. // fragments in the appropriate lists. Coplanar polygons go into either
  49450. // `coplanarFront` or `coplanarBack` depending on their orientation with
  49451. // respect to this plane. Polygons in front or in back of this plane go into
  49452. // either `front` or `back`.
  49453. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  49454. var COPLANAR = 0;
  49455. var FRONT = 1;
  49456. var BACK = 2;
  49457. var SPANNING = 3;
  49458. // Classify each point as well as the entire polygon into one of the above
  49459. // four classes.
  49460. var polygonType = 0;
  49461. var types = [];
  49462. var i;
  49463. var t;
  49464. for (i = 0; i < polygon.vertices.length; i++) {
  49465. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  49466. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  49467. polygonType |= type;
  49468. types.push(type);
  49469. }
  49470. // Put the polygon in the correct list, splitting it when necessary.
  49471. switch (polygonType) {
  49472. case COPLANAR:
  49473. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  49474. break;
  49475. case FRONT:
  49476. front.push(polygon);
  49477. break;
  49478. case BACK:
  49479. back.push(polygon);
  49480. break;
  49481. case SPANNING:
  49482. var f = [], b = [];
  49483. for (i = 0; i < polygon.vertices.length; i++) {
  49484. var j = (i + 1) % polygon.vertices.length;
  49485. var ti = types[i], tj = types[j];
  49486. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  49487. if (ti !== BACK)
  49488. f.push(vi);
  49489. if (ti !== FRONT)
  49490. b.push(ti !== BACK ? vi.clone() : vi);
  49491. if ((ti | tj) === SPANNING) {
  49492. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  49493. var v = vi.interpolate(vj, t);
  49494. f.push(v);
  49495. b.push(v.clone());
  49496. }
  49497. }
  49498. var poly;
  49499. if (f.length >= 3) {
  49500. poly = new Polygon(f, polygon.shared);
  49501. if (poly.plane)
  49502. front.push(poly);
  49503. }
  49504. if (b.length >= 3) {
  49505. poly = new Polygon(b, polygon.shared);
  49506. if (poly.plane)
  49507. back.push(poly);
  49508. }
  49509. break;
  49510. }
  49511. };
  49512. return Plane;
  49513. }());
  49514. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  49515. // point is on the plane.
  49516. Plane.EPSILON = 1e-5;
  49517. // # class Polygon
  49518. // Represents a convex polygon. The vertices used to initialize a polygon must
  49519. // be coplanar and form a convex loop.
  49520. //
  49521. // Each convex polygon has a `shared` property, which is shared between all
  49522. // polygons that are clones of each other or were split from the same polygon.
  49523. // This can be used to define per-polygon properties (such as surface color).
  49524. var Polygon = (function () {
  49525. function Polygon(vertices, shared) {
  49526. this.vertices = vertices;
  49527. this.shared = shared;
  49528. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  49529. }
  49530. Polygon.prototype.clone = function () {
  49531. var vertices = this.vertices.map(function (v) { return v.clone(); });
  49532. return new Polygon(vertices, this.shared);
  49533. };
  49534. Polygon.prototype.flip = function () {
  49535. this.vertices.reverse().map(function (v) { v.flip(); });
  49536. this.plane.flip();
  49537. };
  49538. return Polygon;
  49539. }());
  49540. // # class Node
  49541. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  49542. // by picking a polygon to split along. That polygon (and all other coplanar
  49543. // polygons) are added directly to that node and the other polygons are added to
  49544. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  49545. // no distinction between internal and leaf nodes.
  49546. var Node = (function () {
  49547. function Node(polygons) {
  49548. this.plane = null;
  49549. this.front = null;
  49550. this.back = null;
  49551. this.polygons = [];
  49552. if (polygons) {
  49553. this.build(polygons);
  49554. }
  49555. }
  49556. Node.prototype.clone = function () {
  49557. var node = new Node();
  49558. node.plane = this.plane && this.plane.clone();
  49559. node.front = this.front && this.front.clone();
  49560. node.back = this.back && this.back.clone();
  49561. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  49562. return node;
  49563. };
  49564. // Convert solid space to empty space and empty space to solid space.
  49565. Node.prototype.invert = function () {
  49566. for (var i = 0; i < this.polygons.length; i++) {
  49567. this.polygons[i].flip();
  49568. }
  49569. if (this.plane) {
  49570. this.plane.flip();
  49571. }
  49572. if (this.front) {
  49573. this.front.invert();
  49574. }
  49575. if (this.back) {
  49576. this.back.invert();
  49577. }
  49578. var temp = this.front;
  49579. this.front = this.back;
  49580. this.back = temp;
  49581. };
  49582. // Recursively remove all polygons in `polygons` that are inside this BSP
  49583. // tree.
  49584. Node.prototype.clipPolygons = function (polygons) {
  49585. if (!this.plane)
  49586. return polygons.slice();
  49587. var front = [], back = [];
  49588. for (var i = 0; i < polygons.length; i++) {
  49589. this.plane.splitPolygon(polygons[i], front, back, front, back);
  49590. }
  49591. if (this.front) {
  49592. front = this.front.clipPolygons(front);
  49593. }
  49594. if (this.back) {
  49595. back = this.back.clipPolygons(back);
  49596. }
  49597. else {
  49598. back = [];
  49599. }
  49600. return front.concat(back);
  49601. };
  49602. // Remove all polygons in this BSP tree that are inside the other BSP tree
  49603. // `bsp`.
  49604. Node.prototype.clipTo = function (bsp) {
  49605. this.polygons = bsp.clipPolygons(this.polygons);
  49606. if (this.front)
  49607. this.front.clipTo(bsp);
  49608. if (this.back)
  49609. this.back.clipTo(bsp);
  49610. };
  49611. // Return a list of all polygons in this BSP tree.
  49612. Node.prototype.allPolygons = function () {
  49613. var polygons = this.polygons.slice();
  49614. if (this.front)
  49615. polygons = polygons.concat(this.front.allPolygons());
  49616. if (this.back)
  49617. polygons = polygons.concat(this.back.allPolygons());
  49618. return polygons;
  49619. };
  49620. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  49621. // new polygons are filtered down to the bottom of the tree and become new
  49622. // nodes there. Each set of polygons is partitioned using the first polygon
  49623. // (no heuristic is used to pick a good split).
  49624. Node.prototype.build = function (polygons) {
  49625. if (!polygons.length)
  49626. return;
  49627. if (!this.plane)
  49628. this.plane = polygons[0].plane.clone();
  49629. var front = [], back = [];
  49630. for (var i = 0; i < polygons.length; i++) {
  49631. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  49632. }
  49633. if (front.length) {
  49634. if (!this.front)
  49635. this.front = new Node();
  49636. this.front.build(front);
  49637. }
  49638. if (back.length) {
  49639. if (!this.back)
  49640. this.back = new Node();
  49641. this.back.build(back);
  49642. }
  49643. };
  49644. return Node;
  49645. }());
  49646. var CSG = (function () {
  49647. function CSG() {
  49648. this.polygons = new Array();
  49649. }
  49650. // Convert BABYLON.Mesh to BABYLON.CSG
  49651. CSG.FromMesh = function (mesh) {
  49652. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  49653. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  49654. if (mesh instanceof BABYLON.Mesh) {
  49655. mesh.computeWorldMatrix(true);
  49656. matrix = mesh.getWorldMatrix();
  49657. meshPosition = mesh.position.clone();
  49658. meshRotation = mesh.rotation.clone();
  49659. if (mesh.rotationQuaternion) {
  49660. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  49661. }
  49662. meshScaling = mesh.scaling.clone();
  49663. }
  49664. else {
  49665. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  49666. }
  49667. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49668. var subMeshes = mesh.subMeshes;
  49669. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  49670. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  49671. vertices = [];
  49672. for (var j = 0; j < 3; j++) {
  49673. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  49674. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  49675. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  49676. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  49677. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  49678. vertex = new Vertex(position, normal, uv);
  49679. vertices.push(vertex);
  49680. }
  49681. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  49682. // To handle the case of degenerated triangle
  49683. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  49684. if (polygon.plane)
  49685. polygons.push(polygon);
  49686. }
  49687. }
  49688. var csg = CSG.FromPolygons(polygons);
  49689. csg.matrix = matrix;
  49690. csg.position = meshPosition;
  49691. csg.rotation = meshRotation;
  49692. csg.scaling = meshScaling;
  49693. csg.rotationQuaternion = meshRotationQuaternion;
  49694. currentCSGMeshId++;
  49695. return csg;
  49696. };
  49697. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  49698. CSG.FromPolygons = function (polygons) {
  49699. var csg = new CSG();
  49700. csg.polygons = polygons;
  49701. return csg;
  49702. };
  49703. CSG.prototype.clone = function () {
  49704. var csg = new CSG();
  49705. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  49706. csg.copyTransformAttributes(this);
  49707. return csg;
  49708. };
  49709. CSG.prototype.toPolygons = function () {
  49710. return this.polygons;
  49711. };
  49712. CSG.prototype.union = function (csg) {
  49713. var a = new Node(this.clone().polygons);
  49714. var b = new Node(csg.clone().polygons);
  49715. a.clipTo(b);
  49716. b.clipTo(a);
  49717. b.invert();
  49718. b.clipTo(a);
  49719. b.invert();
  49720. a.build(b.allPolygons());
  49721. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49722. };
  49723. CSG.prototype.unionInPlace = function (csg) {
  49724. var a = new Node(this.polygons);
  49725. var b = new Node(csg.polygons);
  49726. a.clipTo(b);
  49727. b.clipTo(a);
  49728. b.invert();
  49729. b.clipTo(a);
  49730. b.invert();
  49731. a.build(b.allPolygons());
  49732. this.polygons = a.allPolygons();
  49733. };
  49734. CSG.prototype.subtract = function (csg) {
  49735. var a = new Node(this.clone().polygons);
  49736. var b = new Node(csg.clone().polygons);
  49737. a.invert();
  49738. a.clipTo(b);
  49739. b.clipTo(a);
  49740. b.invert();
  49741. b.clipTo(a);
  49742. b.invert();
  49743. a.build(b.allPolygons());
  49744. a.invert();
  49745. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49746. };
  49747. CSG.prototype.subtractInPlace = function (csg) {
  49748. var a = new Node(this.polygons);
  49749. var b = new Node(csg.polygons);
  49750. a.invert();
  49751. a.clipTo(b);
  49752. b.clipTo(a);
  49753. b.invert();
  49754. b.clipTo(a);
  49755. b.invert();
  49756. a.build(b.allPolygons());
  49757. a.invert();
  49758. this.polygons = a.allPolygons();
  49759. };
  49760. CSG.prototype.intersect = function (csg) {
  49761. var a = new Node(this.clone().polygons);
  49762. var b = new Node(csg.clone().polygons);
  49763. a.invert();
  49764. b.clipTo(a);
  49765. b.invert();
  49766. a.clipTo(b);
  49767. b.clipTo(a);
  49768. a.build(b.allPolygons());
  49769. a.invert();
  49770. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  49771. };
  49772. CSG.prototype.intersectInPlace = function (csg) {
  49773. var a = new Node(this.polygons);
  49774. var b = new Node(csg.polygons);
  49775. a.invert();
  49776. b.clipTo(a);
  49777. b.invert();
  49778. a.clipTo(b);
  49779. b.clipTo(a);
  49780. a.build(b.allPolygons());
  49781. a.invert();
  49782. this.polygons = a.allPolygons();
  49783. };
  49784. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  49785. // not modified.
  49786. CSG.prototype.inverse = function () {
  49787. var csg = this.clone();
  49788. csg.inverseInPlace();
  49789. return csg;
  49790. };
  49791. CSG.prototype.inverseInPlace = function () {
  49792. this.polygons.map(function (p) { p.flip(); });
  49793. };
  49794. // This is used to keep meshes transformations so they can be restored
  49795. // when we build back a Babylon Mesh
  49796. // NB : All CSG operations are performed in world coordinates
  49797. CSG.prototype.copyTransformAttributes = function (csg) {
  49798. this.matrix = csg.matrix;
  49799. this.position = csg.position;
  49800. this.rotation = csg.rotation;
  49801. this.scaling = csg.scaling;
  49802. this.rotationQuaternion = csg.rotationQuaternion;
  49803. return this;
  49804. };
  49805. // Build Raw mesh from CSG
  49806. // Coordinates here are in world space
  49807. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  49808. var matrix = this.matrix.clone();
  49809. matrix.invert();
  49810. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  49811. if (keepSubMeshes) {
  49812. // Sort Polygons, since subMeshes are indices range
  49813. polygons.sort(function (a, b) {
  49814. if (a.shared.meshId === b.shared.meshId) {
  49815. return a.shared.subMeshId - b.shared.subMeshId;
  49816. }
  49817. else {
  49818. return a.shared.meshId - b.shared.meshId;
  49819. }
  49820. });
  49821. }
  49822. for (var i = 0, il = polygons.length; i < il; i++) {
  49823. polygon = polygons[i];
  49824. // Building SubMeshes
  49825. if (!subMesh_dict[polygon.shared.meshId]) {
  49826. subMesh_dict[polygon.shared.meshId] = {};
  49827. }
  49828. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  49829. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  49830. indexStart: +Infinity,
  49831. indexEnd: -Infinity,
  49832. materialIndex: polygon.shared.materialIndex
  49833. };
  49834. }
  49835. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  49836. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  49837. polygonIndices[0] = 0;
  49838. polygonIndices[1] = j - 1;
  49839. polygonIndices[2] = j;
  49840. for (var k = 0; k < 3; k++) {
  49841. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  49842. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  49843. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  49844. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  49845. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  49846. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  49847. // Check if 2 points can be merged
  49848. if (!(typeof vertex_idx !== 'undefined' &&
  49849. normals[vertex_idx * 3] === localNormal.x &&
  49850. normals[vertex_idx * 3 + 1] === localNormal.y &&
  49851. normals[vertex_idx * 3 + 2] === localNormal.z &&
  49852. uvs[vertex_idx * 2] === uv.x &&
  49853. uvs[vertex_idx * 2 + 1] === uv.y)) {
  49854. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  49855. uvs.push(uv.x, uv.y);
  49856. normals.push(normal.x, normal.y, normal.z);
  49857. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  49858. }
  49859. indices.push(vertex_idx);
  49860. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  49861. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  49862. currentIndex++;
  49863. }
  49864. }
  49865. }
  49866. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  49867. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  49868. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  49869. mesh.setIndices(indices);
  49870. if (keepSubMeshes) {
  49871. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  49872. var materialIndexOffset = 0, materialMaxIndex;
  49873. mesh.subMeshes = new Array();
  49874. for (var m in subMesh_dict) {
  49875. materialMaxIndex = -1;
  49876. for (var sm in subMesh_dict[m]) {
  49877. subMesh_obj = subMesh_dict[m][sm];
  49878. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  49879. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  49880. }
  49881. materialIndexOffset += ++materialMaxIndex;
  49882. }
  49883. }
  49884. return mesh;
  49885. };
  49886. // Build Mesh from CSG taking material and transforms into account
  49887. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  49888. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  49889. mesh.material = material;
  49890. mesh.position.copyFrom(this.position);
  49891. mesh.rotation.copyFrom(this.rotation);
  49892. if (this.rotationQuaternion) {
  49893. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  49894. }
  49895. mesh.scaling.copyFrom(this.scaling);
  49896. mesh.computeWorldMatrix(true);
  49897. return mesh;
  49898. };
  49899. return CSG;
  49900. }());
  49901. BABYLON.CSG = CSG;
  49902. })(BABYLON || (BABYLON = {}));
  49903. //# sourceMappingURL=babylon.csg.js.map
  49904. var BABYLON;
  49905. (function (BABYLON) {
  49906. var VRDistortionCorrectionPostProcess = (function (_super) {
  49907. __extends(VRDistortionCorrectionPostProcess, _super);
  49908. //ANY
  49909. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  49910. var _this = _super.call(this, name, "vrDistortionCorrection", [
  49911. 'LensCenter',
  49912. 'Scale',
  49913. 'ScaleIn',
  49914. 'HmdWarpParam'
  49915. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  49916. _this._isRightEye = isRightEye;
  49917. _this._distortionFactors = vrMetrics.distortionK;
  49918. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  49919. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  49920. _this.onSizeChangedObservable.add(function () {
  49921. _this.aspectRatio = _this.width * .5 / _this.height;
  49922. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  49923. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  49924. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  49925. });
  49926. _this.onApplyObservable.add(function (effect) {
  49927. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  49928. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  49929. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  49930. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  49931. });
  49932. return _this;
  49933. }
  49934. return VRDistortionCorrectionPostProcess;
  49935. }(BABYLON.PostProcess));
  49936. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  49937. })(BABYLON || (BABYLON = {}));
  49938. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  49939. // Mainly based on these 2 articles :
  49940. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  49941. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  49942. var BABYLON;
  49943. (function (BABYLON) {
  49944. var JoystickAxis;
  49945. (function (JoystickAxis) {
  49946. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  49947. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  49948. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  49949. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  49950. var VirtualJoystick = (function () {
  49951. function VirtualJoystick(leftJoystick) {
  49952. var _this = this;
  49953. if (leftJoystick) {
  49954. this._leftJoystick = true;
  49955. }
  49956. else {
  49957. this._leftJoystick = false;
  49958. }
  49959. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  49960. VirtualJoystick._globalJoystickIndex++;
  49961. // By default left & right arrow keys are moving the X
  49962. // and up & down keys are moving the Y
  49963. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  49964. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  49965. this.reverseLeftRight = false;
  49966. this.reverseUpDown = false;
  49967. // collections of pointers
  49968. this._touches = new BABYLON.StringDictionary();
  49969. this.deltaPosition = BABYLON.Vector3.Zero();
  49970. this._joystickSensibility = 25;
  49971. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  49972. this._rotationSpeed = 25;
  49973. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  49974. this._rotateOnAxisRelativeToMesh = false;
  49975. this._onResize = function (evt) {
  49976. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49977. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49978. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  49979. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  49980. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  49981. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  49982. };
  49983. // injecting a canvas element on top of the canvas 3D game
  49984. if (!VirtualJoystick.vjCanvas) {
  49985. window.addEventListener("resize", this._onResize, false);
  49986. VirtualJoystick.vjCanvas = document.createElement("canvas");
  49987. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  49988. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  49989. VirtualJoystick.vjCanvas.width = window.innerWidth;
  49990. VirtualJoystick.vjCanvas.height = window.innerHeight;
  49991. VirtualJoystick.vjCanvas.style.width = "100%";
  49992. VirtualJoystick.vjCanvas.style.height = "100%";
  49993. VirtualJoystick.vjCanvas.style.position = "absolute";
  49994. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  49995. VirtualJoystick.vjCanvas.style.top = "0px";
  49996. VirtualJoystick.vjCanvas.style.left = "0px";
  49997. VirtualJoystick.vjCanvas.style.zIndex = "5";
  49998. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  49999. // Support for jQuery PEP polyfill
  50000. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  50001. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  50002. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  50003. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50004. document.body.appendChild(VirtualJoystick.vjCanvas);
  50005. }
  50006. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  50007. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  50008. this.pressed = false;
  50009. // default joystick color
  50010. this._joystickColor = "cyan";
  50011. this._joystickPointerID = -1;
  50012. // current joystick position
  50013. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  50014. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  50015. // origin joystick position
  50016. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  50017. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  50018. this._onPointerDownHandlerRef = function (evt) {
  50019. _this._onPointerDown(evt);
  50020. };
  50021. this._onPointerMoveHandlerRef = function (evt) {
  50022. _this._onPointerMove(evt);
  50023. };
  50024. this._onPointerOutHandlerRef = function (evt) {
  50025. _this._onPointerUp(evt);
  50026. };
  50027. this._onPointerUpHandlerRef = function (evt) {
  50028. _this._onPointerUp(evt);
  50029. };
  50030. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  50031. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  50032. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  50033. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  50034. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  50035. evt.preventDefault(); // Disables system menu
  50036. }, false);
  50037. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50038. }
  50039. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  50040. this._joystickSensibility = newJoystickSensibility;
  50041. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50042. };
  50043. VirtualJoystick.prototype._onPointerDown = function (e) {
  50044. var positionOnScreenCondition;
  50045. e.preventDefault();
  50046. if (this._leftJoystick === true) {
  50047. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  50048. }
  50049. else {
  50050. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  50051. }
  50052. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  50053. // First contact will be dedicated to the virtual joystick
  50054. this._joystickPointerID = e.pointerId;
  50055. this._joystickPointerStartPos.x = e.clientX;
  50056. this._joystickPointerStartPos.y = e.clientY;
  50057. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  50058. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  50059. this._deltaJoystickVector.x = 0;
  50060. this._deltaJoystickVector.y = 0;
  50061. this.pressed = true;
  50062. this._touches.add(e.pointerId.toString(), e);
  50063. }
  50064. else {
  50065. // You can only trigger the action buttons with a joystick declared
  50066. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  50067. this._action();
  50068. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  50069. }
  50070. }
  50071. };
  50072. VirtualJoystick.prototype._onPointerMove = function (e) {
  50073. // If the current pointer is the one associated to the joystick (first touch contact)
  50074. if (this._joystickPointerID == e.pointerId) {
  50075. this._joystickPointerPos.x = e.clientX;
  50076. this._joystickPointerPos.y = e.clientY;
  50077. this._deltaJoystickVector = this._joystickPointerPos.clone();
  50078. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  50079. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  50080. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  50081. switch (this._axisTargetedByLeftAndRight) {
  50082. case JoystickAxis.X:
  50083. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  50084. break;
  50085. case JoystickAxis.Y:
  50086. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  50087. break;
  50088. case JoystickAxis.Z:
  50089. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  50090. break;
  50091. }
  50092. var directionUpDown = this.reverseUpDown ? 1 : -1;
  50093. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  50094. switch (this._axisTargetedByUpAndDown) {
  50095. case JoystickAxis.X:
  50096. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  50097. break;
  50098. case JoystickAxis.Y:
  50099. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  50100. break;
  50101. case JoystickAxis.Z:
  50102. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  50103. break;
  50104. }
  50105. }
  50106. else {
  50107. var data = this._touches.get(e.pointerId.toString());
  50108. if (data) {
  50109. data.x = e.clientX;
  50110. data.y = e.clientY;
  50111. }
  50112. }
  50113. };
  50114. VirtualJoystick.prototype._onPointerUp = function (e) {
  50115. if (this._joystickPointerID == e.pointerId) {
  50116. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  50117. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  50118. this._joystickPointerID = -1;
  50119. this.pressed = false;
  50120. }
  50121. else {
  50122. var touch = this._touches.get(e.pointerId.toString());
  50123. if (touch) {
  50124. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  50125. }
  50126. }
  50127. this._deltaJoystickVector.x = 0;
  50128. this._deltaJoystickVector.y = 0;
  50129. this._touches.remove(e.pointerId.toString());
  50130. };
  50131. /**
  50132. * Change the color of the virtual joystick
  50133. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  50134. */
  50135. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  50136. this._joystickColor = newColor;
  50137. };
  50138. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  50139. this._action = action;
  50140. };
  50141. // Define which axis you'd like to control for left & right
  50142. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  50143. switch (axis) {
  50144. case JoystickAxis.X:
  50145. case JoystickAxis.Y:
  50146. case JoystickAxis.Z:
  50147. this._axisTargetedByLeftAndRight = axis;
  50148. break;
  50149. default:
  50150. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50151. break;
  50152. }
  50153. };
  50154. // Define which axis you'd like to control for up & down
  50155. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  50156. switch (axis) {
  50157. case JoystickAxis.X:
  50158. case JoystickAxis.Y:
  50159. case JoystickAxis.Z:
  50160. this._axisTargetedByUpAndDown = axis;
  50161. break;
  50162. default:
  50163. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50164. break;
  50165. }
  50166. };
  50167. VirtualJoystick.prototype._clearCanvas = function () {
  50168. if (this._leftJoystick) {
  50169. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  50170. }
  50171. else {
  50172. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  50173. }
  50174. };
  50175. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  50176. var _this = this;
  50177. if (this.pressed) {
  50178. this._touches.forEach(function (key, touch) {
  50179. if (touch.pointerId === _this._joystickPointerID) {
  50180. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  50181. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  50182. VirtualJoystick.vjCanvasContext.beginPath();
  50183. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50184. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50185. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  50186. VirtualJoystick.vjCanvasContext.stroke();
  50187. VirtualJoystick.vjCanvasContext.closePath();
  50188. VirtualJoystick.vjCanvasContext.beginPath();
  50189. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50190. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50191. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  50192. VirtualJoystick.vjCanvasContext.stroke();
  50193. VirtualJoystick.vjCanvasContext.closePath();
  50194. VirtualJoystick.vjCanvasContext.beginPath();
  50195. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50196. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  50197. VirtualJoystick.vjCanvasContext.stroke();
  50198. VirtualJoystick.vjCanvasContext.closePath();
  50199. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  50200. }
  50201. else {
  50202. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  50203. VirtualJoystick.vjCanvasContext.beginPath();
  50204. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  50205. VirtualJoystick.vjCanvasContext.beginPath();
  50206. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  50207. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50208. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  50209. VirtualJoystick.vjCanvasContext.stroke();
  50210. VirtualJoystick.vjCanvasContext.closePath();
  50211. touch.prevX = touch.x;
  50212. touch.prevY = touch.y;
  50213. }
  50214. ;
  50215. });
  50216. }
  50217. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50218. };
  50219. VirtualJoystick.prototype.releaseCanvas = function () {
  50220. if (VirtualJoystick.vjCanvas) {
  50221. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  50222. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  50223. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  50224. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  50225. window.removeEventListener("resize", this._onResize);
  50226. document.body.removeChild(VirtualJoystick.vjCanvas);
  50227. VirtualJoystick.vjCanvas = null;
  50228. }
  50229. };
  50230. return VirtualJoystick;
  50231. }());
  50232. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  50233. VirtualJoystick._globalJoystickIndex = 0;
  50234. BABYLON.VirtualJoystick = VirtualJoystick;
  50235. })(BABYLON || (BABYLON = {}));
  50236. //# sourceMappingURL=babylon.virtualJoystick.js.map
  50237. var BABYLON;
  50238. (function (BABYLON) {
  50239. // We're mainly based on the logic defined into the FreeCamera code
  50240. var VirtualJoysticksCamera = (function (_super) {
  50241. __extends(VirtualJoysticksCamera, _super);
  50242. function VirtualJoysticksCamera(name, position, scene) {
  50243. var _this = _super.call(this, name, position, scene) || this;
  50244. _this.inputs.addVirtualJoystick();
  50245. return _this;
  50246. }
  50247. VirtualJoysticksCamera.prototype.getClassName = function () {
  50248. return "VirtualJoysticksCamera";
  50249. };
  50250. return VirtualJoysticksCamera;
  50251. }(BABYLON.FreeCamera));
  50252. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  50253. })(BABYLON || (BABYLON = {}));
  50254. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  50255. var BABYLON;
  50256. (function (BABYLON) {
  50257. var FreeCameraVirtualJoystickInput = (function () {
  50258. function FreeCameraVirtualJoystickInput() {
  50259. }
  50260. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  50261. return this._leftjoystick;
  50262. };
  50263. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  50264. return this._rightjoystick;
  50265. };
  50266. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  50267. if (this._leftjoystick) {
  50268. var camera = this.camera;
  50269. var speed = camera._computeLocalCameraSpeed() * 50;
  50270. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  50271. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  50272. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  50273. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  50274. if (!this._leftjoystick.pressed) {
  50275. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  50276. }
  50277. if (!this._rightjoystick.pressed) {
  50278. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  50279. }
  50280. }
  50281. };
  50282. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  50283. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  50284. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  50285. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  50286. this._leftjoystick.setJoystickSensibility(0.15);
  50287. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  50288. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  50289. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  50290. this._rightjoystick.reverseUpDown = true;
  50291. this._rightjoystick.setJoystickSensibility(0.05);
  50292. this._rightjoystick.setJoystickColor("yellow");
  50293. };
  50294. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  50295. this._leftjoystick.releaseCanvas();
  50296. this._rightjoystick.releaseCanvas();
  50297. };
  50298. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  50299. return "FreeCameraVirtualJoystickInput";
  50300. };
  50301. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  50302. return "virtualJoystick";
  50303. };
  50304. return FreeCameraVirtualJoystickInput;
  50305. }());
  50306. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  50307. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  50308. })(BABYLON || (BABYLON = {}));
  50309. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  50310. var BABYLON;
  50311. (function (BABYLON) {
  50312. var AnaglyphPostProcess = (function (_super) {
  50313. __extends(AnaglyphPostProcess, _super);
  50314. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  50315. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  50316. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50317. _this.onApplyObservable.add(function (effect) {
  50318. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  50319. });
  50320. return _this;
  50321. }
  50322. return AnaglyphPostProcess;
  50323. }(BABYLON.PostProcess));
  50324. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  50325. })(BABYLON || (BABYLON = {}));
  50326. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  50327. var BABYLON;
  50328. (function (BABYLON) {
  50329. var OutlineRenderer = (function () {
  50330. function OutlineRenderer(scene) {
  50331. this._scene = scene;
  50332. }
  50333. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  50334. var _this = this;
  50335. if (useOverlay === void 0) { useOverlay = false; }
  50336. var scene = this._scene;
  50337. var engine = this._scene.getEngine();
  50338. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50339. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  50340. return;
  50341. }
  50342. var mesh = subMesh.getRenderingMesh();
  50343. var material = subMesh.getMaterial();
  50344. engine.enableEffect(this._effect);
  50345. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  50346. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  50347. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50348. // Bones
  50349. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50350. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50351. }
  50352. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50353. // Alpha test
  50354. if (material && material.needAlphaTesting()) {
  50355. var alphaTexture = material.getAlphaTestTexture();
  50356. this._effect.setTexture("diffuseSampler", alphaTexture);
  50357. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50358. }
  50359. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  50360. };
  50361. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  50362. var defines = [];
  50363. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50364. var mesh = subMesh.getMesh();
  50365. var material = subMesh.getMaterial();
  50366. // Alpha test
  50367. if (material && material.needAlphaTesting()) {
  50368. defines.push("#define ALPHATEST");
  50369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50370. attribs.push(BABYLON.VertexBuffer.UVKind);
  50371. defines.push("#define UV1");
  50372. }
  50373. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50374. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50375. defines.push("#define UV2");
  50376. }
  50377. }
  50378. // Bones
  50379. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50382. if (mesh.numBoneInfluencers > 4) {
  50383. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50384. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50385. }
  50386. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50387. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50388. }
  50389. else {
  50390. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50391. }
  50392. // Instances
  50393. if (useInstances) {
  50394. defines.push("#define INSTANCES");
  50395. attribs.push("world0");
  50396. attribs.push("world1");
  50397. attribs.push("world2");
  50398. attribs.push("world3");
  50399. }
  50400. // Get correct effect
  50401. var join = defines.join("\n");
  50402. if (this._cachedDefines !== join) {
  50403. this._cachedDefines = join;
  50404. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  50405. }
  50406. return this._effect.isReady();
  50407. };
  50408. return OutlineRenderer;
  50409. }());
  50410. BABYLON.OutlineRenderer = OutlineRenderer;
  50411. })(BABYLON || (BABYLON = {}));
  50412. //# sourceMappingURL=babylon.outlineRenderer.js.map
  50413. var BABYLON;
  50414. (function (BABYLON) {
  50415. var MeshAssetTask = (function () {
  50416. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  50417. this.name = name;
  50418. this.meshesNames = meshesNames;
  50419. this.rootUrl = rootUrl;
  50420. this.sceneFilename = sceneFilename;
  50421. this.isCompleted = false;
  50422. }
  50423. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50424. var _this = this;
  50425. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  50426. _this.loadedMeshes = meshes;
  50427. _this.loadedParticleSystems = particleSystems;
  50428. _this.loadedSkeletons = skeletons;
  50429. _this.isCompleted = true;
  50430. if (_this.onSuccess) {
  50431. _this.onSuccess(_this);
  50432. }
  50433. onSuccess();
  50434. }, null, function () {
  50435. if (_this.onError) {
  50436. _this.onError(_this);
  50437. }
  50438. onError();
  50439. });
  50440. };
  50441. return MeshAssetTask;
  50442. }());
  50443. BABYLON.MeshAssetTask = MeshAssetTask;
  50444. var TextFileAssetTask = (function () {
  50445. function TextFileAssetTask(name, url) {
  50446. this.name = name;
  50447. this.url = url;
  50448. this.isCompleted = false;
  50449. }
  50450. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50451. var _this = this;
  50452. BABYLON.Tools.LoadFile(this.url, function (data) {
  50453. _this.text = data;
  50454. _this.isCompleted = true;
  50455. if (_this.onSuccess) {
  50456. _this.onSuccess(_this);
  50457. }
  50458. onSuccess();
  50459. }, null, scene.database, false, function () {
  50460. if (_this.onError) {
  50461. _this.onError(_this);
  50462. }
  50463. onError();
  50464. });
  50465. };
  50466. return TextFileAssetTask;
  50467. }());
  50468. BABYLON.TextFileAssetTask = TextFileAssetTask;
  50469. var BinaryFileAssetTask = (function () {
  50470. function BinaryFileAssetTask(name, url) {
  50471. this.name = name;
  50472. this.url = url;
  50473. this.isCompleted = false;
  50474. }
  50475. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50476. var _this = this;
  50477. BABYLON.Tools.LoadFile(this.url, function (data) {
  50478. _this.data = data;
  50479. _this.isCompleted = true;
  50480. if (_this.onSuccess) {
  50481. _this.onSuccess(_this);
  50482. }
  50483. onSuccess();
  50484. }, null, scene.database, true, function () {
  50485. if (_this.onError) {
  50486. _this.onError(_this);
  50487. }
  50488. onError();
  50489. });
  50490. };
  50491. return BinaryFileAssetTask;
  50492. }());
  50493. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  50494. var ImageAssetTask = (function () {
  50495. function ImageAssetTask(name, url) {
  50496. this.name = name;
  50497. this.url = url;
  50498. this.isCompleted = false;
  50499. }
  50500. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50501. var _this = this;
  50502. var img = new Image();
  50503. BABYLON.Tools.SetCorsBehavior(this.url, img);
  50504. img.onload = function () {
  50505. _this.image = img;
  50506. _this.isCompleted = true;
  50507. if (_this.onSuccess) {
  50508. _this.onSuccess(_this);
  50509. }
  50510. onSuccess();
  50511. };
  50512. img.onerror = function () {
  50513. if (_this.onError) {
  50514. _this.onError(_this);
  50515. }
  50516. onError();
  50517. };
  50518. img.src = this.url;
  50519. };
  50520. return ImageAssetTask;
  50521. }());
  50522. BABYLON.ImageAssetTask = ImageAssetTask;
  50523. var TextureAssetTask = (function () {
  50524. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  50525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50526. this.name = name;
  50527. this.url = url;
  50528. this.noMipmap = noMipmap;
  50529. this.invertY = invertY;
  50530. this.samplingMode = samplingMode;
  50531. this.isCompleted = false;
  50532. }
  50533. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50534. var _this = this;
  50535. var onload = function () {
  50536. _this.isCompleted = true;
  50537. if (_this.onSuccess) {
  50538. _this.onSuccess(_this);
  50539. }
  50540. onSuccess();
  50541. };
  50542. var onerror = function () {
  50543. if (_this.onError) {
  50544. _this.onError(_this);
  50545. }
  50546. onError();
  50547. };
  50548. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  50549. };
  50550. return TextureAssetTask;
  50551. }());
  50552. BABYLON.TextureAssetTask = TextureAssetTask;
  50553. var CubeTextureAssetTask = (function () {
  50554. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  50555. this.name = name;
  50556. this.url = url;
  50557. this.extensions = extensions;
  50558. this.noMipmap = noMipmap;
  50559. this.files = files;
  50560. this.isCompleted = false;
  50561. }
  50562. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50563. var _this = this;
  50564. var onload = function () {
  50565. _this.isCompleted = true;
  50566. if (_this.onSuccess) {
  50567. _this.onSuccess(_this);
  50568. }
  50569. onSuccess();
  50570. };
  50571. var onerror = function () {
  50572. if (_this.onError) {
  50573. _this.onError(_this);
  50574. }
  50575. onError();
  50576. };
  50577. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  50578. };
  50579. return CubeTextureAssetTask;
  50580. }());
  50581. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  50582. var HDRCubeTextureAssetTask = (function () {
  50583. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50584. if (noMipmap === void 0) { noMipmap = false; }
  50585. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50586. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50587. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50588. this.name = name;
  50589. this.url = url;
  50590. this.size = size;
  50591. this.noMipmap = noMipmap;
  50592. this.generateHarmonics = generateHarmonics;
  50593. this.useInGammaSpace = useInGammaSpace;
  50594. this.usePMREMGenerator = usePMREMGenerator;
  50595. this.isCompleted = false;
  50596. }
  50597. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50598. var _this = this;
  50599. var onload = function () {
  50600. _this.isCompleted = true;
  50601. if (_this.onSuccess) {
  50602. _this.onSuccess(_this);
  50603. }
  50604. onSuccess();
  50605. };
  50606. var onerror = function () {
  50607. if (_this.onError) {
  50608. _this.onError(_this);
  50609. }
  50610. onError();
  50611. };
  50612. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  50613. };
  50614. return HDRCubeTextureAssetTask;
  50615. }());
  50616. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  50617. var AssetsManager = (function () {
  50618. function AssetsManager(scene) {
  50619. this.tasks = new Array();
  50620. this.waitingTasksCount = 0;
  50621. this.useDefaultLoadingScreen = true;
  50622. this._scene = scene;
  50623. }
  50624. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  50625. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  50626. this.tasks.push(task);
  50627. return task;
  50628. };
  50629. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  50630. var task = new TextFileAssetTask(taskName, url);
  50631. this.tasks.push(task);
  50632. return task;
  50633. };
  50634. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  50635. var task = new BinaryFileAssetTask(taskName, url);
  50636. this.tasks.push(task);
  50637. return task;
  50638. };
  50639. AssetsManager.prototype.addImageTask = function (taskName, url) {
  50640. var task = new ImageAssetTask(taskName, url);
  50641. this.tasks.push(task);
  50642. return task;
  50643. };
  50644. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  50645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50646. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  50647. this.tasks.push(task);
  50648. return task;
  50649. };
  50650. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  50651. this.waitingTasksCount--;
  50652. if (this.waitingTasksCount === 0) {
  50653. if (this.onFinish) {
  50654. this.onFinish(this.tasks);
  50655. }
  50656. this._scene.getEngine().hideLoadingUI();
  50657. }
  50658. };
  50659. AssetsManager.prototype._runTask = function (task) {
  50660. var _this = this;
  50661. task.run(this._scene, function () {
  50662. if (_this.onTaskSuccess) {
  50663. _this.onTaskSuccess(task);
  50664. }
  50665. _this._decreaseWaitingTasksCount();
  50666. }, function () {
  50667. if (_this.onTaskError) {
  50668. _this.onTaskError(task);
  50669. }
  50670. _this._decreaseWaitingTasksCount();
  50671. });
  50672. };
  50673. AssetsManager.prototype.reset = function () {
  50674. this.tasks = new Array();
  50675. return this;
  50676. };
  50677. AssetsManager.prototype.load = function () {
  50678. this.waitingTasksCount = this.tasks.length;
  50679. if (this.waitingTasksCount === 0) {
  50680. if (this.onFinish) {
  50681. this.onFinish(this.tasks);
  50682. }
  50683. return this;
  50684. }
  50685. if (this.useDefaultLoadingScreen) {
  50686. this._scene.getEngine().displayLoadingUI();
  50687. }
  50688. for (var index = 0; index < this.tasks.length; index++) {
  50689. var task = this.tasks[index];
  50690. this._runTask(task);
  50691. }
  50692. return this;
  50693. };
  50694. return AssetsManager;
  50695. }());
  50696. BABYLON.AssetsManager = AssetsManager;
  50697. })(BABYLON || (BABYLON = {}));
  50698. //# sourceMappingURL=babylon.assetsManager.js.map
  50699. var BABYLON;
  50700. (function (BABYLON) {
  50701. var VRCameraMetrics = (function () {
  50702. function VRCameraMetrics() {
  50703. this.compensateDistortion = true;
  50704. }
  50705. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  50706. get: function () {
  50707. return this.hResolution / (2 * this.vResolution);
  50708. },
  50709. enumerable: true,
  50710. configurable: true
  50711. });
  50712. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  50713. get: function () {
  50714. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  50715. },
  50716. enumerable: true,
  50717. configurable: true
  50718. });
  50719. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  50720. get: function () {
  50721. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50722. var h = (4 * meters) / this.hScreenSize;
  50723. return BABYLON.Matrix.Translation(h, 0, 0);
  50724. },
  50725. enumerable: true,
  50726. configurable: true
  50727. });
  50728. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  50729. get: function () {
  50730. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  50731. var h = (4 * meters) / this.hScreenSize;
  50732. return BABYLON.Matrix.Translation(-h, 0, 0);
  50733. },
  50734. enumerable: true,
  50735. configurable: true
  50736. });
  50737. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  50738. get: function () {
  50739. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  50740. },
  50741. enumerable: true,
  50742. configurable: true
  50743. });
  50744. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  50745. get: function () {
  50746. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  50747. },
  50748. enumerable: true,
  50749. configurable: true
  50750. });
  50751. VRCameraMetrics.GetDefault = function () {
  50752. var result = new VRCameraMetrics();
  50753. result.hResolution = 1280;
  50754. result.vResolution = 800;
  50755. result.hScreenSize = 0.149759993;
  50756. result.vScreenSize = 0.0935999975;
  50757. result.vScreenCenter = 0.0467999987;
  50758. result.eyeToScreenDistance = 0.0410000011;
  50759. result.lensSeparationDistance = 0.0635000020;
  50760. result.interpupillaryDistance = 0.0640000030;
  50761. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  50762. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  50763. result.postProcessScaleFactor = 1.714605507808412;
  50764. result.lensCenterOffset = 0.151976421;
  50765. return result;
  50766. };
  50767. return VRCameraMetrics;
  50768. }());
  50769. BABYLON.VRCameraMetrics = VRCameraMetrics;
  50770. })(BABYLON || (BABYLON = {}));
  50771. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  50772. var BABYLON;
  50773. (function (BABYLON) {
  50774. var WebVRFreeCamera = (function (_super) {
  50775. __extends(WebVRFreeCamera, _super);
  50776. function WebVRFreeCamera(name, position, scene, webVROptions) {
  50777. if (webVROptions === void 0) { webVROptions = {}; }
  50778. var _this = _super.call(this, name, position, scene) || this;
  50779. _this.webVROptions = webVROptions;
  50780. _this._vrDevice = null;
  50781. _this.rawPose = null;
  50782. _this._vrEnabled = false;
  50783. _this._specsVersion = 1.1;
  50784. _this._attached = false;
  50785. _this._positionOffset = BABYLON.Vector3.Zero();
  50786. _this._descendants = [];
  50787. _this.devicePosition = BABYLON.Vector3.Zero();
  50788. _this.deviceScaleFactor = 1;
  50789. _this.controllers = [];
  50790. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  50791. //legacy support - the compensation boolean was removed.
  50792. if (arguments.length === 5) {
  50793. _this.webVROptions = arguments[4];
  50794. }
  50795. // default webVR options
  50796. if (_this.webVROptions.trackPosition == undefined) {
  50797. _this.webVROptions.trackPosition = true;
  50798. }
  50799. if (_this.webVROptions.controllerMeshes == undefined) {
  50800. _this.webVROptions.controllerMeshes = true;
  50801. }
  50802. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  50803. _this.webVROptions.defaultLightningOnControllers = true;
  50804. }
  50805. _this.rotationQuaternion = new BABYLON.Quaternion();
  50806. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50807. if (_this.webVROptions && _this.webVROptions.positionScale) {
  50808. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  50809. }
  50810. //enable VR
  50811. _this.getEngine().initWebVR();
  50812. if (!_this.getEngine().vrDisplaysPromise) {
  50813. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  50814. }
  50815. else {
  50816. //check specs version
  50817. if (!window.VRFrameData) {
  50818. _this._specsVersion = 1.0;
  50819. _this._frameData = {};
  50820. }
  50821. else {
  50822. _this._frameData = new VRFrameData();
  50823. }
  50824. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  50825. if (devices.length > 0) {
  50826. _this._vrEnabled = true;
  50827. if (_this.webVROptions.displayName) {
  50828. var found = devices.some(function (device) {
  50829. if (device.displayName === _this.webVROptions.displayName) {
  50830. _this._vrDevice = device;
  50831. return true;
  50832. }
  50833. else {
  50834. return false;
  50835. }
  50836. });
  50837. if (!found) {
  50838. _this._vrDevice = devices[0];
  50839. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  50840. }
  50841. }
  50842. else {
  50843. //choose the first one
  50844. _this._vrDevice = devices[0];
  50845. }
  50846. //reset the rig parameters.
  50847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  50848. if (_this._attached) {
  50849. _this.getEngine().enableVR(_this._vrDevice);
  50850. }
  50851. }
  50852. else {
  50853. BABYLON.Tools.Error("No WebVR devices found!");
  50854. }
  50855. });
  50856. }
  50857. // try to attach the controllers, if found.
  50858. _this.initControllers();
  50859. /**
  50860. * The idea behind the following lines:
  50861. * objects that have the camera as parent should actually have the rig cameras as a parent.
  50862. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  50863. * the second will not show it correctly.
  50864. *
  50865. * To solve this - each object that has the camera as parent will be added to a protected array.
  50866. * When the rig camera renders, it will take this array and set all of those to be its children.
  50867. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  50868. * Amazing!
  50869. */
  50870. scene.onBeforeCameraRenderObservable.add(function (camera) {
  50871. if (camera.parent === _this && _this.rigParenting) {
  50872. _this._descendants = _this.getDescendants(true, function (n) {
  50873. // don't take the cameras or the controllers!
  50874. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  50875. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  50876. return !isController && !isRigCamera;
  50877. });
  50878. _this._descendants.forEach(function (node) {
  50879. node.parent = camera;
  50880. });
  50881. }
  50882. });
  50883. scene.onAfterCameraRenderObservable.add(function (camera) {
  50884. if (camera.parent === _this && _this.rigParenting) {
  50885. _this._descendants.forEach(function (node) {
  50886. node.parent = _this;
  50887. });
  50888. }
  50889. });
  50890. return _this;
  50891. }
  50892. WebVRFreeCamera.prototype._checkInputs = function () {
  50893. if (this._vrEnabled) {
  50894. if (this._specsVersion === 1.1) {
  50895. this._vrDevice.getFrameData(this._frameData);
  50896. }
  50897. else {
  50898. //backwards comp
  50899. var pose = this._vrDevice.getPose();
  50900. this._frameData.pose = pose;
  50901. // calculate view and projection matrix
  50902. }
  50903. this.updateFromDevice(this._frameData.pose);
  50904. }
  50905. _super.prototype._checkInputs.call(this);
  50906. };
  50907. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  50908. if (poseData && poseData.orientation) {
  50909. this.rawPose = poseData;
  50910. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50911. if (this.getScene().useRightHandedSystem) {
  50912. this.deviceRotationQuaternion.z *= -1;
  50913. this.deviceRotationQuaternion.w *= -1;
  50914. }
  50915. if (this.webVROptions.trackPosition && this.rawPose.position) {
  50916. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  50917. if (this.getScene().useRightHandedSystem) {
  50918. this.devicePosition.z *= -1;
  50919. }
  50920. }
  50921. }
  50922. };
  50923. /**
  50924. * WebVR's attach control will start broadcasting frames to the device.
  50925. * Note that in certain browsers (chrome for example) this function must be called
  50926. * within a user-interaction callback. Example:
  50927. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  50928. *
  50929. * @param {HTMLElement} element
  50930. * @param {boolean} [noPreventDefault]
  50931. *
  50932. * @memberOf WebVRFreeCamera
  50933. */
  50934. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  50935. _super.prototype.attachControl.call(this, element, noPreventDefault);
  50936. this._attached = true;
  50937. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  50938. if (this._vrEnabled) {
  50939. this.getEngine().enableVR(this._vrDevice);
  50940. }
  50941. };
  50942. WebVRFreeCamera.prototype.detachControl = function (element) {
  50943. _super.prototype.detachControl.call(this, element);
  50944. this._vrEnabled = false;
  50945. this._attached = false;
  50946. this.getEngine().disableVR();
  50947. };
  50948. WebVRFreeCamera.prototype.getClassName = function () {
  50949. return "WebVRFreeCamera";
  50950. };
  50951. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  50952. //uses the vrDisplay's "resetPose()".
  50953. //pitch and roll won't be affected.
  50954. this._vrDevice.resetPose();
  50955. };
  50956. WebVRFreeCamera.prototype._updateRigCameras = function () {
  50957. var camLeft = this._rigCameras[0];
  50958. var camRight = this._rigCameras[1];
  50959. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  50960. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  50961. camLeft.position.copyFrom(this.devicePosition);
  50962. camRight.position.copyFrom(this.devicePosition);
  50963. };
  50964. /**
  50965. * This function is called by the two RIG cameras.
  50966. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  50967. */
  50968. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  50969. var _this = this;
  50970. //WebVR 1.0
  50971. if (this._cameraRigParams["specs"] === 1.0) {
  50972. this._updateCameraRotationMatrix();
  50973. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  50974. // Computing target and final matrix
  50975. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  50976. if (this.getScene().useRightHandedSystem) {
  50977. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  50978. }
  50979. else {
  50980. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  50981. }
  50982. //now move the eye in the right direction
  50983. var eyeParams = this._cameraRigParams["eyeParameters"];
  50984. var offset = eyeParams.offset;
  50985. // it will actually always be 0, but just in case
  50986. if (this.getScene().useRightHandedSystem) {
  50987. offset[2] *= -1;
  50988. }
  50989. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  50990. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  50991. }
  50992. else {
  50993. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  50994. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  50995. if (!this.getScene().useRightHandedSystem) {
  50996. [2, 6, 8, 9, 14].forEach(function (num) {
  50997. _this._webvrViewMatrix.m[num] *= -1;
  50998. });
  50999. }
  51000. // update the camera rotation matrix
  51001. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  51002. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  51003. // Computing target and final matrix
  51004. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  51005. }
  51006. var parentCamera = this._cameraRigParams["parentCamera"];
  51007. // should the view matrix be updated with scale and position offset?
  51008. if (parentCamera.deviceScaleFactor !== 1) {
  51009. this._webvrViewMatrix.invert();
  51010. // scale the position, if set
  51011. if (parentCamera.deviceScaleFactor) {
  51012. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  51013. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  51014. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  51015. }
  51016. this._webvrViewMatrix.invert();
  51017. }
  51018. return this._webvrViewMatrix;
  51019. };
  51020. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  51021. var _this = this;
  51022. if (this._cameraRigParams["specs"] === 1.0) {
  51023. var eyeParams = this._cameraRigParams["eyeParameters"];
  51024. // deprecated!!
  51025. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  51026. }
  51027. else {
  51028. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  51029. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  51030. //babylon compatible matrix
  51031. if (!this.getScene().useRightHandedSystem) {
  51032. [8, 9, 10, 11].forEach(function (num) {
  51033. _this._projectionMatrix.m[num] *= -1;
  51034. });
  51035. }
  51036. }
  51037. return this._projectionMatrix;
  51038. };
  51039. WebVRFreeCamera.prototype.initControllers = function () {
  51040. var _this = this;
  51041. this.controllers = [];
  51042. new BABYLON.Gamepads(function (gp) {
  51043. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  51044. var webVrController = gp;
  51045. if (_this.webVROptions.controllerMeshes) {
  51046. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  51047. if (_this.webVROptions.defaultLightningOnControllers) {
  51048. if (!_this._lightOnControllers) {
  51049. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  51050. }
  51051. loadedMesh.getChildren().forEach(function (mesh) {
  51052. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  51053. });
  51054. }
  51055. });
  51056. }
  51057. webVrController.attachToPoseControlledCamera(_this);
  51058. // since this is async - sanity check. Is the controller already stored?
  51059. if (_this.controllers.indexOf(webVrController) === -1) {
  51060. //add to the controllers array
  51061. _this.controllers.push(webVrController);
  51062. //did we find enough controllers? Great! let the developer know.
  51063. if (_this.onControllersAttached && _this.controllers.length === 2) {
  51064. _this.onControllersAttached(_this.controllers);
  51065. }
  51066. }
  51067. }
  51068. });
  51069. };
  51070. return WebVRFreeCamera;
  51071. }(BABYLON.FreeCamera));
  51072. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  51073. })(BABYLON || (BABYLON = {}));
  51074. //# sourceMappingURL=babylon.webVRCamera.js.map
  51075. var BABYLON;
  51076. (function (BABYLON) {
  51077. // Standard optimizations
  51078. var SceneOptimization = (function () {
  51079. function SceneOptimization(priority) {
  51080. if (priority === void 0) { priority = 0; }
  51081. this.priority = priority;
  51082. this.apply = function (scene) {
  51083. return true; // Return true if everything that can be done was applied
  51084. };
  51085. }
  51086. return SceneOptimization;
  51087. }());
  51088. BABYLON.SceneOptimization = SceneOptimization;
  51089. var TextureOptimization = (function (_super) {
  51090. __extends(TextureOptimization, _super);
  51091. function TextureOptimization(priority, maximumSize) {
  51092. if (priority === void 0) { priority = 0; }
  51093. if (maximumSize === void 0) { maximumSize = 1024; }
  51094. var _this = _super.call(this, priority) || this;
  51095. _this.priority = priority;
  51096. _this.maximumSize = maximumSize;
  51097. _this.apply = function (scene) {
  51098. var allDone = true;
  51099. for (var index = 0; index < scene.textures.length; index++) {
  51100. var texture = scene.textures[index];
  51101. if (!texture.canRescale) {
  51102. continue;
  51103. }
  51104. var currentSize = texture.getSize();
  51105. var maxDimension = Math.max(currentSize.width, currentSize.height);
  51106. if (maxDimension > _this.maximumSize) {
  51107. texture.scale(0.5);
  51108. allDone = false;
  51109. }
  51110. }
  51111. return allDone;
  51112. };
  51113. return _this;
  51114. }
  51115. return TextureOptimization;
  51116. }(SceneOptimization));
  51117. BABYLON.TextureOptimization = TextureOptimization;
  51118. var HardwareScalingOptimization = (function (_super) {
  51119. __extends(HardwareScalingOptimization, _super);
  51120. function HardwareScalingOptimization(priority, maximumScale) {
  51121. if (priority === void 0) { priority = 0; }
  51122. if (maximumScale === void 0) { maximumScale = 2; }
  51123. var _this = _super.call(this, priority) || this;
  51124. _this.priority = priority;
  51125. _this.maximumScale = maximumScale;
  51126. _this._currentScale = 1;
  51127. _this.apply = function (scene) {
  51128. _this._currentScale++;
  51129. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  51130. return _this._currentScale >= _this.maximumScale;
  51131. };
  51132. return _this;
  51133. }
  51134. return HardwareScalingOptimization;
  51135. }(SceneOptimization));
  51136. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  51137. var ShadowsOptimization = (function (_super) {
  51138. __extends(ShadowsOptimization, _super);
  51139. function ShadowsOptimization() {
  51140. var _this = _super !== null && _super.apply(this, arguments) || this;
  51141. _this.apply = function (scene) {
  51142. scene.shadowsEnabled = false;
  51143. return true;
  51144. };
  51145. return _this;
  51146. }
  51147. return ShadowsOptimization;
  51148. }(SceneOptimization));
  51149. BABYLON.ShadowsOptimization = ShadowsOptimization;
  51150. var PostProcessesOptimization = (function (_super) {
  51151. __extends(PostProcessesOptimization, _super);
  51152. function PostProcessesOptimization() {
  51153. var _this = _super !== null && _super.apply(this, arguments) || this;
  51154. _this.apply = function (scene) {
  51155. scene.postProcessesEnabled = false;
  51156. return true;
  51157. };
  51158. return _this;
  51159. }
  51160. return PostProcessesOptimization;
  51161. }(SceneOptimization));
  51162. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  51163. var LensFlaresOptimization = (function (_super) {
  51164. __extends(LensFlaresOptimization, _super);
  51165. function LensFlaresOptimization() {
  51166. var _this = _super !== null && _super.apply(this, arguments) || this;
  51167. _this.apply = function (scene) {
  51168. scene.lensFlaresEnabled = false;
  51169. return true;
  51170. };
  51171. return _this;
  51172. }
  51173. return LensFlaresOptimization;
  51174. }(SceneOptimization));
  51175. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  51176. var ParticlesOptimization = (function (_super) {
  51177. __extends(ParticlesOptimization, _super);
  51178. function ParticlesOptimization() {
  51179. var _this = _super !== null && _super.apply(this, arguments) || this;
  51180. _this.apply = function (scene) {
  51181. scene.particlesEnabled = false;
  51182. return true;
  51183. };
  51184. return _this;
  51185. }
  51186. return ParticlesOptimization;
  51187. }(SceneOptimization));
  51188. BABYLON.ParticlesOptimization = ParticlesOptimization;
  51189. var RenderTargetsOptimization = (function (_super) {
  51190. __extends(RenderTargetsOptimization, _super);
  51191. function RenderTargetsOptimization() {
  51192. var _this = _super !== null && _super.apply(this, arguments) || this;
  51193. _this.apply = function (scene) {
  51194. scene.renderTargetsEnabled = false;
  51195. return true;
  51196. };
  51197. return _this;
  51198. }
  51199. return RenderTargetsOptimization;
  51200. }(SceneOptimization));
  51201. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  51202. var MergeMeshesOptimization = (function (_super) {
  51203. __extends(MergeMeshesOptimization, _super);
  51204. function MergeMeshesOptimization() {
  51205. var _this = _super !== null && _super.apply(this, arguments) || this;
  51206. _this._canBeMerged = function (abstractMesh) {
  51207. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  51208. return false;
  51209. }
  51210. var mesh = abstractMesh;
  51211. if (!mesh.isVisible || !mesh.isEnabled()) {
  51212. return false;
  51213. }
  51214. if (mesh.instances.length > 0) {
  51215. return false;
  51216. }
  51217. if (mesh.skeleton || mesh.hasLODLevels) {
  51218. return false;
  51219. }
  51220. if (mesh.parent) {
  51221. return false;
  51222. }
  51223. return true;
  51224. };
  51225. _this.apply = function (scene, updateSelectionTree) {
  51226. var globalPool = scene.meshes.slice(0);
  51227. var globalLength = globalPool.length;
  51228. for (var index = 0; index < globalLength; index++) {
  51229. var currentPool = new Array();
  51230. var current = globalPool[index];
  51231. // Checks
  51232. if (!_this._canBeMerged(current)) {
  51233. continue;
  51234. }
  51235. currentPool.push(current);
  51236. // Find compatible meshes
  51237. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  51238. var otherMesh = globalPool[subIndex];
  51239. if (!_this._canBeMerged(otherMesh)) {
  51240. continue;
  51241. }
  51242. if (otherMesh.material !== current.material) {
  51243. continue;
  51244. }
  51245. if (otherMesh.checkCollisions !== current.checkCollisions) {
  51246. continue;
  51247. }
  51248. currentPool.push(otherMesh);
  51249. globalLength--;
  51250. globalPool.splice(subIndex, 1);
  51251. subIndex--;
  51252. }
  51253. if (currentPool.length < 2) {
  51254. continue;
  51255. }
  51256. // Merge meshes
  51257. BABYLON.Mesh.MergeMeshes(currentPool);
  51258. }
  51259. if (updateSelectionTree != undefined) {
  51260. if (updateSelectionTree) {
  51261. scene.createOrUpdateSelectionOctree();
  51262. }
  51263. }
  51264. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  51265. scene.createOrUpdateSelectionOctree();
  51266. }
  51267. return true;
  51268. };
  51269. return _this;
  51270. }
  51271. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  51272. get: function () {
  51273. return MergeMeshesOptimization._UpdateSelectionTree;
  51274. },
  51275. set: function (value) {
  51276. MergeMeshesOptimization._UpdateSelectionTree = value;
  51277. },
  51278. enumerable: true,
  51279. configurable: true
  51280. });
  51281. return MergeMeshesOptimization;
  51282. }(SceneOptimization));
  51283. MergeMeshesOptimization._UpdateSelectionTree = false;
  51284. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  51285. // Options
  51286. var SceneOptimizerOptions = (function () {
  51287. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  51288. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  51289. if (trackerDuration === void 0) { trackerDuration = 2000; }
  51290. this.targetFrameRate = targetFrameRate;
  51291. this.trackerDuration = trackerDuration;
  51292. this.optimizations = new Array();
  51293. }
  51294. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  51295. var result = new SceneOptimizerOptions(targetFrameRate);
  51296. var priority = 0;
  51297. result.optimizations.push(new MergeMeshesOptimization(priority));
  51298. result.optimizations.push(new ShadowsOptimization(priority));
  51299. result.optimizations.push(new LensFlaresOptimization(priority));
  51300. // Next priority
  51301. priority++;
  51302. result.optimizations.push(new PostProcessesOptimization(priority));
  51303. result.optimizations.push(new ParticlesOptimization(priority));
  51304. // Next priority
  51305. priority++;
  51306. result.optimizations.push(new TextureOptimization(priority, 1024));
  51307. return result;
  51308. };
  51309. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  51310. var result = new SceneOptimizerOptions(targetFrameRate);
  51311. var priority = 0;
  51312. result.optimizations.push(new MergeMeshesOptimization(priority));
  51313. result.optimizations.push(new ShadowsOptimization(priority));
  51314. result.optimizations.push(new LensFlaresOptimization(priority));
  51315. // Next priority
  51316. priority++;
  51317. result.optimizations.push(new PostProcessesOptimization(priority));
  51318. result.optimizations.push(new ParticlesOptimization(priority));
  51319. // Next priority
  51320. priority++;
  51321. result.optimizations.push(new TextureOptimization(priority, 512));
  51322. // Next priority
  51323. priority++;
  51324. result.optimizations.push(new RenderTargetsOptimization(priority));
  51325. // Next priority
  51326. priority++;
  51327. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  51328. return result;
  51329. };
  51330. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  51331. var result = new SceneOptimizerOptions(targetFrameRate);
  51332. var priority = 0;
  51333. result.optimizations.push(new MergeMeshesOptimization(priority));
  51334. result.optimizations.push(new ShadowsOptimization(priority));
  51335. result.optimizations.push(new LensFlaresOptimization(priority));
  51336. // Next priority
  51337. priority++;
  51338. result.optimizations.push(new PostProcessesOptimization(priority));
  51339. result.optimizations.push(new ParticlesOptimization(priority));
  51340. // Next priority
  51341. priority++;
  51342. result.optimizations.push(new TextureOptimization(priority, 256));
  51343. // Next priority
  51344. priority++;
  51345. result.optimizations.push(new RenderTargetsOptimization(priority));
  51346. // Next priority
  51347. priority++;
  51348. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  51349. return result;
  51350. };
  51351. return SceneOptimizerOptions;
  51352. }());
  51353. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  51354. // Scene optimizer tool
  51355. var SceneOptimizer = (function () {
  51356. function SceneOptimizer() {
  51357. }
  51358. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  51359. // TODO: add an epsilon
  51360. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  51361. if (onSuccess) {
  51362. onSuccess();
  51363. }
  51364. return;
  51365. }
  51366. // Apply current level of optimizations
  51367. var allDone = true;
  51368. var noOptimizationApplied = true;
  51369. for (var index = 0; index < options.optimizations.length; index++) {
  51370. var optimization = options.optimizations[index];
  51371. if (optimization.priority === currentPriorityLevel) {
  51372. noOptimizationApplied = false;
  51373. allDone = allDone && optimization.apply(scene);
  51374. }
  51375. }
  51376. // If no optimization was applied, this is a failure :(
  51377. if (noOptimizationApplied) {
  51378. if (onFailure) {
  51379. onFailure();
  51380. }
  51381. return;
  51382. }
  51383. // If all optimizations were done, move to next level
  51384. if (allDone) {
  51385. currentPriorityLevel++;
  51386. }
  51387. // Let's the system running for a specific amount of time before checking FPS
  51388. scene.executeWhenReady(function () {
  51389. setTimeout(function () {
  51390. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  51391. }, options.trackerDuration);
  51392. });
  51393. };
  51394. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  51395. if (!options) {
  51396. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  51397. }
  51398. // Let's the system running for a specific amount of time before checking FPS
  51399. scene.executeWhenReady(function () {
  51400. setTimeout(function () {
  51401. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  51402. }, options.trackerDuration);
  51403. });
  51404. };
  51405. return SceneOptimizer;
  51406. }());
  51407. BABYLON.SceneOptimizer = SceneOptimizer;
  51408. })(BABYLON || (BABYLON = {}));
  51409. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  51410. var BABYLON;
  51411. (function (BABYLON) {
  51412. var Internals;
  51413. (function (Internals) {
  51414. var MeshLODLevel = (function () {
  51415. function MeshLODLevel(distance, mesh) {
  51416. this.distance = distance;
  51417. this.mesh = mesh;
  51418. }
  51419. return MeshLODLevel;
  51420. }());
  51421. Internals.MeshLODLevel = MeshLODLevel;
  51422. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51423. })(BABYLON || (BABYLON = {}));
  51424. //# sourceMappingURL=babylon.meshLODLevel.js.map
  51425. var BABYLON;
  51426. (function (BABYLON) {
  51427. var RawTexture = (function (_super) {
  51428. __extends(RawTexture, _super);
  51429. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51430. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51431. if (invertY === void 0) { invertY = false; }
  51432. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51433. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51434. _this.format = format;
  51435. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51436. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51437. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51438. return _this;
  51439. }
  51440. RawTexture.prototype.update = function (data) {
  51441. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  51442. };
  51443. // Statics
  51444. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51445. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51446. if (invertY === void 0) { invertY = false; }
  51447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51448. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51449. };
  51450. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51451. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51452. if (invertY === void 0) { invertY = false; }
  51453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51454. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51455. };
  51456. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51457. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51458. if (invertY === void 0) { invertY = false; }
  51459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51460. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51461. };
  51462. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51463. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51464. if (invertY === void 0) { invertY = false; }
  51465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51466. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51467. };
  51468. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51469. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51470. if (invertY === void 0) { invertY = false; }
  51471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51472. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51473. };
  51474. return RawTexture;
  51475. }(BABYLON.Texture));
  51476. BABYLON.RawTexture = RawTexture;
  51477. })(BABYLON || (BABYLON = {}));
  51478. //# sourceMappingURL=babylon.rawTexture.js.map
  51479. /// <reference path="..\Math\babylon.math.ts" />
  51480. var BABYLON;
  51481. (function (BABYLON) {
  51482. var IndexedVector2 = (function (_super) {
  51483. __extends(IndexedVector2, _super);
  51484. function IndexedVector2(original, index) {
  51485. var _this = _super.call(this, original.x, original.y) || this;
  51486. _this.index = index;
  51487. return _this;
  51488. }
  51489. return IndexedVector2;
  51490. }(BABYLON.Vector2));
  51491. var PolygonPoints = (function () {
  51492. function PolygonPoints() {
  51493. this.elements = new Array();
  51494. }
  51495. PolygonPoints.prototype.add = function (originalPoints) {
  51496. var _this = this;
  51497. var result = new Array();
  51498. originalPoints.forEach(function (point) {
  51499. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  51500. var newPoint = new IndexedVector2(point, _this.elements.length);
  51501. result.push(newPoint);
  51502. _this.elements.push(newPoint);
  51503. }
  51504. });
  51505. return result;
  51506. };
  51507. PolygonPoints.prototype.computeBounds = function () {
  51508. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51509. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51510. this.elements.forEach(function (point) {
  51511. // x
  51512. if (point.x < lmin.x) {
  51513. lmin.x = point.x;
  51514. }
  51515. else if (point.x > lmax.x) {
  51516. lmax.x = point.x;
  51517. }
  51518. // y
  51519. if (point.y < lmin.y) {
  51520. lmin.y = point.y;
  51521. }
  51522. else if (point.y > lmax.y) {
  51523. lmax.y = point.y;
  51524. }
  51525. });
  51526. return {
  51527. min: lmin,
  51528. max: lmax,
  51529. width: lmax.x - lmin.x,
  51530. height: lmax.y - lmin.y
  51531. };
  51532. };
  51533. return PolygonPoints;
  51534. }());
  51535. var Polygon = (function () {
  51536. function Polygon() {
  51537. }
  51538. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51539. return [
  51540. new BABYLON.Vector2(xmin, ymin),
  51541. new BABYLON.Vector2(xmax, ymin),
  51542. new BABYLON.Vector2(xmax, ymax),
  51543. new BABYLON.Vector2(xmin, ymax)
  51544. ];
  51545. };
  51546. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51547. if (cx === void 0) { cx = 0; }
  51548. if (cy === void 0) { cy = 0; }
  51549. if (numberOfSides === void 0) { numberOfSides = 32; }
  51550. var result = new Array();
  51551. var angle = 0;
  51552. var increment = (Math.PI * 2) / numberOfSides;
  51553. for (var i = 0; i < numberOfSides; i++) {
  51554. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51555. angle -= increment;
  51556. }
  51557. return result;
  51558. };
  51559. Polygon.Parse = function (input) {
  51560. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51561. var i, result = [];
  51562. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51563. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51564. }
  51565. return result;
  51566. };
  51567. Polygon.StartingAt = function (x, y) {
  51568. return BABYLON.Path2.StartingAt(x, y);
  51569. };
  51570. return Polygon;
  51571. }());
  51572. BABYLON.Polygon = Polygon;
  51573. var PolygonMeshBuilder = (function () {
  51574. function PolygonMeshBuilder(name, contours, scene) {
  51575. this._points = new PolygonPoints();
  51576. this._outlinepoints = new PolygonPoints();
  51577. this._holes = [];
  51578. this._epoints = new Array();
  51579. this._eholes = new Array();
  51580. this._name = name;
  51581. this._scene = scene;
  51582. var points;
  51583. if (contours instanceof BABYLON.Path2) {
  51584. points = contours.getPoints();
  51585. }
  51586. else {
  51587. points = contours;
  51588. }
  51589. this._addToepoint(points);
  51590. this._points.add(points);
  51591. this._outlinepoints.add(points);
  51592. }
  51593. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51594. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  51595. var p = points_1[_i];
  51596. this._epoints.push(p.x, p.y);
  51597. }
  51598. };
  51599. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51600. this._points.add(hole);
  51601. var holepoints = new PolygonPoints();
  51602. holepoints.add(hole);
  51603. this._holes.push(holepoints);
  51604. this._eholes.push(this._epoints.length / 2);
  51605. this._addToepoint(hole);
  51606. return this;
  51607. };
  51608. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51609. var _this = this;
  51610. if (updatable === void 0) { updatable = false; }
  51611. var result = new BABYLON.Mesh(this._name, this._scene);
  51612. var normals = [];
  51613. var positions = [];
  51614. var uvs = [];
  51615. var bounds = this._points.computeBounds();
  51616. this._points.elements.forEach(function (p) {
  51617. normals.push(0, 1.0, 0);
  51618. positions.push(p.x, 0, p.y);
  51619. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51620. });
  51621. var indices = [];
  51622. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51623. for (var i = 0; i < res.length; i++) {
  51624. indices.push(res[i]);
  51625. }
  51626. if (depth > 0) {
  51627. var positionscount = (positions.length / 3); //get the current pointcount
  51628. this._points.elements.forEach(function (p) {
  51629. normals.push(0, -1.0, 0);
  51630. positions.push(p.x, -depth, p.y);
  51631. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51632. });
  51633. var totalCount = indices.length;
  51634. for (var i = 0; i < totalCount; i += 3) {
  51635. var i0 = indices[i + 0];
  51636. var i1 = indices[i + 1];
  51637. var i2 = indices[i + 2];
  51638. indices.push(i2 + positionscount);
  51639. indices.push(i1 + positionscount);
  51640. indices.push(i0 + positionscount);
  51641. }
  51642. //Add the sides
  51643. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51644. this._holes.forEach(function (hole) {
  51645. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51646. });
  51647. }
  51648. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51649. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51650. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51651. result.setIndices(indices);
  51652. return result;
  51653. };
  51654. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51655. var StartIndex = positions.length / 3;
  51656. var ulength = 0;
  51657. for (var i = 0; i < points.elements.length; i++) {
  51658. var p = points.elements[i];
  51659. var p1;
  51660. if ((i + 1) > points.elements.length - 1) {
  51661. p1 = points.elements[0];
  51662. }
  51663. else {
  51664. p1 = points.elements[i + 1];
  51665. }
  51666. positions.push(p.x, 0, p.y);
  51667. positions.push(p.x, -depth, p.y);
  51668. positions.push(p1.x, 0, p1.y);
  51669. positions.push(p1.x, -depth, p1.y);
  51670. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51671. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51672. var v3 = v2.subtract(v1);
  51673. var v4 = new BABYLON.Vector3(0, 1, 0);
  51674. var vn = BABYLON.Vector3.Cross(v3, v4);
  51675. vn = vn.normalize();
  51676. uvs.push(ulength / bounds.width, 0);
  51677. uvs.push(ulength / bounds.width, 1);
  51678. ulength += v3.length();
  51679. uvs.push((ulength / bounds.width), 0);
  51680. uvs.push((ulength / bounds.width), 1);
  51681. if (!flip) {
  51682. normals.push(-vn.x, -vn.y, -vn.z);
  51683. normals.push(-vn.x, -vn.y, -vn.z);
  51684. normals.push(-vn.x, -vn.y, -vn.z);
  51685. normals.push(-vn.x, -vn.y, -vn.z);
  51686. indices.push(StartIndex);
  51687. indices.push(StartIndex + 1);
  51688. indices.push(StartIndex + 2);
  51689. indices.push(StartIndex + 1);
  51690. indices.push(StartIndex + 3);
  51691. indices.push(StartIndex + 2);
  51692. }
  51693. else {
  51694. normals.push(vn.x, vn.y, vn.z);
  51695. normals.push(vn.x, vn.y, vn.z);
  51696. normals.push(vn.x, vn.y, vn.z);
  51697. normals.push(vn.x, vn.y, vn.z);
  51698. indices.push(StartIndex);
  51699. indices.push(StartIndex + 2);
  51700. indices.push(StartIndex + 1);
  51701. indices.push(StartIndex + 1);
  51702. indices.push(StartIndex + 2);
  51703. indices.push(StartIndex + 3);
  51704. }
  51705. StartIndex += 4;
  51706. }
  51707. ;
  51708. };
  51709. return PolygonMeshBuilder;
  51710. }());
  51711. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  51712. })(BABYLON || (BABYLON = {}));
  51713. //# sourceMappingURL=babylon.polygonMesh.js.map
  51714. var BABYLON;
  51715. (function (BABYLON) {
  51716. var Octree = (function () {
  51717. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  51718. if (maxDepth === void 0) { maxDepth = 2; }
  51719. this.maxDepth = maxDepth;
  51720. this.dynamicContent = new Array();
  51721. this._maxBlockCapacity = maxBlockCapacity || 64;
  51722. this._selectionContent = new BABYLON.SmartArray(1024);
  51723. this._creationFunc = creationFunc;
  51724. }
  51725. // Methods
  51726. Octree.prototype.update = function (worldMin, worldMax, entries) {
  51727. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  51728. };
  51729. Octree.prototype.addMesh = function (entry) {
  51730. for (var index = 0; index < this.blocks.length; index++) {
  51731. var block = this.blocks[index];
  51732. block.addEntry(entry);
  51733. }
  51734. };
  51735. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  51736. this._selectionContent.reset();
  51737. for (var index = 0; index < this.blocks.length; index++) {
  51738. var block = this.blocks[index];
  51739. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  51740. }
  51741. if (allowDuplicate) {
  51742. this._selectionContent.concat(this.dynamicContent);
  51743. }
  51744. else {
  51745. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51746. }
  51747. return this._selectionContent;
  51748. };
  51749. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  51750. this._selectionContent.reset();
  51751. for (var index = 0; index < this.blocks.length; index++) {
  51752. var block = this.blocks[index];
  51753. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  51754. }
  51755. if (allowDuplicate) {
  51756. this._selectionContent.concat(this.dynamicContent);
  51757. }
  51758. else {
  51759. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51760. }
  51761. return this._selectionContent;
  51762. };
  51763. Octree.prototype.intersectsRay = function (ray) {
  51764. this._selectionContent.reset();
  51765. for (var index = 0; index < this.blocks.length; index++) {
  51766. var block = this.blocks[index];
  51767. block.intersectsRay(ray, this._selectionContent);
  51768. }
  51769. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  51770. return this._selectionContent;
  51771. };
  51772. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  51773. target.blocks = new Array();
  51774. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  51775. // Segmenting space
  51776. for (var x = 0; x < 2; x++) {
  51777. for (var y = 0; y < 2; y++) {
  51778. for (var z = 0; z < 2; z++) {
  51779. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  51780. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  51781. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  51782. block.addEntries(entries);
  51783. target.blocks.push(block);
  51784. }
  51785. }
  51786. }
  51787. };
  51788. return Octree;
  51789. }());
  51790. Octree.CreationFuncForMeshes = function (entry, block) {
  51791. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51792. block.entries.push(entry);
  51793. }
  51794. };
  51795. Octree.CreationFuncForSubMeshes = function (entry, block) {
  51796. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  51797. block.entries.push(entry);
  51798. }
  51799. };
  51800. BABYLON.Octree = Octree;
  51801. })(BABYLON || (BABYLON = {}));
  51802. //# sourceMappingURL=babylon.octree.js.map
  51803. var BABYLON;
  51804. (function (BABYLON) {
  51805. var OctreeBlock = (function () {
  51806. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  51807. this.entries = new Array();
  51808. this._boundingVectors = new Array();
  51809. this._capacity = capacity;
  51810. this._depth = depth;
  51811. this._maxDepth = maxDepth;
  51812. this._creationFunc = creationFunc;
  51813. this._minPoint = minPoint;
  51814. this._maxPoint = maxPoint;
  51815. this._boundingVectors.push(minPoint.clone());
  51816. this._boundingVectors.push(maxPoint.clone());
  51817. this._boundingVectors.push(minPoint.clone());
  51818. this._boundingVectors[2].x = maxPoint.x;
  51819. this._boundingVectors.push(minPoint.clone());
  51820. this._boundingVectors[3].y = maxPoint.y;
  51821. this._boundingVectors.push(minPoint.clone());
  51822. this._boundingVectors[4].z = maxPoint.z;
  51823. this._boundingVectors.push(maxPoint.clone());
  51824. this._boundingVectors[5].z = minPoint.z;
  51825. this._boundingVectors.push(maxPoint.clone());
  51826. this._boundingVectors[6].x = minPoint.x;
  51827. this._boundingVectors.push(maxPoint.clone());
  51828. this._boundingVectors[7].y = minPoint.y;
  51829. }
  51830. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  51831. // Property
  51832. get: function () {
  51833. return this._capacity;
  51834. },
  51835. enumerable: true,
  51836. configurable: true
  51837. });
  51838. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  51839. get: function () {
  51840. return this._minPoint;
  51841. },
  51842. enumerable: true,
  51843. configurable: true
  51844. });
  51845. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  51846. get: function () {
  51847. return this._maxPoint;
  51848. },
  51849. enumerable: true,
  51850. configurable: true
  51851. });
  51852. // Methods
  51853. OctreeBlock.prototype.addEntry = function (entry) {
  51854. if (this.blocks) {
  51855. for (var index = 0; index < this.blocks.length; index++) {
  51856. var block = this.blocks[index];
  51857. block.addEntry(entry);
  51858. }
  51859. return;
  51860. }
  51861. this._creationFunc(entry, this);
  51862. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  51863. this.createInnerBlocks();
  51864. }
  51865. };
  51866. OctreeBlock.prototype.addEntries = function (entries) {
  51867. for (var index = 0; index < entries.length; index++) {
  51868. var mesh = entries[index];
  51869. this.addEntry(mesh);
  51870. }
  51871. };
  51872. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  51873. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  51874. if (this.blocks) {
  51875. for (var index = 0; index < this.blocks.length; index++) {
  51876. var block = this.blocks[index];
  51877. block.select(frustumPlanes, selection, allowDuplicate);
  51878. }
  51879. return;
  51880. }
  51881. if (allowDuplicate) {
  51882. selection.concat(this.entries);
  51883. }
  51884. else {
  51885. selection.concatWithNoDuplicate(this.entries);
  51886. }
  51887. }
  51888. };
  51889. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  51890. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  51891. if (this.blocks) {
  51892. for (var index = 0; index < this.blocks.length; index++) {
  51893. var block = this.blocks[index];
  51894. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  51895. }
  51896. return;
  51897. }
  51898. if (allowDuplicate) {
  51899. selection.concat(this.entries);
  51900. }
  51901. else {
  51902. selection.concatWithNoDuplicate(this.entries);
  51903. }
  51904. }
  51905. };
  51906. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  51907. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  51908. if (this.blocks) {
  51909. for (var index = 0; index < this.blocks.length; index++) {
  51910. var block = this.blocks[index];
  51911. block.intersectsRay(ray, selection);
  51912. }
  51913. return;
  51914. }
  51915. selection.concatWithNoDuplicate(this.entries);
  51916. }
  51917. };
  51918. OctreeBlock.prototype.createInnerBlocks = function () {
  51919. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  51920. };
  51921. return OctreeBlock;
  51922. }());
  51923. BABYLON.OctreeBlock = OctreeBlock;
  51924. })(BABYLON || (BABYLON = {}));
  51925. //# sourceMappingURL=babylon.octreeBlock.js.map
  51926. var BABYLON;
  51927. (function (BABYLON) {
  51928. var BlurPostProcess = (function (_super) {
  51929. __extends(BlurPostProcess, _super);
  51930. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  51931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51932. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  51933. _this.direction = direction;
  51934. _this.blurWidth = blurWidth;
  51935. _this.onApplyObservable.add(function (effect) {
  51936. effect.setFloat2("screenSize", _this.width, _this.height);
  51937. effect.setVector2("direction", _this.direction);
  51938. effect.setFloat("blurWidth", _this.blurWidth);
  51939. });
  51940. return _this;
  51941. }
  51942. return BlurPostProcess;
  51943. }(BABYLON.PostProcess));
  51944. BABYLON.BlurPostProcess = BlurPostProcess;
  51945. })(BABYLON || (BABYLON = {}));
  51946. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51947. var BABYLON;
  51948. (function (BABYLON) {
  51949. var RefractionPostProcess = (function (_super) {
  51950. __extends(RefractionPostProcess, _super);
  51951. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  51952. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  51953. _this.color = color;
  51954. _this.depth = depth;
  51955. _this.colorLevel = colorLevel;
  51956. _this.onActivateObservable.add(function (cam) {
  51957. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51958. });
  51959. _this.onApplyObservable.add(function (effect) {
  51960. effect.setColor3("baseColor", _this.color);
  51961. effect.setFloat("depth", _this.depth);
  51962. effect.setFloat("colorLevel", _this.colorLevel);
  51963. effect.setTexture("refractionSampler", _this._refRexture);
  51964. });
  51965. return _this;
  51966. }
  51967. // Methods
  51968. RefractionPostProcess.prototype.dispose = function (camera) {
  51969. if (this._refRexture) {
  51970. this._refRexture.dispose();
  51971. }
  51972. _super.prototype.dispose.call(this, camera);
  51973. };
  51974. return RefractionPostProcess;
  51975. }(BABYLON.PostProcess));
  51976. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51977. })(BABYLON || (BABYLON = {}));
  51978. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51979. var BABYLON;
  51980. (function (BABYLON) {
  51981. var BlackAndWhitePostProcess = (function (_super) {
  51982. __extends(BlackAndWhitePostProcess, _super);
  51983. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51984. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  51985. }
  51986. return BlackAndWhitePostProcess;
  51987. }(BABYLON.PostProcess));
  51988. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51989. })(BABYLON || (BABYLON = {}));
  51990. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51991. var BABYLON;
  51992. (function (BABYLON) {
  51993. var ConvolutionPostProcess = (function (_super) {
  51994. __extends(ConvolutionPostProcess, _super);
  51995. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51996. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51997. _this.kernel = kernel;
  51998. _this.onApply = function (effect) {
  51999. effect.setFloat2("screenSize", _this.width, _this.height);
  52000. effect.setArray("kernel", _this.kernel);
  52001. };
  52002. return _this;
  52003. }
  52004. return ConvolutionPostProcess;
  52005. }(BABYLON.PostProcess));
  52006. // Statics
  52007. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  52008. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  52009. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  52010. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  52011. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  52012. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  52013. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  52014. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  52015. })(BABYLON || (BABYLON = {}));
  52016. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  52017. var BABYLON;
  52018. (function (BABYLON) {
  52019. var FilterPostProcess = (function (_super) {
  52020. __extends(FilterPostProcess, _super);
  52021. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  52022. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  52023. _this.kernelMatrix = kernelMatrix;
  52024. _this.onApply = function (effect) {
  52025. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  52026. };
  52027. return _this;
  52028. }
  52029. return FilterPostProcess;
  52030. }(BABYLON.PostProcess));
  52031. BABYLON.FilterPostProcess = FilterPostProcess;
  52032. })(BABYLON || (BABYLON = {}));
  52033. //# sourceMappingURL=babylon.filterPostProcess.js.map
  52034. var BABYLON;
  52035. (function (BABYLON) {
  52036. var FxaaPostProcess = (function (_super) {
  52037. __extends(FxaaPostProcess, _super);
  52038. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52039. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  52040. _this.onSizeChangedObservable.add(function () {
  52041. _this.texelWidth = 1.0 / _this.width;
  52042. _this.texelHeight = 1.0 / _this.height;
  52043. });
  52044. _this.onApplyObservable.add(function (effect) {
  52045. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  52046. });
  52047. return _this;
  52048. }
  52049. return FxaaPostProcess;
  52050. }(BABYLON.PostProcess));
  52051. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52052. })(BABYLON || (BABYLON = {}));
  52053. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  52054. var BABYLON;
  52055. (function (BABYLON) {
  52056. var StereoscopicInterlacePostProcess = (function (_super) {
  52057. __extends(StereoscopicInterlacePostProcess, _super);
  52058. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  52059. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  52060. _this._passedProcess = rigCameras[0]._rigPostProcess;
  52061. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52062. _this.onSizeChangedObservable.add(function () {
  52063. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52064. });
  52065. _this.onApplyObservable.add(function (effect) {
  52066. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  52067. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  52068. });
  52069. return _this;
  52070. }
  52071. return StereoscopicInterlacePostProcess;
  52072. }(BABYLON.PostProcess));
  52073. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  52074. })(BABYLON || (BABYLON = {}));
  52075. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  52076. var BABYLON;
  52077. (function (BABYLON) {
  52078. var LensFlare = (function () {
  52079. function LensFlare(size, position, color, imgUrl, system) {
  52080. this.size = size;
  52081. this.position = position;
  52082. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52083. this.dispose = function () {
  52084. if (this.texture) {
  52085. this.texture.dispose();
  52086. }
  52087. // Remove from scene
  52088. var index = this._system.lensFlares.indexOf(this);
  52089. this._system.lensFlares.splice(index, 1);
  52090. };
  52091. this.color = color || new BABYLON.Color3(1, 1, 1);
  52092. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52093. this._system = system;
  52094. system.lensFlares.push(this);
  52095. }
  52096. return LensFlare;
  52097. }());
  52098. BABYLON.LensFlare = LensFlare;
  52099. })(BABYLON || (BABYLON = {}));
  52100. //# sourceMappingURL=babylon.lensFlare.js.map
  52101. var BABYLON;
  52102. (function (BABYLON) {
  52103. var LensFlareSystem = (function () {
  52104. function LensFlareSystem(name, emitter, scene) {
  52105. this.name = name;
  52106. this.lensFlares = new Array();
  52107. this.borderLimit = 300;
  52108. this.viewportBorder = 0;
  52109. this.layerMask = 0x0FFFFFFF;
  52110. this._vertexBuffers = {};
  52111. this._isEnabled = true;
  52112. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52113. this._emitter = emitter;
  52114. this.id = name;
  52115. scene.lensFlareSystems.push(this);
  52116. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52117. var engine = scene.getEngine();
  52118. // VBO
  52119. var vertices = [];
  52120. vertices.push(1, 1);
  52121. vertices.push(-1, 1);
  52122. vertices.push(-1, -1);
  52123. vertices.push(1, -1);
  52124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52125. // Indices
  52126. var indices = [];
  52127. indices.push(0);
  52128. indices.push(1);
  52129. indices.push(2);
  52130. indices.push(0);
  52131. indices.push(2);
  52132. indices.push(3);
  52133. this._indexBuffer = engine.createIndexBuffer(indices);
  52134. // Effects
  52135. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52136. }
  52137. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52138. get: function () {
  52139. return this._isEnabled;
  52140. },
  52141. set: function (value) {
  52142. this._isEnabled = value;
  52143. },
  52144. enumerable: true,
  52145. configurable: true
  52146. });
  52147. LensFlareSystem.prototype.getScene = function () {
  52148. return this._scene;
  52149. };
  52150. LensFlareSystem.prototype.getEmitter = function () {
  52151. return this._emitter;
  52152. };
  52153. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52154. this._emitter = newEmitter;
  52155. };
  52156. LensFlareSystem.prototype.getEmitterPosition = function () {
  52157. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52158. };
  52159. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52160. var position = this.getEmitterPosition();
  52161. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52162. this._positionX = position.x;
  52163. this._positionY = position.y;
  52164. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52165. if (this.viewportBorder > 0) {
  52166. globalViewport.x -= this.viewportBorder;
  52167. globalViewport.y -= this.viewportBorder;
  52168. globalViewport.width += this.viewportBorder * 2;
  52169. globalViewport.height += this.viewportBorder * 2;
  52170. position.x += this.viewportBorder;
  52171. position.y += this.viewportBorder;
  52172. this._positionX += this.viewportBorder;
  52173. this._positionY += this.viewportBorder;
  52174. }
  52175. if (position.z > 0) {
  52176. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52177. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52178. return true;
  52179. }
  52180. return true;
  52181. }
  52182. return false;
  52183. };
  52184. LensFlareSystem.prototype._isVisible = function () {
  52185. if (!this._isEnabled) {
  52186. return false;
  52187. }
  52188. var emitterPosition = this.getEmitterPosition();
  52189. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  52190. var distance = direction.length();
  52191. direction.normalize();
  52192. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  52193. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52194. return !pickInfo.hit || pickInfo.distance > distance;
  52195. };
  52196. LensFlareSystem.prototype.render = function () {
  52197. if (!this._effect.isReady())
  52198. return false;
  52199. var engine = this._scene.getEngine();
  52200. var viewport = this._scene.activeCamera.viewport;
  52201. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52202. // Position
  52203. if (!this.computeEffectivePosition(globalViewport)) {
  52204. return false;
  52205. }
  52206. // Visibility
  52207. if (!this._isVisible()) {
  52208. return false;
  52209. }
  52210. // Intensity
  52211. var awayX;
  52212. var awayY;
  52213. if (this._positionX < this.borderLimit + globalViewport.x) {
  52214. awayX = this.borderLimit + globalViewport.x - this._positionX;
  52215. }
  52216. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  52217. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  52218. }
  52219. else {
  52220. awayX = 0;
  52221. }
  52222. if (this._positionY < this.borderLimit + globalViewport.y) {
  52223. awayY = this.borderLimit + globalViewport.y - this._positionY;
  52224. }
  52225. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  52226. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  52227. }
  52228. else {
  52229. awayY = 0;
  52230. }
  52231. var away = (awayX > awayY) ? awayX : awayY;
  52232. away -= this.viewportBorder;
  52233. if (away > this.borderLimit) {
  52234. away = this.borderLimit;
  52235. }
  52236. var intensity = 1.0 - (away / this.borderLimit);
  52237. if (intensity < 0) {
  52238. return false;
  52239. }
  52240. if (intensity > 1.0) {
  52241. intensity = 1.0;
  52242. }
  52243. if (this.viewportBorder > 0) {
  52244. globalViewport.x += this.viewportBorder;
  52245. globalViewport.y += this.viewportBorder;
  52246. globalViewport.width -= this.viewportBorder * 2;
  52247. globalViewport.height -= this.viewportBorder * 2;
  52248. this._positionX -= this.viewportBorder;
  52249. this._positionY -= this.viewportBorder;
  52250. }
  52251. // Position
  52252. var centerX = globalViewport.x + globalViewport.width / 2;
  52253. var centerY = globalViewport.y + globalViewport.height / 2;
  52254. var distX = centerX - this._positionX;
  52255. var distY = centerY - this._positionY;
  52256. // Effects
  52257. engine.enableEffect(this._effect);
  52258. engine.setState(false);
  52259. engine.setDepthBuffer(false);
  52260. // VBOs
  52261. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52262. // Flares
  52263. for (var index = 0; index < this.lensFlares.length; index++) {
  52264. var flare = this.lensFlares[index];
  52265. engine.setAlphaMode(flare.alphaMode);
  52266. var x = centerX - (distX * flare.position);
  52267. var y = centerY - (distY * flare.position);
  52268. var cw = flare.size;
  52269. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  52270. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  52271. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  52272. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  52273. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  52274. // Texture
  52275. this._effect.setTexture("textureSampler", flare.texture);
  52276. // Color
  52277. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  52278. // Draw order
  52279. engine.draw(true, 0, 6);
  52280. }
  52281. engine.setDepthBuffer(true);
  52282. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52283. return true;
  52284. };
  52285. LensFlareSystem.prototype.dispose = function () {
  52286. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52287. if (vertexBuffer) {
  52288. vertexBuffer.dispose();
  52289. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52290. }
  52291. if (this._indexBuffer) {
  52292. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52293. this._indexBuffer = null;
  52294. }
  52295. while (this.lensFlares.length) {
  52296. this.lensFlares[0].dispose();
  52297. }
  52298. // Remove from scene
  52299. var index = this._scene.lensFlareSystems.indexOf(this);
  52300. this._scene.lensFlareSystems.splice(index, 1);
  52301. };
  52302. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  52303. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  52304. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  52305. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  52306. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  52307. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  52308. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  52309. var parsedFlare = parsedLensFlareSystem.flares[index];
  52310. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  52311. }
  52312. return lensFlareSystem;
  52313. };
  52314. LensFlareSystem.prototype.serialize = function () {
  52315. var serializationObject = {};
  52316. serializationObject.id = this.id;
  52317. serializationObject.name = this.name;
  52318. serializationObject.emitterId = this.getEmitter().id;
  52319. serializationObject.borderLimit = this.borderLimit;
  52320. serializationObject.flares = [];
  52321. for (var index = 0; index < this.lensFlares.length; index++) {
  52322. var flare = this.lensFlares[index];
  52323. serializationObject.flares.push({
  52324. size: flare.size,
  52325. position: flare.position,
  52326. color: flare.color.asArray(),
  52327. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  52328. });
  52329. }
  52330. return serializationObject;
  52331. };
  52332. return LensFlareSystem;
  52333. }());
  52334. BABYLON.LensFlareSystem = LensFlareSystem;
  52335. })(BABYLON || (BABYLON = {}));
  52336. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  52337. /// <reference path="babylon.freeCamera.ts" />
  52338. var BABYLON;
  52339. (function (BABYLON) {
  52340. // We're mainly based on the logic defined into the FreeCamera code
  52341. var DeviceOrientationCamera = (function (_super) {
  52342. __extends(DeviceOrientationCamera, _super);
  52343. function DeviceOrientationCamera(name, position, scene) {
  52344. var _this = _super.call(this, name, position, scene) || this;
  52345. _this._quaternionCache = new BABYLON.Quaternion();
  52346. _this.inputs.addDeviceOrientation();
  52347. return _this;
  52348. }
  52349. DeviceOrientationCamera.prototype.getClassName = function () {
  52350. return "DeviceOrientationCamera";
  52351. };
  52352. DeviceOrientationCamera.prototype._checkInputs = function () {
  52353. _super.prototype._checkInputs.call(this);
  52354. this._quaternionCache.copyFrom(this.rotationQuaternion);
  52355. if (this._initialQuaternion) {
  52356. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52357. }
  52358. };
  52359. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  52360. var _this = this;
  52361. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  52362. //can only work if this camera has a rotation quaternion already.
  52363. if (!this.rotationQuaternion)
  52364. return;
  52365. if (!this._initialQuaternion) {
  52366. this._initialQuaternion = new BABYLON.Quaternion();
  52367. }
  52368. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  52369. ['x', 'y', 'z'].forEach(function (axisName) {
  52370. if (!axis[axisName]) {
  52371. _this._initialQuaternion[axisName] = 0;
  52372. }
  52373. else {
  52374. _this._initialQuaternion[axisName] *= -1;
  52375. }
  52376. });
  52377. this._initialQuaternion.normalize();
  52378. //force rotation update
  52379. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  52380. };
  52381. return DeviceOrientationCamera;
  52382. }(BABYLON.FreeCamera));
  52383. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  52384. })(BABYLON || (BABYLON = {}));
  52385. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  52386. var BABYLON;
  52387. (function (BABYLON) {
  52388. var VRDeviceOrientationFreeCamera = (function (_super) {
  52389. __extends(VRDeviceOrientationFreeCamera, _super);
  52390. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52391. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52392. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52393. var _this = _super.call(this, name, position, scene) || this;
  52394. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52395. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52396. return _this;
  52397. }
  52398. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  52399. return "VRDeviceOrientationFreeCamera";
  52400. };
  52401. return VRDeviceOrientationFreeCamera;
  52402. }(BABYLON.DeviceOrientationCamera));
  52403. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  52404. var VRDeviceOrientationGamepadCamera = (function (_super) {
  52405. __extends(VRDeviceOrientationGamepadCamera, _super);
  52406. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  52407. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52408. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52409. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  52410. _this.inputs.addGamepad();
  52411. return _this;
  52412. }
  52413. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  52414. return "VRDeviceOrientationGamepadCamera";
  52415. };
  52416. return VRDeviceOrientationGamepadCamera;
  52417. }(VRDeviceOrientationFreeCamera));
  52418. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  52419. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  52420. __extends(VRDeviceOrientationArcRotateCamera, _super);
  52421. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  52422. if (compensateDistortion === void 0) { compensateDistortion = true; }
  52423. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  52424. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52425. vrCameraMetrics.compensateDistortion = compensateDistortion;
  52426. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  52427. _this.inputs.addVRDeviceOrientation();
  52428. return _this;
  52429. }
  52430. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  52431. return "VRDeviceOrientationArcRotateCamera";
  52432. };
  52433. return VRDeviceOrientationArcRotateCamera;
  52434. }(BABYLON.ArcRotateCamera));
  52435. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  52436. })(BABYLON || (BABYLON = {}));
  52437. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  52438. /// <reference path="babylon.touchCamera.ts" />
  52439. var BABYLON;
  52440. (function (BABYLON) {
  52441. // We're mainly based on the logic defined into the FreeCamera code
  52442. var UniversalCamera = (function (_super) {
  52443. __extends(UniversalCamera, _super);
  52444. //-- end properties for backward compatibility for inputs
  52445. function UniversalCamera(name, position, scene) {
  52446. var _this = _super.call(this, name, position, scene) || this;
  52447. _this.inputs.addGamepad();
  52448. return _this;
  52449. }
  52450. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52451. //-- Begin properties for backward compatibility for inputs
  52452. get: function () {
  52453. var gamepad = this.inputs.attached["gamepad"];
  52454. if (gamepad)
  52455. return gamepad.gamepadAngularSensibility;
  52456. },
  52457. set: function (value) {
  52458. var gamepad = this.inputs.attached["gamepad"];
  52459. if (gamepad)
  52460. gamepad.gamepadAngularSensibility = value;
  52461. },
  52462. enumerable: true,
  52463. configurable: true
  52464. });
  52465. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52466. get: function () {
  52467. var gamepad = this.inputs.attached["gamepad"];
  52468. if (gamepad)
  52469. return gamepad.gamepadMoveSensibility;
  52470. },
  52471. set: function (value) {
  52472. var gamepad = this.inputs.attached["gamepad"];
  52473. if (gamepad)
  52474. gamepad.gamepadMoveSensibility = value;
  52475. },
  52476. enumerable: true,
  52477. configurable: true
  52478. });
  52479. UniversalCamera.prototype.getClassName = function () {
  52480. return "UniversalCamera";
  52481. };
  52482. return UniversalCamera;
  52483. }(BABYLON.TouchCamera));
  52484. BABYLON.UniversalCamera = UniversalCamera;
  52485. })(BABYLON || (BABYLON = {}));
  52486. //# sourceMappingURL=babylon.universalCamera.js.map
  52487. var BABYLON;
  52488. (function (BABYLON) {
  52489. var Gamepads = (function () {
  52490. function Gamepads(ongamedpadconnected) {
  52491. var _this = this;
  52492. this.babylonGamepads = [];
  52493. this.oneGamepadConnected = false;
  52494. this.isMonitoring = false;
  52495. this.gamepadEventSupported = 'GamepadEvent' in window;
  52496. this.gamepadSupport = (navigator.getGamepads ||
  52497. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  52498. this._callbackGamepadConnected = ongamedpadconnected;
  52499. if (this.gamepadSupport) {
  52500. //first add already-connected gamepads
  52501. this._updateGamepadObjects();
  52502. if (this.babylonGamepads.length) {
  52503. this._startMonitoringGamepads();
  52504. }
  52505. // Checking if the gamepad connected event is supported (like in Firefox)
  52506. if (this.gamepadEventSupported) {
  52507. this._onGamepadConnectedEvent = function (evt) {
  52508. _this._onGamepadConnected(evt.gamepad);
  52509. };
  52510. this._onGamepadDisonnectedEvent = function (evt) {
  52511. _this._onGamepadDisconnected(evt);
  52512. };
  52513. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52514. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52515. }
  52516. else {
  52517. this._startMonitoringGamepads();
  52518. }
  52519. }
  52520. }
  52521. Gamepads.prototype.dispose = function () {
  52522. if (Gamepads.gamepadDOMInfo) {
  52523. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52524. }
  52525. if (this._onGamepadConnectedEvent) {
  52526. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52527. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52528. this._onGamepadConnectedEvent = null;
  52529. this._onGamepadDisonnectedEvent = null;
  52530. }
  52531. };
  52532. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  52533. var newGamepad = this._addNewGamepad(gamepad);
  52534. if (this._callbackGamepadConnected)
  52535. this._callbackGamepadConnected(newGamepad);
  52536. this._startMonitoringGamepads();
  52537. };
  52538. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52539. if (!this.oneGamepadConnected) {
  52540. this.oneGamepadConnected = true;
  52541. if (Gamepads.gamepadDOMInfo) {
  52542. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52543. Gamepads.gamepadDOMInfo = null;
  52544. }
  52545. }
  52546. var newGamepad;
  52547. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  52548. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52549. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  52550. }
  52551. else if (gamepad.pose) {
  52552. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  52553. }
  52554. else {
  52555. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52556. }
  52557. this.babylonGamepads.push(newGamepad);
  52558. return newGamepad;
  52559. };
  52560. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52561. // Remove the gamepad from the list of gamepads to monitor.
  52562. for (var i in this.babylonGamepads) {
  52563. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52564. this.babylonGamepads.splice(+i, 1);
  52565. break;
  52566. }
  52567. }
  52568. // If no gamepads are left, stop the polling loop.
  52569. if (this.babylonGamepads.length == 0) {
  52570. this._stopMonitoringGamepads();
  52571. }
  52572. };
  52573. Gamepads.prototype._startMonitoringGamepads = function () {
  52574. if (!this.isMonitoring) {
  52575. this.isMonitoring = true;
  52576. this._checkGamepadsStatus();
  52577. }
  52578. };
  52579. Gamepads.prototype._stopMonitoringGamepads = function () {
  52580. this.isMonitoring = false;
  52581. };
  52582. Gamepads.prototype._checkGamepadsStatus = function () {
  52583. var _this = this;
  52584. // updating gamepad objects
  52585. this._updateGamepadObjects();
  52586. for (var i in this.babylonGamepads) {
  52587. this.babylonGamepads[i].update();
  52588. }
  52589. if (this.isMonitoring) {
  52590. if (window.requestAnimationFrame) {
  52591. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52592. }
  52593. else if (window.mozRequestAnimationFrame) {
  52594. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52595. }
  52596. else if (window.webkitRequestAnimationFrame) {
  52597. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52598. }
  52599. }
  52600. };
  52601. // This function is called only on Chrome, which does not yet support
  52602. // connection/disconnection events, but requires you to monitor
  52603. // an array for changes.
  52604. Gamepads.prototype._updateGamepadObjects = function () {
  52605. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52606. for (var i = 0; i < gamepads.length; i++) {
  52607. if (gamepads[i]) {
  52608. if (!(gamepads[i].index in this.babylonGamepads)) {
  52609. var newGamepad = this._addNewGamepad(gamepads[i]);
  52610. if (this._callbackGamepadConnected) {
  52611. this._callbackGamepadConnected(newGamepad);
  52612. }
  52613. }
  52614. else {
  52615. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52616. }
  52617. }
  52618. }
  52619. };
  52620. return Gamepads;
  52621. }());
  52622. BABYLON.Gamepads = Gamepads;
  52623. var StickValues = (function () {
  52624. function StickValues(x, y) {
  52625. this.x = x;
  52626. this.y = y;
  52627. }
  52628. return StickValues;
  52629. }());
  52630. BABYLON.StickValues = StickValues;
  52631. var Gamepad = (function () {
  52632. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  52633. if (leftStickX === void 0) { leftStickX = 0; }
  52634. if (leftStickY === void 0) { leftStickY = 1; }
  52635. if (rightStickX === void 0) { rightStickX = 2; }
  52636. if (rightStickY === void 0) { rightStickY = 3; }
  52637. this.id = id;
  52638. this.index = index;
  52639. this.browserGamepad = browserGamepad;
  52640. this.type = Gamepad.GAMEPAD;
  52641. this._leftStickAxisX = leftStickX;
  52642. this._leftStickAxisY = leftStickY;
  52643. this._rightStickAxisX = rightStickX;
  52644. this._rightStickAxisY = rightStickY;
  52645. if (this.browserGamepad.axes.length >= 2) {
  52646. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  52647. }
  52648. if (this.browserGamepad.axes.length >= 4) {
  52649. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  52650. }
  52651. }
  52652. Gamepad.prototype.onleftstickchanged = function (callback) {
  52653. this._onleftstickchanged = callback;
  52654. };
  52655. Gamepad.prototype.onrightstickchanged = function (callback) {
  52656. this._onrightstickchanged = callback;
  52657. };
  52658. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52659. get: function () {
  52660. return this._leftStick;
  52661. },
  52662. set: function (newValues) {
  52663. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52664. this._onleftstickchanged(newValues);
  52665. }
  52666. this._leftStick = newValues;
  52667. },
  52668. enumerable: true,
  52669. configurable: true
  52670. });
  52671. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52672. get: function () {
  52673. return this._rightStick;
  52674. },
  52675. set: function (newValues) {
  52676. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52677. this._onrightstickchanged(newValues);
  52678. }
  52679. this._rightStick = newValues;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Gamepad.prototype.update = function () {
  52685. if (this._leftStick) {
  52686. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  52687. }
  52688. if (this._rightStick) {
  52689. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  52690. }
  52691. };
  52692. return Gamepad;
  52693. }());
  52694. Gamepad.GAMEPAD = 0;
  52695. Gamepad.GENERIC = 1;
  52696. Gamepad.XBOX = 2;
  52697. Gamepad.POSE_ENABLED = 3;
  52698. BABYLON.Gamepad = Gamepad;
  52699. var GenericPad = (function (_super) {
  52700. __extends(GenericPad, _super);
  52701. function GenericPad(id, index, gamepad) {
  52702. var _this = _super.call(this, id, index, gamepad) || this;
  52703. _this.id = id;
  52704. _this.index = index;
  52705. _this.gamepad = gamepad;
  52706. _this.type = Gamepad.GENERIC;
  52707. _this._buttons = new Array(gamepad.buttons.length);
  52708. return _this;
  52709. }
  52710. GenericPad.prototype.onbuttondown = function (callback) {
  52711. this._onbuttondown = callback;
  52712. };
  52713. GenericPad.prototype.onbuttonup = function (callback) {
  52714. this._onbuttonup = callback;
  52715. };
  52716. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52717. if (newValue !== currentValue) {
  52718. if (this._onbuttondown && newValue === 1) {
  52719. this._onbuttondown(buttonIndex);
  52720. }
  52721. if (this._onbuttonup && newValue === 0) {
  52722. this._onbuttonup(buttonIndex);
  52723. }
  52724. }
  52725. return newValue;
  52726. };
  52727. GenericPad.prototype.update = function () {
  52728. _super.prototype.update.call(this);
  52729. for (var index = 0; index < this._buttons.length; index++) {
  52730. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52731. }
  52732. };
  52733. return GenericPad;
  52734. }(Gamepad));
  52735. BABYLON.GenericPad = GenericPad;
  52736. var Xbox360Button;
  52737. (function (Xbox360Button) {
  52738. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52739. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52740. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52741. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52742. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52743. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52744. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52745. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52746. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52747. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52748. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52749. var Xbox360Dpad;
  52750. (function (Xbox360Dpad) {
  52751. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52752. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52753. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52754. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52755. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52756. var Xbox360Pad = (function (_super) {
  52757. __extends(Xbox360Pad, _super);
  52758. function Xbox360Pad(id, index, gamepad, xboxOne) {
  52759. if (xboxOne === void 0) { xboxOne = false; }
  52760. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  52761. _this._leftTrigger = 0;
  52762. _this._rightTrigger = 0;
  52763. _this._buttonA = 0;
  52764. _this._buttonB = 0;
  52765. _this._buttonX = 0;
  52766. _this._buttonY = 0;
  52767. _this._buttonBack = 0;
  52768. _this._buttonStart = 0;
  52769. _this._buttonLB = 0;
  52770. _this._buttonRB = 0;
  52771. _this._buttonLeftStick = 0;
  52772. _this._buttonRightStick = 0;
  52773. _this._dPadUp = 0;
  52774. _this._dPadDown = 0;
  52775. _this._dPadLeft = 0;
  52776. _this._dPadRight = 0;
  52777. _this._isXboxOnePad = false;
  52778. _this.type = Gamepad.XBOX;
  52779. _this._isXboxOnePad = xboxOne;
  52780. return _this;
  52781. }
  52782. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52783. this._onlefttriggerchanged = callback;
  52784. };
  52785. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52786. this._onrighttriggerchanged = callback;
  52787. };
  52788. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52789. get: function () {
  52790. return this._leftTrigger;
  52791. },
  52792. set: function (newValue) {
  52793. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52794. this._onlefttriggerchanged(newValue);
  52795. }
  52796. this._leftTrigger = newValue;
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52802. get: function () {
  52803. return this._rightTrigger;
  52804. },
  52805. set: function (newValue) {
  52806. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52807. this._onrighttriggerchanged(newValue);
  52808. }
  52809. this._rightTrigger = newValue;
  52810. },
  52811. enumerable: true,
  52812. configurable: true
  52813. });
  52814. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52815. this._onbuttondown = callback;
  52816. };
  52817. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52818. this._onbuttonup = callback;
  52819. };
  52820. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52821. this._ondpaddown = callback;
  52822. };
  52823. Xbox360Pad.prototype.ondpadup = function (callback) {
  52824. this._ondpadup = callback;
  52825. };
  52826. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52827. if (newValue !== currentValue) {
  52828. if (this._onbuttondown && newValue === 1) {
  52829. this._onbuttondown(buttonType);
  52830. }
  52831. if (this._onbuttonup && newValue === 0) {
  52832. this._onbuttonup(buttonType);
  52833. }
  52834. }
  52835. return newValue;
  52836. };
  52837. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52838. if (newValue !== currentValue) {
  52839. if (this._ondpaddown && newValue === 1) {
  52840. this._ondpaddown(buttonType);
  52841. }
  52842. if (this._ondpadup && newValue === 0) {
  52843. this._ondpadup(buttonType);
  52844. }
  52845. }
  52846. return newValue;
  52847. };
  52848. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  52849. get: function () {
  52850. return this._buttonA;
  52851. },
  52852. set: function (value) {
  52853. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  52854. },
  52855. enumerable: true,
  52856. configurable: true
  52857. });
  52858. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  52859. get: function () {
  52860. return this._buttonB;
  52861. },
  52862. set: function (value) {
  52863. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  52864. },
  52865. enumerable: true,
  52866. configurable: true
  52867. });
  52868. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  52869. get: function () {
  52870. return this._buttonX;
  52871. },
  52872. set: function (value) {
  52873. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  52874. },
  52875. enumerable: true,
  52876. configurable: true
  52877. });
  52878. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  52879. get: function () {
  52880. return this._buttonY;
  52881. },
  52882. set: function (value) {
  52883. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  52884. },
  52885. enumerable: true,
  52886. configurable: true
  52887. });
  52888. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  52889. get: function () {
  52890. return this._buttonStart;
  52891. },
  52892. set: function (value) {
  52893. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  52894. },
  52895. enumerable: true,
  52896. configurable: true
  52897. });
  52898. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  52899. get: function () {
  52900. return this._buttonBack;
  52901. },
  52902. set: function (value) {
  52903. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  52904. },
  52905. enumerable: true,
  52906. configurable: true
  52907. });
  52908. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  52909. get: function () {
  52910. return this._buttonLB;
  52911. },
  52912. set: function (value) {
  52913. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  52914. },
  52915. enumerable: true,
  52916. configurable: true
  52917. });
  52918. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  52919. get: function () {
  52920. return this._buttonRB;
  52921. },
  52922. set: function (value) {
  52923. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  52924. },
  52925. enumerable: true,
  52926. configurable: true
  52927. });
  52928. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  52929. get: function () {
  52930. return this._buttonLeftStick;
  52931. },
  52932. set: function (value) {
  52933. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  52934. },
  52935. enumerable: true,
  52936. configurable: true
  52937. });
  52938. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  52939. get: function () {
  52940. return this._buttonRightStick;
  52941. },
  52942. set: function (value) {
  52943. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  52944. },
  52945. enumerable: true,
  52946. configurable: true
  52947. });
  52948. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  52949. get: function () {
  52950. return this._dPadUp;
  52951. },
  52952. set: function (value) {
  52953. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  52954. },
  52955. enumerable: true,
  52956. configurable: true
  52957. });
  52958. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  52959. get: function () {
  52960. return this._dPadDown;
  52961. },
  52962. set: function (value) {
  52963. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  52964. },
  52965. enumerable: true,
  52966. configurable: true
  52967. });
  52968. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  52969. get: function () {
  52970. return this._dPadLeft;
  52971. },
  52972. set: function (value) {
  52973. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  52974. },
  52975. enumerable: true,
  52976. configurable: true
  52977. });
  52978. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  52979. get: function () {
  52980. return this._dPadRight;
  52981. },
  52982. set: function (value) {
  52983. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  52984. },
  52985. enumerable: true,
  52986. configurable: true
  52987. });
  52988. Xbox360Pad.prototype.update = function () {
  52989. _super.prototype.update.call(this);
  52990. if (this._isXboxOnePad) {
  52991. this.buttonA = this.browserGamepad.buttons[0].value;
  52992. this.buttonB = this.browserGamepad.buttons[1].value;
  52993. this.buttonX = this.browserGamepad.buttons[2].value;
  52994. this.buttonY = this.browserGamepad.buttons[3].value;
  52995. this.buttonLB = this.browserGamepad.buttons[4].value;
  52996. this.buttonRB = this.browserGamepad.buttons[5].value;
  52997. this.leftTrigger = this.browserGamepad.axes[2];
  52998. this.rightTrigger = this.browserGamepad.axes[5];
  52999. this.buttonBack = this.browserGamepad.buttons[9].value;
  53000. this.buttonStart = this.browserGamepad.buttons[8].value;
  53001. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  53002. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  53003. this.dPadUp = this.browserGamepad.buttons[11].value;
  53004. this.dPadDown = this.browserGamepad.buttons[12].value;
  53005. this.dPadLeft = this.browserGamepad.buttons[13].value;
  53006. this.dPadRight = this.browserGamepad.buttons[14].value;
  53007. }
  53008. else {
  53009. this.buttonA = this.browserGamepad.buttons[0].value;
  53010. this.buttonB = this.browserGamepad.buttons[1].value;
  53011. this.buttonX = this.browserGamepad.buttons[2].value;
  53012. this.buttonY = this.browserGamepad.buttons[3].value;
  53013. this.buttonLB = this.browserGamepad.buttons[4].value;
  53014. this.buttonRB = this.browserGamepad.buttons[5].value;
  53015. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53016. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53017. this.buttonBack = this.browserGamepad.buttons[8].value;
  53018. this.buttonStart = this.browserGamepad.buttons[9].value;
  53019. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53020. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53021. this.dPadUp = this.browserGamepad.buttons[12].value;
  53022. this.dPadDown = this.browserGamepad.buttons[13].value;
  53023. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53024. this.dPadRight = this.browserGamepad.buttons[15].value;
  53025. }
  53026. };
  53027. return Xbox360Pad;
  53028. }(Gamepad));
  53029. BABYLON.Xbox360Pad = Xbox360Pad;
  53030. })(BABYLON || (BABYLON = {}));
  53031. //# sourceMappingURL=babylon.gamepads.js.map
  53032. var BABYLON;
  53033. (function (BABYLON) {
  53034. var PoseEnabledControllerType;
  53035. (function (PoseEnabledControllerType) {
  53036. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  53037. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  53038. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  53039. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  53040. var PoseEnabledControllerHelper = (function () {
  53041. function PoseEnabledControllerHelper() {
  53042. }
  53043. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  53044. // for now, only Oculus and Vive are supported
  53045. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  53046. return new OculusTouchController(vrGamepad);
  53047. }
  53048. else {
  53049. return new ViveController(vrGamepad);
  53050. }
  53051. };
  53052. return PoseEnabledControllerHelper;
  53053. }());
  53054. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  53055. var PoseEnabledController = (function (_super) {
  53056. __extends(PoseEnabledController, _super);
  53057. function PoseEnabledController(vrGamepad) {
  53058. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  53059. _this.vrGamepad = vrGamepad;
  53060. _this.deviceScaleFactor = 1;
  53061. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  53062. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  53063. _this.controllerType = PoseEnabledControllerType.GENERIC;
  53064. _this.position = BABYLON.Vector3.Zero();
  53065. _this.rotationQuaternion = new BABYLON.Quaternion();
  53066. _this.devicePosition = BABYLON.Vector3.Zero();
  53067. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  53068. _this._calculatedPosition = BABYLON.Vector3.Zero();
  53069. _this._calculatedRotation = new BABYLON.Quaternion();
  53070. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  53071. return _this;
  53072. }
  53073. PoseEnabledController.prototype.update = function () {
  53074. _super.prototype.update.call(this);
  53075. var pose = this.vrGamepad.pose;
  53076. this.updateFromDevice(pose);
  53077. if (this._mesh) {
  53078. this._mesh.position.copyFrom(this._calculatedPosition);
  53079. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  53080. }
  53081. };
  53082. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  53083. if (poseData) {
  53084. this.rawPose = poseData;
  53085. if (poseData.position) {
  53086. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  53087. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  53088. this.devicePosition.z *= -1;
  53089. }
  53090. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  53091. this._calculatedPosition.addInPlace(this.position);
  53092. }
  53093. if (poseData.orientation) {
  53094. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  53095. if (this._mesh) {
  53096. if (this._mesh.getScene().useRightHandedSystem) {
  53097. this.deviceRotationQuaternion.z *= -1;
  53098. this.deviceRotationQuaternion.w *= -1;
  53099. }
  53100. else {
  53101. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  53102. }
  53103. }
  53104. // if the camera is set, rotate to the camera's rotation
  53105. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  53106. }
  53107. }
  53108. };
  53109. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  53110. if (this._mesh) {
  53111. this._mesh.parent = undefined;
  53112. }
  53113. this._mesh = mesh;
  53114. if (this._poseControlledCamera) {
  53115. this._mesh.parent = this._poseControlledCamera;
  53116. }
  53117. if (!this._mesh.rotationQuaternion) {
  53118. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  53119. }
  53120. };
  53121. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  53122. this._poseControlledCamera = camera;
  53123. if (this._mesh) {
  53124. this._mesh.parent = this._poseControlledCamera;
  53125. }
  53126. };
  53127. PoseEnabledController.prototype.detachMesh = function () {
  53128. this._mesh = undefined;
  53129. };
  53130. return PoseEnabledController;
  53131. }(BABYLON.Gamepad));
  53132. BABYLON.PoseEnabledController = PoseEnabledController;
  53133. var WebVRController = (function (_super) {
  53134. __extends(WebVRController, _super);
  53135. function WebVRController(vrGamepad) {
  53136. var _this = _super.call(this, vrGamepad) || this;
  53137. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  53138. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  53139. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  53140. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  53141. _this.onPadStateChangedObservable = new BABYLON.Observable();
  53142. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  53143. _this.pad = { x: 0, y: 0 };
  53144. // avoid GC, store state in a tmp object
  53145. _this._changes = {
  53146. pressChanged: false,
  53147. touchChanged: false,
  53148. valueChanged: false,
  53149. changed: false
  53150. };
  53151. _this._buttons = new Array(vrGamepad.buttons.length);
  53152. _this.hand = vrGamepad.hand;
  53153. return _this;
  53154. }
  53155. WebVRController.prototype.onButtonStateChange = function (callback) {
  53156. this._onButtonStateChange = callback;
  53157. };
  53158. WebVRController.prototype.update = function () {
  53159. _super.prototype.update.call(this);
  53160. for (var index = 0; index < this._buttons.length; index++) {
  53161. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  53162. }
  53163. ;
  53164. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  53165. this.pad.x = this.leftStick.x;
  53166. this.pad.y = this.leftStick.y;
  53167. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  53168. }
  53169. };
  53170. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  53171. if (!currentState) {
  53172. this._buttons[buttonIndex] = {
  53173. pressed: newState.pressed,
  53174. touched: newState.touched,
  53175. value: newState.value
  53176. };
  53177. return;
  53178. }
  53179. this._checkChanges(newState, currentState);
  53180. if (this._changes.changed) {
  53181. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  53182. this.handleButtonChange(buttonIndex, newState, this._changes);
  53183. }
  53184. this._buttons[buttonIndex].pressed = newState.pressed;
  53185. this._buttons[buttonIndex].touched = newState.touched;
  53186. // oculus triggers are never 0, thou not touched.
  53187. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  53188. };
  53189. WebVRController.prototype._checkChanges = function (newState, currentState) {
  53190. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  53191. this._changes.touchChanged = newState.touched !== currentState.touched;
  53192. this._changes.valueChanged = newState.value !== currentState.value;
  53193. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  53194. return this._changes;
  53195. };
  53196. return WebVRController;
  53197. }(PoseEnabledController));
  53198. BABYLON.WebVRController = WebVRController;
  53199. var OculusTouchController = (function (_super) {
  53200. __extends(OculusTouchController, _super);
  53201. function OculusTouchController(vrGamepad) {
  53202. var _this = _super.call(this, vrGamepad) || this;
  53203. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  53204. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  53205. _this.controllerType = PoseEnabledControllerType.OCULUS;
  53206. return _this;
  53207. }
  53208. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  53209. var _this = this;
  53210. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  53211. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  53212. /*
  53213. Parent Mesh name: oculus_touch_left
  53214. - body
  53215. - trigger
  53216. - thumbstick
  53217. - grip
  53218. - button_y
  53219. - button_x
  53220. - button_enter
  53221. */
  53222. _this._defaultModel = newMeshes[1];
  53223. if (meshLoaded) {
  53224. meshLoaded(_this._defaultModel);
  53225. }
  53226. _this.attachToMesh(_this._defaultModel);
  53227. });
  53228. };
  53229. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  53230. // helper getters for left and right hand.
  53231. get: function () {
  53232. if (this.hand === 'right') {
  53233. return this.onMainButtonStateChangedObservable;
  53234. }
  53235. else {
  53236. throw new Error('No A button on left hand');
  53237. }
  53238. },
  53239. enumerable: true,
  53240. configurable: true
  53241. });
  53242. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  53243. get: function () {
  53244. if (this.hand === 'right') {
  53245. return this.onSecondaryButtonStateChangedObservable;
  53246. }
  53247. else {
  53248. throw new Error('No B button on left hand');
  53249. }
  53250. },
  53251. enumerable: true,
  53252. configurable: true
  53253. });
  53254. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  53255. get: function () {
  53256. if (this.hand === 'left') {
  53257. return this.onMainButtonStateChangedObservable;
  53258. }
  53259. else {
  53260. throw new Error('No X button on right hand');
  53261. }
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  53267. get: function () {
  53268. if (this.hand === 'left') {
  53269. return this.onSecondaryButtonStateChangedObservable;
  53270. }
  53271. else {
  53272. throw new Error('No Y button on right hand');
  53273. }
  53274. },
  53275. enumerable: true,
  53276. configurable: true
  53277. });
  53278. /*
  53279. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  53280. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  53281. 2) secondary trigger (same)
  53282. 3) A (right) X (left), touch, pressed = value
  53283. 4) B / Y
  53284. 5) thumb rest
  53285. */
  53286. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  53287. var notifyObject = state; //{ state: state, changes: changes };
  53288. switch (buttonIdx) {
  53289. case 0:
  53290. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  53291. return;
  53292. case 1:
  53293. if (this._defaultModel) {
  53294. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  53295. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  53296. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  53297. }
  53298. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  53299. return;
  53300. case 2:
  53301. if (this._defaultModel) {
  53302. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  53303. }
  53304. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  53305. return;
  53306. case 3:
  53307. if (this._defaultModel) {
  53308. if (notifyObject.pressed) {
  53309. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  53310. }
  53311. else {
  53312. (this._defaultModel.getChildren()[1]).position.y = 0;
  53313. }
  53314. }
  53315. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  53316. return;
  53317. case 4:
  53318. if (this._defaultModel) {
  53319. if (notifyObject.pressed) {
  53320. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  53321. }
  53322. else {
  53323. (this._defaultModel.getChildren()[2]).position.y = 0;
  53324. }
  53325. }
  53326. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  53327. return;
  53328. case 5:
  53329. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  53330. return;
  53331. }
  53332. };
  53333. return OculusTouchController;
  53334. }(WebVRController));
  53335. BABYLON.OculusTouchController = OculusTouchController;
  53336. var ViveController = (function (_super) {
  53337. __extends(ViveController, _super);
  53338. function ViveController(vrGamepad) {
  53339. var _this = _super.call(this, vrGamepad) || this;
  53340. _this.controllerType = PoseEnabledControllerType.VIVE;
  53341. return _this;
  53342. }
  53343. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  53344. var _this = this;
  53345. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  53346. /*
  53347. Parent Mesh name: ViveWand
  53348. - body
  53349. - r_gripper
  53350. - l_gripper
  53351. - menu_button
  53352. - system_button
  53353. - trackpad
  53354. - trigger
  53355. - LED
  53356. */
  53357. _this._defaultModel = newMeshes[1];
  53358. if (meshLoaded) {
  53359. meshLoaded(_this._defaultModel);
  53360. }
  53361. _this.attachToMesh(_this._defaultModel);
  53362. });
  53363. };
  53364. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  53365. get: function () {
  53366. return this.onMainButtonStateChangedObservable;
  53367. },
  53368. enumerable: true,
  53369. configurable: true
  53370. });
  53371. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  53372. get: function () {
  53373. return this.onMainButtonStateChangedObservable;
  53374. },
  53375. enumerable: true,
  53376. configurable: true
  53377. });
  53378. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  53379. get: function () {
  53380. return this.onSecondaryButtonStateChangedObservable;
  53381. },
  53382. enumerable: true,
  53383. configurable: true
  53384. });
  53385. /**
  53386. * Vive mapping:
  53387. * 0: touchpad
  53388. * 1: trigger
  53389. * 2: left AND right buttons
  53390. * 3: menu button
  53391. */
  53392. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  53393. var notifyObject = state; //{ state: state, changes: changes };
  53394. switch (buttonIdx) {
  53395. case 0:
  53396. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  53397. return;
  53398. case 1:
  53399. if (this._defaultModel) {
  53400. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  53401. }
  53402. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  53403. return;
  53404. case 2:
  53405. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  53406. return;
  53407. case 3:
  53408. if (this._defaultModel) {
  53409. if (notifyObject.pressed) {
  53410. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  53411. }
  53412. else {
  53413. (this._defaultModel.getChildren()[2]).position.y = 0;
  53414. }
  53415. }
  53416. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  53417. return;
  53418. }
  53419. };
  53420. return ViveController;
  53421. }(WebVRController));
  53422. BABYLON.ViveController = ViveController;
  53423. })(BABYLON || (BABYLON = {}));
  53424. //# sourceMappingURL=babylon.extendedGamepad.js.map
  53425. /// <reference path="babylon.universalCamera.ts" />
  53426. var BABYLON;
  53427. (function (BABYLON) {
  53428. // We're mainly based on the logic defined into the FreeCamera code
  53429. var GamepadCamera = (function (_super) {
  53430. __extends(GamepadCamera, _super);
  53431. //-- end properties for backward compatibility for inputs
  53432. function GamepadCamera(name, position, scene) {
  53433. return _super.call(this, name, position, scene) || this;
  53434. }
  53435. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53436. //-- Begin properties for backward compatibility for inputs
  53437. get: function () {
  53438. var gamepad = this.inputs.attached["gamepad"];
  53439. if (gamepad)
  53440. return gamepad.gamepadAngularSensibility;
  53441. },
  53442. set: function (value) {
  53443. var gamepad = this.inputs.attached["gamepad"];
  53444. if (gamepad)
  53445. gamepad.gamepadAngularSensibility = value;
  53446. },
  53447. enumerable: true,
  53448. configurable: true
  53449. });
  53450. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53451. get: function () {
  53452. var gamepad = this.inputs.attached["gamepad"];
  53453. if (gamepad)
  53454. return gamepad.gamepadMoveSensibility;
  53455. },
  53456. set: function (value) {
  53457. var gamepad = this.inputs.attached["gamepad"];
  53458. if (gamepad)
  53459. gamepad.gamepadMoveSensibility = value;
  53460. },
  53461. enumerable: true,
  53462. configurable: true
  53463. });
  53464. GamepadCamera.prototype.getClassName = function () {
  53465. return "GamepadCamera";
  53466. };
  53467. return GamepadCamera;
  53468. }(BABYLON.UniversalCamera));
  53469. BABYLON.GamepadCamera = GamepadCamera;
  53470. })(BABYLON || (BABYLON = {}));
  53471. //# sourceMappingURL=babylon.gamepadCamera.js.map
  53472. var BABYLON;
  53473. (function (BABYLON) {
  53474. var Analyser = (function () {
  53475. function Analyser(scene) {
  53476. this.SMOOTHING = 0.75;
  53477. this.FFT_SIZE = 512;
  53478. this.BARGRAPHAMPLITUDE = 256;
  53479. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53480. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53481. this._scene = scene;
  53482. this._audioEngine = BABYLON.Engine.audioEngine;
  53483. if (this._audioEngine.canUseWebAudio) {
  53484. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53485. this._webAudioAnalyser.minDecibels = -140;
  53486. this._webAudioAnalyser.maxDecibels = 0;
  53487. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53488. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53489. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53490. }
  53491. }
  53492. Analyser.prototype.getFrequencyBinCount = function () {
  53493. if (this._audioEngine.canUseWebAudio) {
  53494. return this._webAudioAnalyser.frequencyBinCount;
  53495. }
  53496. else {
  53497. return 0;
  53498. }
  53499. };
  53500. Analyser.prototype.getByteFrequencyData = function () {
  53501. if (this._audioEngine.canUseWebAudio) {
  53502. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53503. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53504. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53505. }
  53506. return this._byteFreqs;
  53507. };
  53508. Analyser.prototype.getByteTimeDomainData = function () {
  53509. if (this._audioEngine.canUseWebAudio) {
  53510. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53511. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53512. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53513. }
  53514. return this._byteTime;
  53515. };
  53516. Analyser.prototype.getFloatFrequencyData = function () {
  53517. if (this._audioEngine.canUseWebAudio) {
  53518. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53519. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53520. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53521. }
  53522. return this._floatFreqs;
  53523. };
  53524. Analyser.prototype.drawDebugCanvas = function () {
  53525. var _this = this;
  53526. if (this._audioEngine.canUseWebAudio) {
  53527. if (!this._debugCanvas) {
  53528. this._debugCanvas = document.createElement("canvas");
  53529. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53530. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53531. this._debugCanvas.style.position = "absolute";
  53532. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53533. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53534. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53535. document.body.appendChild(this._debugCanvas);
  53536. this._registerFunc = function () {
  53537. _this.drawDebugCanvas();
  53538. };
  53539. this._scene.registerBeforeRender(this._registerFunc);
  53540. }
  53541. if (this._registerFunc) {
  53542. var workingArray = this.getByteFrequencyData();
  53543. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53544. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53545. // Draw the frequency domain chart.
  53546. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53547. var value = workingArray[i];
  53548. var percent = value / this.BARGRAPHAMPLITUDE;
  53549. var height = this.DEBUGCANVASSIZE.height * percent;
  53550. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53551. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53552. var hue = i / this.getFrequencyBinCount() * 360;
  53553. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53554. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53555. }
  53556. }
  53557. }
  53558. };
  53559. Analyser.prototype.stopDebugCanvas = function () {
  53560. if (this._debugCanvas) {
  53561. this._scene.unregisterBeforeRender(this._registerFunc);
  53562. this._registerFunc = null;
  53563. document.body.removeChild(this._debugCanvas);
  53564. this._debugCanvas = null;
  53565. this._debugCanvasContext = null;
  53566. }
  53567. };
  53568. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53569. if (this._audioEngine.canUseWebAudio) {
  53570. inputAudioNode.connect(this._webAudioAnalyser);
  53571. this._webAudioAnalyser.connect(outputAudioNode);
  53572. }
  53573. };
  53574. Analyser.prototype.dispose = function () {
  53575. if (this._audioEngine.canUseWebAudio) {
  53576. this._webAudioAnalyser.disconnect();
  53577. }
  53578. };
  53579. return Analyser;
  53580. }());
  53581. BABYLON.Analyser = Analyser;
  53582. })(BABYLON || (BABYLON = {}));
  53583. //# sourceMappingURL=babylon.analyser.js.map
  53584. var BABYLON;
  53585. (function (BABYLON) {
  53586. var DepthRenderer = (function () {
  53587. function DepthRenderer(scene, type) {
  53588. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53589. var _this = this;
  53590. this._viewMatrix = BABYLON.Matrix.Zero();
  53591. this._projectionMatrix = BABYLON.Matrix.Zero();
  53592. this._transformMatrix = BABYLON.Matrix.Zero();
  53593. this._worldViewProjection = BABYLON.Matrix.Zero();
  53594. this._scene = scene;
  53595. var engine = scene.getEngine();
  53596. // Render target
  53597. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53598. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53599. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53600. this._depthMap.refreshRate = 1;
  53601. this._depthMap.renderParticles = false;
  53602. this._depthMap.renderList = null;
  53603. // set default depth value to 1.0 (far away)
  53604. this._depthMap.onClearObservable.add(function (engine) {
  53605. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53606. });
  53607. // Custom render function
  53608. var renderSubMesh = function (subMesh) {
  53609. var mesh = subMesh.getRenderingMesh();
  53610. var scene = _this._scene;
  53611. var engine = scene.getEngine();
  53612. // Culling
  53613. engine.setState(subMesh.getMaterial().backFaceCulling);
  53614. // Managing instances
  53615. var batch = mesh._getInstancesRenderList(subMesh._id);
  53616. if (batch.mustReturn) {
  53617. return;
  53618. }
  53619. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53620. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53621. engine.enableEffect(_this._effect);
  53622. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53623. var material = subMesh.getMaterial();
  53624. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53625. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53626. // Alpha test
  53627. if (material && material.needAlphaTesting()) {
  53628. var alphaTexture = material.getAlphaTestTexture();
  53629. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53630. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53631. }
  53632. // Bones
  53633. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53634. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53635. }
  53636. // Draw
  53637. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53638. }
  53639. };
  53640. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53641. var index;
  53642. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53643. renderSubMesh(opaqueSubMeshes.data[index]);
  53644. }
  53645. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53646. renderSubMesh(alphaTestSubMeshes.data[index]);
  53647. }
  53648. };
  53649. }
  53650. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53651. var material = subMesh.getMaterial();
  53652. if (material.disableDepthWrite) {
  53653. return false;
  53654. }
  53655. var defines = [];
  53656. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53657. var mesh = subMesh.getMesh();
  53658. var scene = mesh.getScene();
  53659. // Alpha test
  53660. if (material && material.needAlphaTesting()) {
  53661. defines.push("#define ALPHATEST");
  53662. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53663. attribs.push(BABYLON.VertexBuffer.UVKind);
  53664. defines.push("#define UV1");
  53665. }
  53666. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53667. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53668. defines.push("#define UV2");
  53669. }
  53670. }
  53671. // Bones
  53672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53675. if (mesh.numBoneInfluencers > 4) {
  53676. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53677. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53678. }
  53679. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53680. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53681. }
  53682. else {
  53683. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53684. }
  53685. // Instances
  53686. if (useInstances) {
  53687. defines.push("#define INSTANCES");
  53688. attribs.push("world0");
  53689. attribs.push("world1");
  53690. attribs.push("world2");
  53691. attribs.push("world3");
  53692. }
  53693. // Get correct effect
  53694. var join = defines.join("\n");
  53695. if (this._cachedDefines !== join) {
  53696. this._cachedDefines = join;
  53697. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53698. }
  53699. return this._effect.isReady();
  53700. };
  53701. DepthRenderer.prototype.getDepthMap = function () {
  53702. return this._depthMap;
  53703. };
  53704. // Methods
  53705. DepthRenderer.prototype.dispose = function () {
  53706. this._depthMap.dispose();
  53707. };
  53708. return DepthRenderer;
  53709. }());
  53710. BABYLON.DepthRenderer = DepthRenderer;
  53711. })(BABYLON || (BABYLON = {}));
  53712. //# sourceMappingURL=babylon.depthRenderer.js.map
  53713. var BABYLON;
  53714. (function (BABYLON) {
  53715. var SSAORenderingPipeline = (function (_super) {
  53716. __extends(SSAORenderingPipeline, _super);
  53717. /**
  53718. * @constructor
  53719. * @param {string} name - The rendering pipeline name
  53720. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53721. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  53722. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53723. */
  53724. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53725. var _this = _super.call(this, scene.getEngine(), name) || this;
  53726. // Members
  53727. /**
  53728. * The PassPostProcess id in the pipeline that contains the original scene color
  53729. * @type {string}
  53730. */
  53731. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53732. /**
  53733. * The SSAO PostProcess id in the pipeline
  53734. * @type {string}
  53735. */
  53736. _this.SSAORenderEffect = "SSAORenderEffect";
  53737. /**
  53738. * The horizontal blur PostProcess id in the pipeline
  53739. * @type {string}
  53740. */
  53741. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53742. /**
  53743. * The vertical blur PostProcess id in the pipeline
  53744. * @type {string}
  53745. */
  53746. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53747. /**
  53748. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53749. * @type {string}
  53750. */
  53751. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53752. /**
  53753. * The output strength of the SSAO post-process. Default value is 1.0.
  53754. * @type {number}
  53755. */
  53756. _this.totalStrength = 1.0;
  53757. /**
  53758. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53759. * @type {number}
  53760. */
  53761. _this.radius = 0.0001;
  53762. /**
  53763. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53764. * Must not be equal to fallOff and superior to fallOff.
  53765. * Default value is 0.975
  53766. * @type {number}
  53767. */
  53768. _this.area = 0.0075;
  53769. /**
  53770. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53771. * Must not be equal to area and inferior to area.
  53772. * Default value is 0.0
  53773. * @type {number}
  53774. */
  53775. _this.fallOff = 0.000001;
  53776. /**
  53777. * The base color of the SSAO post-process
  53778. * The final result is "base + ssao" between [0, 1]
  53779. * @type {number}
  53780. */
  53781. _this.base = 0.5;
  53782. _this._firstUpdate = true;
  53783. _this._scene = scene;
  53784. // Set up assets
  53785. _this._createRandomTexture();
  53786. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53787. var ssaoRatio = ratio.ssaoRatio || ratio;
  53788. var combineRatio = ratio.combineRatio || ratio;
  53789. _this._ratio = {
  53790. ssaoRatio: ssaoRatio,
  53791. combineRatio: combineRatio
  53792. };
  53793. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53794. _this._createSSAOPostProcess(ssaoRatio);
  53795. _this._createBlurPostProcess(ssaoRatio);
  53796. _this._createSSAOCombinePostProcess(combineRatio);
  53797. // Set up pipeline
  53798. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53799. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53800. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53801. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53802. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53803. // Finish
  53804. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53805. if (cameras)
  53806. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53807. return _this;
  53808. }
  53809. // Public Methods
  53810. /**
  53811. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53812. */
  53813. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53814. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53815. for (var i = 0; i < this._scene.cameras.length; i++) {
  53816. var camera = this._scene.cameras[i];
  53817. this._originalColorPostProcess.dispose(camera);
  53818. this._ssaoPostProcess.dispose(camera);
  53819. this._blurHPostProcess.dispose(camera);
  53820. this._blurVPostProcess.dispose(camera);
  53821. this._ssaoCombinePostProcess.dispose(camera);
  53822. }
  53823. this._randomTexture.dispose();
  53824. if (disableDepthRender)
  53825. this._scene.disableDepthRenderer();
  53826. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53827. _super.prototype.dispose.call(this);
  53828. };
  53829. // Private Methods
  53830. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53831. var _this = this;
  53832. /*
  53833. var samplerOffsets = [
  53834. -8.0, -6.0, -4.0, -2.0,
  53835. 0.0,
  53836. 2.0, 4.0, 6.0, 8.0
  53837. ];
  53838. */
  53839. var samples = 16;
  53840. var samplerOffsets = [];
  53841. for (var i = -8; i < 8; i++) {
  53842. samplerOffsets.push(i * 2);
  53843. }
  53844. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  53845. this._blurHPostProcess.onApply = function (effect) {
  53846. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53847. effect.setTexture("depthSampler", _this._depthTexture);
  53848. if (_this._firstUpdate) {
  53849. effect.setArray("samplerOffsets", samplerOffsets);
  53850. }
  53851. };
  53852. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  53853. this._blurVPostProcess.onApply = function (effect) {
  53854. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53855. effect.setTexture("depthSampler", _this._depthTexture);
  53856. if (_this._firstUpdate) {
  53857. effect.setArray("samplerOffsets", samplerOffsets);
  53858. _this._firstUpdate = false;
  53859. }
  53860. };
  53861. };
  53862. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53863. var _this = this;
  53864. var numSamples = 16;
  53865. var sampleSphere = [
  53866. 0.5381, 0.1856, -0.4319,
  53867. 0.1379, 0.2486, 0.4430,
  53868. 0.3371, 0.5679, -0.0057,
  53869. -0.6999, -0.0451, -0.0019,
  53870. 0.0689, -0.1598, -0.8547,
  53871. 0.0560, 0.0069, -0.1843,
  53872. -0.0146, 0.1402, 0.0762,
  53873. 0.0100, -0.1924, -0.0344,
  53874. -0.3577, -0.5301, -0.4358,
  53875. -0.3169, 0.1063, 0.0158,
  53876. 0.0103, -0.5869, 0.0046,
  53877. -0.0897, -0.4940, 0.3287,
  53878. 0.7119, -0.0154, -0.0918,
  53879. -0.0533, 0.0596, -0.5411,
  53880. 0.0352, -0.0631, 0.5460,
  53881. -0.4776, 0.2847, -0.0271
  53882. ];
  53883. var samplesFactor = 1.0 / numSamples;
  53884. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53885. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53886. "area", "fallOff", "base", "range", "viewport"
  53887. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53888. var viewport = new BABYLON.Vector2(0, 0);
  53889. this._ssaoPostProcess.onApply = function (effect) {
  53890. if (_this._firstUpdate) {
  53891. effect.setArray3("sampleSphere", sampleSphere);
  53892. effect.setFloat("samplesFactor", samplesFactor);
  53893. effect.setFloat("randTextureTiles", 4.0);
  53894. }
  53895. effect.setFloat("totalStrength", _this.totalStrength);
  53896. effect.setFloat("radius", _this.radius);
  53897. effect.setFloat("area", _this.area);
  53898. effect.setFloat("fallOff", _this.fallOff);
  53899. effect.setFloat("base", _this.base);
  53900. effect.setTexture("textureSampler", _this._depthTexture);
  53901. effect.setTexture("randomSampler", _this._randomTexture);
  53902. };
  53903. };
  53904. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53905. var _this = this;
  53906. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53907. this._ssaoCombinePostProcess.onApply = function (effect) {
  53908. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53909. };
  53910. };
  53911. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53912. var size = 512;
  53913. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53914. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53915. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53916. var context = this._randomTexture.getContext();
  53917. var rand = function (min, max) {
  53918. return Math.random() * (max - min) + min;
  53919. };
  53920. var randVector = BABYLON.Vector3.Zero();
  53921. for (var x = 0; x < size; x++) {
  53922. for (var y = 0; y < size; y++) {
  53923. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53924. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53925. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53926. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53927. context.fillRect(x, y, 1, 1);
  53928. }
  53929. }
  53930. this._randomTexture.update(false);
  53931. };
  53932. return SSAORenderingPipeline;
  53933. }(BABYLON.PostProcessRenderPipeline));
  53934. __decorate([
  53935. BABYLON.serialize()
  53936. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53937. __decorate([
  53938. BABYLON.serialize()
  53939. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53940. __decorate([
  53941. BABYLON.serialize()
  53942. ], SSAORenderingPipeline.prototype, "area", void 0);
  53943. __decorate([
  53944. BABYLON.serialize()
  53945. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53946. __decorate([
  53947. BABYLON.serialize()
  53948. ], SSAORenderingPipeline.prototype, "base", void 0);
  53949. __decorate([
  53950. BABYLON.serialize()
  53951. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53952. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53953. })(BABYLON || (BABYLON = {}));
  53954. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53955. var BABYLON;
  53956. (function (BABYLON) {
  53957. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53958. var VolumetricLightScatteringPostProcess = (function (_super) {
  53959. __extends(VolumetricLightScatteringPostProcess, _super);
  53960. /**
  53961. * @constructor
  53962. * @param {string} name - The post-process name
  53963. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  53964. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53965. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53966. * @param {number} samples - The post-process quality, default 100
  53967. * @param {number} samplingMode - The post-process filtering mode
  53968. * @param {BABYLON.Engine} engine - The babylon engine
  53969. * @param {boolean} reusable - If the post-process is reusable
  53970. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53971. */
  53972. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53973. if (samples === void 0) { samples = 100; }
  53974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53975. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  53976. _this._screenCoordinates = BABYLON.Vector2.Zero();
  53977. /**
  53978. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53979. * @type {Vector3}
  53980. */
  53981. _this.customMeshPosition = BABYLON.Vector3.Zero();
  53982. /**
  53983. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53984. * @type {boolean}
  53985. */
  53986. _this.useCustomMeshPosition = false;
  53987. /**
  53988. * If the post-process should inverse the light scattering direction
  53989. * @type {boolean}
  53990. */
  53991. _this.invert = true;
  53992. /**
  53993. * Array containing the excluded meshes not rendered in the internal pass
  53994. */
  53995. _this.excludedMeshes = new Array();
  53996. /**
  53997. * Controls the overall intensity of the post-process
  53998. * @type {number}
  53999. */
  54000. _this.exposure = 0.3;
  54001. /**
  54002. * Dissipates each sample's contribution in range [0, 1]
  54003. * @type {number}
  54004. */
  54005. _this.decay = 0.96815;
  54006. /**
  54007. * Controls the overall intensity of each sample
  54008. * @type {number}
  54009. */
  54010. _this.weight = 0.58767;
  54011. /**
  54012. * Controls the density of each sample
  54013. * @type {number}
  54014. */
  54015. _this.density = 0.926;
  54016. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  54017. var engine = scene.getEngine();
  54018. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54019. // Configure mesh
  54020. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  54021. // Configure
  54022. _this._createPass(scene, ratio.passRatio || ratio);
  54023. _this.onActivate = function (camera) {
  54024. if (!_this.isSupported) {
  54025. _this.dispose(camera);
  54026. }
  54027. _this.onActivate = null;
  54028. };
  54029. _this.onApplyObservable.add(function (effect) {
  54030. _this._updateMeshScreenCoordinates(scene);
  54031. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  54032. effect.setFloat("exposure", _this.exposure);
  54033. effect.setFloat("decay", _this.decay);
  54034. effect.setFloat("weight", _this.weight);
  54035. effect.setFloat("density", _this.density);
  54036. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  54037. });
  54038. return _this;
  54039. }
  54040. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  54041. get: function () {
  54042. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54043. return false;
  54044. },
  54045. set: function (useDiffuseColor) {
  54046. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54047. },
  54048. enumerable: true,
  54049. configurable: true
  54050. });
  54051. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  54052. var mesh = subMesh.getMesh();
  54053. // Render this.mesh as default
  54054. if (mesh === this.mesh) {
  54055. return mesh.material.isReady(mesh);
  54056. }
  54057. var defines = [];
  54058. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54059. var material = subMesh.getMaterial();
  54060. var needUV = false;
  54061. // Alpha test
  54062. if (material) {
  54063. if (material.needAlphaTesting()) {
  54064. defines.push("#define ALPHATEST");
  54065. }
  54066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54067. attribs.push(BABYLON.VertexBuffer.UVKind);
  54068. defines.push("#define UV1");
  54069. }
  54070. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54072. defines.push("#define UV2");
  54073. }
  54074. }
  54075. // Bones
  54076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54079. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54080. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54081. }
  54082. else {
  54083. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54084. }
  54085. // Instances
  54086. if (useInstances) {
  54087. defines.push("#define INSTANCES");
  54088. attribs.push("world0");
  54089. attribs.push("world1");
  54090. attribs.push("world2");
  54091. attribs.push("world3");
  54092. }
  54093. // Get correct effect
  54094. var join = defines.join("\n");
  54095. if (this._cachedDefines !== join) {
  54096. this._cachedDefines = join;
  54097. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  54098. }
  54099. return this._volumetricLightScatteringPass.isReady();
  54100. };
  54101. /**
  54102. * Sets the new light position for light scattering effect
  54103. * @param {BABYLON.Vector3} The new custom light position
  54104. */
  54105. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  54106. this.customMeshPosition = position;
  54107. };
  54108. /**
  54109. * Returns the light position for light scattering effect
  54110. * @return {BABYLON.Vector3} The custom light position
  54111. */
  54112. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  54113. return this.customMeshPosition;
  54114. };
  54115. /**
  54116. * Disposes the internal assets and detaches the post-process from the camera
  54117. */
  54118. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  54119. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  54120. if (rttIndex !== -1) {
  54121. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  54122. }
  54123. this._volumetricLightScatteringRTT.dispose();
  54124. _super.prototype.dispose.call(this, camera);
  54125. };
  54126. /**
  54127. * Returns the render target texture used by the post-process
  54128. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  54129. */
  54130. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  54131. return this._volumetricLightScatteringRTT;
  54132. };
  54133. // Private methods
  54134. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  54135. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  54136. return true;
  54137. }
  54138. return false;
  54139. };
  54140. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  54141. var _this = this;
  54142. var engine = scene.getEngine();
  54143. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54144. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54145. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54146. this._volumetricLightScatteringRTT.renderList = null;
  54147. this._volumetricLightScatteringRTT.renderParticles = false;
  54148. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  54149. // Custom render function for submeshes
  54150. var renderSubMesh = function (subMesh) {
  54151. var mesh = subMesh.getRenderingMesh();
  54152. if (_this._meshExcluded(mesh)) {
  54153. return;
  54154. }
  54155. var scene = mesh.getScene();
  54156. var engine = scene.getEngine();
  54157. // Culling
  54158. engine.setState(subMesh.getMaterial().backFaceCulling);
  54159. // Managing instances
  54160. var batch = mesh._getInstancesRenderList(subMesh._id);
  54161. if (batch.mustReturn) {
  54162. return;
  54163. }
  54164. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54165. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54166. var effect = _this._volumetricLightScatteringPass;
  54167. if (mesh === _this.mesh) {
  54168. if (subMesh.effect) {
  54169. effect = subMesh.effect;
  54170. }
  54171. else {
  54172. effect = subMesh.getMaterial().getEffect();
  54173. }
  54174. }
  54175. engine.enableEffect(effect);
  54176. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  54177. if (mesh === _this.mesh) {
  54178. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  54179. }
  54180. else {
  54181. var material = subMesh.getMaterial();
  54182. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  54183. // Alpha test
  54184. if (material && material.needAlphaTesting()) {
  54185. var alphaTexture = material.getAlphaTestTexture();
  54186. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  54187. if (alphaTexture) {
  54188. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54189. }
  54190. }
  54191. // Bones
  54192. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54193. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54194. }
  54195. }
  54196. // Draw
  54197. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  54198. }
  54199. };
  54200. // Render target texture callbacks
  54201. var savedSceneClearColor;
  54202. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  54203. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  54204. savedSceneClearColor = scene.clearColor;
  54205. scene.clearColor = sceneClearColor;
  54206. });
  54207. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  54208. scene.clearColor = savedSceneClearColor;
  54209. });
  54210. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  54211. var engine = scene.getEngine();
  54212. var index;
  54213. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54214. renderSubMesh(opaqueSubMeshes.data[index]);
  54215. }
  54216. engine.setAlphaTesting(true);
  54217. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54218. renderSubMesh(alphaTestSubMeshes.data[index]);
  54219. }
  54220. engine.setAlphaTesting(false);
  54221. if (transparentSubMeshes.length) {
  54222. // Sort sub meshes
  54223. for (index = 0; index < transparentSubMeshes.length; index++) {
  54224. var submesh = transparentSubMeshes.data[index];
  54225. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  54226. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  54227. }
  54228. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  54229. sortedArray.sort(function (a, b) {
  54230. // Alpha index first
  54231. if (a._alphaIndex > b._alphaIndex) {
  54232. return 1;
  54233. }
  54234. if (a._alphaIndex < b._alphaIndex) {
  54235. return -1;
  54236. }
  54237. // Then distance to camera
  54238. if (a._distanceToCamera < b._distanceToCamera) {
  54239. return 1;
  54240. }
  54241. if (a._distanceToCamera > b._distanceToCamera) {
  54242. return -1;
  54243. }
  54244. return 0;
  54245. });
  54246. // Render sub meshes
  54247. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54248. for (index = 0; index < sortedArray.length; index++) {
  54249. renderSubMesh(sortedArray[index]);
  54250. }
  54251. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54252. }
  54253. };
  54254. };
  54255. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54256. var transform = scene.getTransformMatrix();
  54257. var meshPosition;
  54258. if (this.useCustomMeshPosition) {
  54259. meshPosition = this.customMeshPosition;
  54260. }
  54261. else if (this.attachedNode) {
  54262. meshPosition = this.attachedNode.position;
  54263. }
  54264. else {
  54265. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54266. }
  54267. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54268. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54269. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54270. if (this.invert)
  54271. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54272. };
  54273. // Static methods
  54274. /**
  54275. * Creates a default mesh for the Volumeric Light Scattering post-process
  54276. * @param {string} The mesh name
  54277. * @param {BABYLON.Scene} The scene where to create the mesh
  54278. * @return {BABYLON.Mesh} the default mesh
  54279. */
  54280. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54281. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54282. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54283. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54284. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54285. mesh.material = material;
  54286. return mesh;
  54287. };
  54288. return VolumetricLightScatteringPostProcess;
  54289. }(BABYLON.PostProcess));
  54290. __decorate([
  54291. BABYLON.serializeAsVector3()
  54292. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54293. __decorate([
  54294. BABYLON.serialize()
  54295. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54296. __decorate([
  54297. BABYLON.serialize()
  54298. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54299. __decorate([
  54300. BABYLON.serializeAsMeshReference()
  54301. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54302. __decorate([
  54303. BABYLON.serialize()
  54304. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54305. __decorate([
  54306. BABYLON.serialize()
  54307. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54308. __decorate([
  54309. BABYLON.serialize()
  54310. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54311. __decorate([
  54312. BABYLON.serialize()
  54313. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54314. __decorate([
  54315. BABYLON.serialize()
  54316. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54317. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54318. })(BABYLON || (BABYLON = {}));
  54319. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  54320. // BABYLON.JS Chromatic Aberration GLSL Shader
  54321. // Author: Olivier Guyot
  54322. // Separates very slightly R, G and B colors on the edges of the screen
  54323. // Inspired by Francois Tarlier & Martins Upitis
  54324. var BABYLON;
  54325. (function (BABYLON) {
  54326. var LensRenderingPipeline = (function (_super) {
  54327. __extends(LensRenderingPipeline, _super);
  54328. /**
  54329. * @constructor
  54330. *
  54331. * Effect parameters are as follow:
  54332. * {
  54333. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54334. * edge_blur: number; // from 0 to x (1 for realism)
  54335. * distortion: number; // from 0 to x (1 for realism)
  54336. * grain_amount: number; // from 0 to 1
  54337. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54338. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54339. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54340. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54341. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54342. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54343. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54344. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54345. * }
  54346. * Note: if an effect parameter is unset, effect is disabled
  54347. *
  54348. * @param {string} name - The rendering pipeline name
  54349. * @param {object} parameters - An object containing all parameters (see above)
  54350. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54351. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  54352. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54353. */
  54354. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54355. if (ratio === void 0) { ratio = 1.0; }
  54356. var _this = _super.call(this, scene.getEngine(), name) || this;
  54357. // Lens effects can be of the following:
  54358. // - chromatic aberration (slight shift of RGB colors)
  54359. // - blur on the edge of the lens
  54360. // - lens distortion
  54361. // - depth-of-field blur & highlights enhancing
  54362. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54363. // - grain effect (noise or custom texture)
  54364. // Two additional texture samplers are needed:
  54365. // - depth map (for depth-of-field)
  54366. // - grain texture
  54367. /**
  54368. * The chromatic aberration PostProcess id in the pipeline
  54369. * @type {string}
  54370. */
  54371. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54372. /**
  54373. * The highlights enhancing PostProcess id in the pipeline
  54374. * @type {string}
  54375. */
  54376. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54377. /**
  54378. * The depth-of-field PostProcess id in the pipeline
  54379. * @type {string}
  54380. */
  54381. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54382. _this._scene = scene;
  54383. // Fetch texture samplers
  54384. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54385. if (parameters.grain_texture) {
  54386. _this._grainTexture = parameters.grain_texture;
  54387. }
  54388. else {
  54389. _this._createGrainTexture();
  54390. }
  54391. // save parameters
  54392. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54393. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54394. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54395. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  54396. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54397. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54398. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54399. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54400. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54401. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54402. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54403. // Create effects
  54404. _this._createChromaticAberrationPostProcess(ratio);
  54405. _this._createHighlightsPostProcess(ratio);
  54406. _this._createDepthOfFieldPostProcess(ratio / 4);
  54407. // Set up pipeline
  54408. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54409. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54411. if (_this._highlightsGain === -1) {
  54412. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  54413. }
  54414. // Finish
  54415. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54416. if (cameras) {
  54417. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54418. }
  54419. return _this;
  54420. }
  54421. // public methods (self explanatory)
  54422. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54423. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54424. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54425. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54426. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54427. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54428. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54429. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54430. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54431. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54432. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54433. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54434. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54435. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54436. };
  54437. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54438. this._highlightsPostProcess.updateEffect();
  54439. };
  54440. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54441. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54442. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54443. this._highlightsGain = amount;
  54444. };
  54445. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54446. if (this._highlightsGain === -1) {
  54447. this._highlightsGain = 1.0;
  54448. }
  54449. this._highlightsThreshold = amount;
  54450. };
  54451. LensRenderingPipeline.prototype.disableHighlights = function () {
  54452. this._highlightsGain = -1;
  54453. };
  54454. /**
  54455. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54456. */
  54457. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54458. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54459. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54460. this._chromaticAberrationPostProcess = undefined;
  54461. this._highlightsPostProcess = undefined;
  54462. this._depthOfFieldPostProcess = undefined;
  54463. this._grainTexture.dispose();
  54464. if (disableDepthRender)
  54465. this._scene.disableDepthRenderer();
  54466. };
  54467. // colors shifting and distortion
  54468. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54469. var _this = this;
  54470. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54471. [], // samplers
  54472. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54473. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54474. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54475. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54476. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54477. };
  54478. };
  54479. // highlights enhancing
  54480. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54481. var _this = this;
  54482. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54483. [], // samplers
  54484. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54485. this._highlightsPostProcess.onApply = function (effect) {
  54486. effect.setFloat('gain', _this._highlightsGain);
  54487. effect.setFloat('threshold', _this._highlightsThreshold);
  54488. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54489. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54490. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54491. };
  54492. };
  54493. // colors shifting and distortion
  54494. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54495. var _this = this;
  54496. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54497. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54498. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54499. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54500. this._depthOfFieldPostProcess.onApply = function (effect) {
  54501. effect.setTexture("depthSampler", _this._depthTexture);
  54502. effect.setTexture("grainSampler", _this._grainTexture);
  54503. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54504. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54505. effect.setFloat('grain_amount', _this._grainAmount);
  54506. effect.setBool('blur_noise', _this._blurNoise);
  54507. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54508. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54509. effect.setFloat('distortion', _this._distortion);
  54510. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54511. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54512. effect.setFloat('aperture', _this._dofAperture);
  54513. effect.setFloat('darken', _this._dofDarken);
  54514. effect.setFloat('edge_blur', _this._edgeBlur);
  54515. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54516. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54517. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54518. };
  54519. };
  54520. // creates a black and white random noise texture, 512x512
  54521. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54522. var size = 512;
  54523. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54524. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54525. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54526. var context = this._grainTexture.getContext();
  54527. var rand = function (min, max) {
  54528. return Math.random() * (max - min) + min;
  54529. };
  54530. var value;
  54531. for (var x = 0; x < size; x++) {
  54532. for (var y = 0; y < size; y++) {
  54533. value = Math.floor(rand(0.42, 0.58) * 255);
  54534. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54535. context.fillRect(x, y, 1, 1);
  54536. }
  54537. }
  54538. this._grainTexture.update(false);
  54539. };
  54540. return LensRenderingPipeline;
  54541. }(BABYLON.PostProcessRenderPipeline));
  54542. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54543. })(BABYLON || (BABYLON = {}));
  54544. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  54545. //
  54546. // This post-process allows the modification of rendered colors by using
  54547. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54548. //
  54549. // The object needs to be provided an url to a texture containing the color
  54550. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54551. // Use an image editing software to tweak the LUT to match your needs.
  54552. //
  54553. // For an example of a color LUT, see here:
  54554. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54555. // For explanations on color grading, see here:
  54556. // http://udn.epicgames.com/Three/ColorGrading.html
  54557. //
  54558. var BABYLON;
  54559. (function (BABYLON) {
  54560. var ColorCorrectionPostProcess = (function (_super) {
  54561. __extends(ColorCorrectionPostProcess, _super);
  54562. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54563. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54564. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54565. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54566. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54567. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54568. _this.onApply = function (effect) {
  54569. effect.setTexture("colorTable", _this._colorTableTexture);
  54570. };
  54571. return _this;
  54572. }
  54573. return ColorCorrectionPostProcess;
  54574. }(BABYLON.PostProcess));
  54575. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54576. })(BABYLON || (BABYLON = {}));
  54577. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54578. /// <reference path="babylon.freeCamera.ts" />
  54579. /// <reference path="babylon.arcRotateCamera.ts" />
  54580. /// <reference path="babylon.gamepadCamera.ts" />
  54581. /// <reference path="babylon.universalCamera.ts" />
  54582. var BABYLON;
  54583. (function (BABYLON) {
  54584. var AnaglyphFreeCamera = (function (_super) {
  54585. __extends(AnaglyphFreeCamera, _super);
  54586. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54587. var _this = _super.call(this, name, position, scene) || this;
  54588. _this.interaxialDistance = interaxialDistance;
  54589. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54590. return _this;
  54591. }
  54592. AnaglyphFreeCamera.prototype.getClassName = function () {
  54593. return "AnaglyphFreeCamera";
  54594. };
  54595. return AnaglyphFreeCamera;
  54596. }(BABYLON.FreeCamera));
  54597. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54598. var AnaglyphArcRotateCamera = (function (_super) {
  54599. __extends(AnaglyphArcRotateCamera, _super);
  54600. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54601. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  54602. _this.interaxialDistance = interaxialDistance;
  54603. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54604. return _this;
  54605. }
  54606. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  54607. return "AnaglyphArcRotateCamera";
  54608. };
  54609. return AnaglyphArcRotateCamera;
  54610. }(BABYLON.ArcRotateCamera));
  54611. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54612. var AnaglyphGamepadCamera = (function (_super) {
  54613. __extends(AnaglyphGamepadCamera, _super);
  54614. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54615. var _this = _super.call(this, name, position, scene) || this;
  54616. _this.interaxialDistance = interaxialDistance;
  54617. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54618. return _this;
  54619. }
  54620. AnaglyphGamepadCamera.prototype.getClassName = function () {
  54621. return "AnaglyphGamepadCamera";
  54622. };
  54623. return AnaglyphGamepadCamera;
  54624. }(BABYLON.GamepadCamera));
  54625. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54626. var AnaglyphUniversalCamera = (function (_super) {
  54627. __extends(AnaglyphUniversalCamera, _super);
  54628. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54629. var _this = _super.call(this, name, position, scene) || this;
  54630. _this.interaxialDistance = interaxialDistance;
  54631. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54632. return _this;
  54633. }
  54634. AnaglyphUniversalCamera.prototype.getClassName = function () {
  54635. return "AnaglyphUniversalCamera";
  54636. };
  54637. return AnaglyphUniversalCamera;
  54638. }(BABYLON.UniversalCamera));
  54639. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54640. var StereoscopicFreeCamera = (function (_super) {
  54641. __extends(StereoscopicFreeCamera, _super);
  54642. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54643. var _this = _super.call(this, name, position, scene) || this;
  54644. _this.interaxialDistance = interaxialDistance;
  54645. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54646. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54647. return _this;
  54648. }
  54649. StereoscopicFreeCamera.prototype.getClassName = function () {
  54650. return "StereoscopicFreeCamera";
  54651. };
  54652. return StereoscopicFreeCamera;
  54653. }(BABYLON.FreeCamera));
  54654. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54655. var StereoscopicArcRotateCamera = (function (_super) {
  54656. __extends(StereoscopicArcRotateCamera, _super);
  54657. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54658. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  54659. _this.interaxialDistance = interaxialDistance;
  54660. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54661. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54662. return _this;
  54663. }
  54664. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  54665. return "StereoscopicArcRotateCamera";
  54666. };
  54667. return StereoscopicArcRotateCamera;
  54668. }(BABYLON.ArcRotateCamera));
  54669. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54670. var StereoscopicGamepadCamera = (function (_super) {
  54671. __extends(StereoscopicGamepadCamera, _super);
  54672. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54673. var _this = _super.call(this, name, position, scene) || this;
  54674. _this.interaxialDistance = interaxialDistance;
  54675. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54676. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54677. return _this;
  54678. }
  54679. StereoscopicGamepadCamera.prototype.getClassName = function () {
  54680. return "StereoscopicGamepadCamera";
  54681. };
  54682. return StereoscopicGamepadCamera;
  54683. }(BABYLON.GamepadCamera));
  54684. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54685. var StereoscopicUniversalCamera = (function (_super) {
  54686. __extends(StereoscopicUniversalCamera, _super);
  54687. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54688. var _this = _super.call(this, name, position, scene) || this;
  54689. _this.interaxialDistance = interaxialDistance;
  54690. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54691. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54692. return _this;
  54693. }
  54694. StereoscopicUniversalCamera.prototype.getClassName = function () {
  54695. return "StereoscopicUniversalCamera";
  54696. };
  54697. return StereoscopicUniversalCamera;
  54698. }(BABYLON.UniversalCamera));
  54699. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54700. })(BABYLON || (BABYLON = {}));
  54701. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  54702. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  54703. var BABYLON;
  54704. (function (BABYLON) {
  54705. var HDRRenderingPipeline = (function (_super) {
  54706. __extends(HDRRenderingPipeline, _super);
  54707. /**
  54708. * @constructor
  54709. * @param {string} name - The rendering pipeline name
  54710. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54711. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  54712. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54713. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54714. */
  54715. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54716. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54717. var _this = _super.call(this, scene.getEngine(), name) || this;
  54718. /**
  54719. * Public members
  54720. */
  54721. // Gaussian Blur
  54722. /**
  54723. * Gaussian blur coefficient
  54724. * @type {number}
  54725. */
  54726. _this.gaussCoeff = 0.3;
  54727. /**
  54728. * Gaussian blur mean
  54729. * @type {number}
  54730. */
  54731. _this.gaussMean = 1.0;
  54732. /**
  54733. * Gaussian blur standard deviation
  54734. * @type {number}
  54735. */
  54736. _this.gaussStandDev = 0.8;
  54737. /**
  54738. * Gaussian blur multiplier. Multiplies the blur effect
  54739. * @type {number}
  54740. */
  54741. _this.gaussMultiplier = 4.0;
  54742. // HDR
  54743. /**
  54744. * Exposure, controls the overall intensity of the pipeline
  54745. * @type {number}
  54746. */
  54747. _this.exposure = 1.0;
  54748. /**
  54749. * Minimum luminance that the post-process can output. Luminance is >= 0
  54750. * @type {number}
  54751. */
  54752. _this.minimumLuminance = 1.0;
  54753. /**
  54754. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54755. * @type {number}
  54756. */
  54757. _this.maximumLuminance = 1e20;
  54758. /**
  54759. * Increase rate for luminance: eye adaptation speed to dark
  54760. * @type {number}
  54761. */
  54762. _this.luminanceIncreaserate = 0.5;
  54763. /**
  54764. * Decrease rate for luminance: eye adaptation speed to bright
  54765. * @type {number}
  54766. */
  54767. _this.luminanceDecreaseRate = 0.5;
  54768. // Bright pass
  54769. /**
  54770. * Minimum luminance needed to compute HDR
  54771. * @type {number}
  54772. */
  54773. _this.brightThreshold = 0.8;
  54774. _this._needUpdate = true;
  54775. _this._scene = scene;
  54776. // Bright pass
  54777. _this._createBrightPassPostProcess(scene, ratio);
  54778. // Down sample X4
  54779. _this._createDownSampleX4PostProcess(scene, ratio);
  54780. // Create gaussian blur post-processes
  54781. _this._createGaussianBlurPostProcess(scene, ratio);
  54782. // Texture adder
  54783. _this._createTextureAdderPostProcess(scene, ratio);
  54784. // Luminance generator
  54785. _this._createLuminanceGeneratorPostProcess(scene);
  54786. // HDR
  54787. _this._createHDRPostProcess(scene, ratio);
  54788. // Pass postprocess
  54789. if (originalPostProcess === null) {
  54790. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54791. }
  54792. else {
  54793. _this._originalPostProcess = originalPostProcess;
  54794. }
  54795. // Configure pipeline
  54796. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54797. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54798. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54799. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54800. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54801. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54802. var addDownSamplerPostProcess = function (id) {
  54803. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54804. };
  54805. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54806. addDownSamplerPostProcess(i);
  54807. }
  54808. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54809. // Finish
  54810. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54811. if (cameras !== null) {
  54812. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54813. }
  54814. _this.update();
  54815. return _this;
  54816. }
  54817. /**
  54818. * Tells the pipeline to update its post-processes
  54819. */
  54820. HDRRenderingPipeline.prototype.update = function () {
  54821. this._needUpdate = true;
  54822. };
  54823. /**
  54824. * Returns the current calculated luminance
  54825. */
  54826. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54827. return this._hdrCurrentLuminance;
  54828. };
  54829. /**
  54830. * Returns the currently drawn luminance
  54831. */
  54832. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54833. return this._hdrOutputLuminance;
  54834. };
  54835. /**
  54836. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54837. */
  54838. HDRRenderingPipeline.prototype.dispose = function () {
  54839. for (var i = 0; i < this._scene.cameras.length; i++) {
  54840. var camera = this._scene.cameras[i];
  54841. this._originalPostProcess.dispose(camera);
  54842. this._brightPassPostProcess.dispose(camera);
  54843. this._downSampleX4PostProcess.dispose(camera);
  54844. this._guassianBlurHPostProcess.dispose(camera);
  54845. this._guassianBlurVPostProcess.dispose(camera);
  54846. this._textureAdderPostProcess.dispose(camera);
  54847. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  54848. this._downSamplePostProcesses[j].dispose(camera);
  54849. }
  54850. this._hdrPostProcess.dispose(camera);
  54851. }
  54852. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54853. _super.prototype.dispose.call(this);
  54854. };
  54855. /**
  54856. * Creates the HDR post-process and computes the luminance adaptation
  54857. */
  54858. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54859. var _this = this;
  54860. var hdrLastLuminance = 0.0;
  54861. this._hdrOutputLuminance = -1.0;
  54862. this._hdrCurrentLuminance = 1.0;
  54863. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54864. this._hdrPostProcess.onApply = function (effect) {
  54865. if (_this._hdrOutputLuminance < 0.0) {
  54866. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54867. }
  54868. else {
  54869. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54870. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54871. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54872. }
  54873. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54874. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54875. }
  54876. else {
  54877. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54878. }
  54879. }
  54880. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54881. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54882. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54883. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54884. effect.setFloat("exposure", _this.exposure);
  54885. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54886. _this._needUpdate = false;
  54887. };
  54888. };
  54889. /**
  54890. * Texture Adder post-process
  54891. */
  54892. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54893. var _this = this;
  54894. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54895. this._textureAdderPostProcess.onApply = function (effect) {
  54896. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54897. };
  54898. };
  54899. /**
  54900. * Down sample X4 post-process
  54901. */
  54902. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54903. var _this = this;
  54904. var downSampleX4Offsets = new Array(32);
  54905. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54906. this._downSampleX4PostProcess.onApply = function (effect) {
  54907. if (_this._needUpdate) {
  54908. var id = 0;
  54909. for (var i = -2; i < 2; i++) {
  54910. for (var j = -2; j < 2; j++) {
  54911. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54912. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54913. id += 2;
  54914. }
  54915. }
  54916. }
  54917. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54918. };
  54919. };
  54920. /**
  54921. * Bright pass post-process
  54922. */
  54923. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54924. var _this = this;
  54925. var brightOffsets = new Array(8);
  54926. var brightPassCallback = function (effect) {
  54927. if (_this._needUpdate) {
  54928. var sU = (1.0 / _this._brightPassPostProcess.width);
  54929. var sV = (1.0 / _this._brightPassPostProcess.height);
  54930. brightOffsets[0] = -0.5 * sU;
  54931. brightOffsets[1] = 0.5 * sV;
  54932. brightOffsets[2] = 0.5 * sU;
  54933. brightOffsets[3] = 0.5 * sV;
  54934. brightOffsets[4] = -0.5 * sU;
  54935. brightOffsets[5] = -0.5 * sV;
  54936. brightOffsets[6] = 0.5 * sU;
  54937. brightOffsets[7] = -0.5 * sV;
  54938. }
  54939. effect.setArray2("dsOffsets", brightOffsets);
  54940. effect.setFloat("brightThreshold", _this.brightThreshold);
  54941. };
  54942. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54943. this._brightPassPostProcess.onApply = brightPassCallback;
  54944. };
  54945. /**
  54946. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54947. */
  54948. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54949. var _this = this;
  54950. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54951. var luminanceOffsets = new Array(8);
  54952. var downSampleOffsets = new Array(18);
  54953. var halfDestPixelSize;
  54954. this._downSamplePostProcesses = new Array(lumSteps);
  54955. // Utils for luminance
  54956. var luminanceUpdateSourceOffsets = function (width, height) {
  54957. var sU = (1.0 / width);
  54958. var sV = (1.0 / height);
  54959. luminanceOffsets[0] = -0.5 * sU;
  54960. luminanceOffsets[1] = 0.5 * sV;
  54961. luminanceOffsets[2] = 0.5 * sU;
  54962. luminanceOffsets[3] = 0.5 * sV;
  54963. luminanceOffsets[4] = -0.5 * sU;
  54964. luminanceOffsets[5] = -0.5 * sV;
  54965. luminanceOffsets[6] = 0.5 * sU;
  54966. luminanceOffsets[7] = -0.5 * sV;
  54967. };
  54968. var luminanceUpdateDestOffsets = function (width, height) {
  54969. var id = 0;
  54970. for (var x = -1; x < 2; x++) {
  54971. for (var y = -1; y < 2; y++) {
  54972. downSampleOffsets[id] = (x) / width;
  54973. downSampleOffsets[id + 1] = (y) / height;
  54974. id += 2;
  54975. }
  54976. }
  54977. };
  54978. // Luminance callback
  54979. var luminanceCallback = function (effect) {
  54980. if (_this._needUpdate) {
  54981. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54982. }
  54983. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54984. effect.setArray2("lumOffsets", luminanceOffsets);
  54985. };
  54986. // Down sample callbacks
  54987. var downSampleCallback = function (indice) {
  54988. var i = indice;
  54989. return function (effect) {
  54990. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54991. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54992. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54993. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54994. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54995. effect.setArray2("dsOffsets", downSampleOffsets);
  54996. };
  54997. };
  54998. var downSampleAfterRenderCallback = function (effect) {
  54999. // Unpack result
  55000. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  55001. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  55002. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  55003. };
  55004. // Create luminance post-process
  55005. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  55006. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  55007. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  55008. // Create down sample post-processes
  55009. for (var i = lumSteps - 2; i >= 0; i--) {
  55010. var length = Math.pow(3, i);
  55011. ratio = { width: length, height: length };
  55012. var defines = "#define DOWN_SAMPLE\n";
  55013. if (i === 0) {
  55014. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  55015. }
  55016. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  55017. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  55018. if (i === 0) {
  55019. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  55020. }
  55021. }
  55022. };
  55023. /**
  55024. * Gaussian blur post-processes. Horizontal and Vertical
  55025. */
  55026. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  55027. var _this = this;
  55028. var blurOffsetsW = new Array(9);
  55029. var blurOffsetsH = new Array(9);
  55030. var blurWeights = new Array(9);
  55031. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  55032. // Utils for gaussian blur
  55033. var calculateBlurOffsets = function (height) {
  55034. var lastOutputDimensions = {
  55035. width: scene.getEngine().getRenderWidth(),
  55036. height: scene.getEngine().getRenderHeight()
  55037. };
  55038. for (var i = 0; i < 9; i++) {
  55039. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55040. if (height) {
  55041. blurOffsetsH[i] = value;
  55042. }
  55043. else {
  55044. blurOffsetsW[i] = value;
  55045. }
  55046. }
  55047. };
  55048. var calculateWeights = function () {
  55049. var x = 0.0;
  55050. for (var i = 0; i < 9; i++) {
  55051. x = (i - 4.0) / 4.0;
  55052. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  55053. }
  55054. };
  55055. // Callback
  55056. var gaussianBlurCallback = function (height) {
  55057. return function (effect) {
  55058. if (_this._needUpdate) {
  55059. calculateWeights();
  55060. calculateBlurOffsets(height);
  55061. }
  55062. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  55063. effect.setArray("blurWeights", blurWeights);
  55064. effect.setFloat("multiplier", _this.gaussMultiplier);
  55065. };
  55066. };
  55067. // Create horizontal gaussian blur post-processes
  55068. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  55069. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  55070. // Create vertical gaussian blur post-process
  55071. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  55072. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  55073. };
  55074. return HDRRenderingPipeline;
  55075. }(BABYLON.PostProcessRenderPipeline));
  55076. // Luminance generator
  55077. HDRRenderingPipeline.LUM_STEPS = 6;
  55078. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  55079. })(BABYLON || (BABYLON = {}));
  55080. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  55081. var BABYLON;
  55082. (function (BABYLON) {
  55083. var FaceAdjacencies = (function () {
  55084. function FaceAdjacencies() {
  55085. this.edges = new Array();
  55086. this.edgesConnectedCount = 0;
  55087. }
  55088. return FaceAdjacencies;
  55089. }());
  55090. var EdgesRenderer = (function () {
  55091. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  55092. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  55093. if (epsilon === void 0) { epsilon = 0.95; }
  55094. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  55095. this.edgesWidthScalerForOrthographic = 1000.0;
  55096. this.edgesWidthScalerForPerspective = 50.0;
  55097. this._linesPositions = new Array();
  55098. this._linesNormals = new Array();
  55099. this._linesIndices = new Array();
  55100. this._buffers = {};
  55101. this._checkVerticesInsteadOfIndices = false;
  55102. this._source = source;
  55103. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  55104. this._epsilon = epsilon;
  55105. this._prepareRessources();
  55106. this._generateEdgesLines();
  55107. }
  55108. EdgesRenderer.prototype._prepareRessources = function () {
  55109. if (this._lineShader) {
  55110. return;
  55111. }
  55112. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  55113. attributes: ["position", "normal"],
  55114. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  55115. });
  55116. this._lineShader.disableDepthWrite = true;
  55117. this._lineShader.backFaceCulling = false;
  55118. };
  55119. EdgesRenderer.prototype.dispose = function () {
  55120. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  55121. if (buffer) {
  55122. buffer.dispose();
  55123. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  55124. }
  55125. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  55126. if (buffer) {
  55127. buffer.dispose();
  55128. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  55129. }
  55130. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  55131. this._lineShader.dispose();
  55132. };
  55133. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  55134. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  55135. return 0;
  55136. }
  55137. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  55138. return 1;
  55139. }
  55140. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  55141. return 2;
  55142. }
  55143. return -1;
  55144. };
  55145. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  55146. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  55147. return 0;
  55148. }
  55149. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  55150. return 1;
  55151. }
  55152. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  55153. return 2;
  55154. }
  55155. return -1;
  55156. };
  55157. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  55158. var needToCreateLine;
  55159. if (edge === undefined) {
  55160. needToCreateLine = true;
  55161. }
  55162. else {
  55163. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  55164. needToCreateLine = dotProduct < this._epsilon;
  55165. }
  55166. if (needToCreateLine) {
  55167. var offset = this._linesPositions.length / 3;
  55168. var normal = p0.subtract(p1);
  55169. normal.normalize();
  55170. // Positions
  55171. this._linesPositions.push(p0.x);
  55172. this._linesPositions.push(p0.y);
  55173. this._linesPositions.push(p0.z);
  55174. this._linesPositions.push(p0.x);
  55175. this._linesPositions.push(p0.y);
  55176. this._linesPositions.push(p0.z);
  55177. this._linesPositions.push(p1.x);
  55178. this._linesPositions.push(p1.y);
  55179. this._linesPositions.push(p1.z);
  55180. this._linesPositions.push(p1.x);
  55181. this._linesPositions.push(p1.y);
  55182. this._linesPositions.push(p1.z);
  55183. // Normals
  55184. this._linesNormals.push(p1.x);
  55185. this._linesNormals.push(p1.y);
  55186. this._linesNormals.push(p1.z);
  55187. this._linesNormals.push(-1);
  55188. this._linesNormals.push(p1.x);
  55189. this._linesNormals.push(p1.y);
  55190. this._linesNormals.push(p1.z);
  55191. this._linesNormals.push(1);
  55192. this._linesNormals.push(p0.x);
  55193. this._linesNormals.push(p0.y);
  55194. this._linesNormals.push(p0.z);
  55195. this._linesNormals.push(-1);
  55196. this._linesNormals.push(p0.x);
  55197. this._linesNormals.push(p0.y);
  55198. this._linesNormals.push(p0.z);
  55199. this._linesNormals.push(1);
  55200. // Indices
  55201. this._linesIndices.push(offset);
  55202. this._linesIndices.push(offset + 1);
  55203. this._linesIndices.push(offset + 2);
  55204. this._linesIndices.push(offset);
  55205. this._linesIndices.push(offset + 2);
  55206. this._linesIndices.push(offset + 3);
  55207. }
  55208. };
  55209. EdgesRenderer.prototype._generateEdgesLines = function () {
  55210. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55211. var indices = this._source.getIndices();
  55212. // First let's find adjacencies
  55213. var adjacencies = new Array();
  55214. var faceNormals = new Array();
  55215. var index;
  55216. var faceAdjacencies;
  55217. // Prepare faces
  55218. for (index = 0; index < indices.length; index += 3) {
  55219. faceAdjacencies = new FaceAdjacencies();
  55220. var p0Index = indices[index];
  55221. var p1Index = indices[index + 1];
  55222. var p2Index = indices[index + 2];
  55223. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  55224. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  55225. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  55226. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  55227. faceNormal.normalize();
  55228. faceNormals.push(faceNormal);
  55229. adjacencies.push(faceAdjacencies);
  55230. }
  55231. // Scan
  55232. for (index = 0; index < adjacencies.length; index++) {
  55233. faceAdjacencies = adjacencies[index];
  55234. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  55235. var otherFaceAdjacencies = adjacencies[otherIndex];
  55236. if (faceAdjacencies.edgesConnectedCount === 3) {
  55237. break;
  55238. }
  55239. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  55240. continue;
  55241. }
  55242. var otherP0 = indices[otherIndex * 3];
  55243. var otherP1 = indices[otherIndex * 3 + 1];
  55244. var otherP2 = indices[otherIndex * 3 + 2];
  55245. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  55246. var otherEdgeIndex;
  55247. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  55248. continue;
  55249. }
  55250. switch (edgeIndex) {
  55251. case 0:
  55252. if (this._checkVerticesInsteadOfIndices) {
  55253. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55254. }
  55255. else {
  55256. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  55257. }
  55258. break;
  55259. case 1:
  55260. if (this._checkVerticesInsteadOfIndices) {
  55261. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55262. }
  55263. else {
  55264. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  55265. }
  55266. break;
  55267. case 2:
  55268. if (this._checkVerticesInsteadOfIndices) {
  55269. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  55270. }
  55271. else {
  55272. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  55273. }
  55274. break;
  55275. }
  55276. if (otherEdgeIndex === -1) {
  55277. continue;
  55278. }
  55279. faceAdjacencies.edges[edgeIndex] = otherIndex;
  55280. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  55281. faceAdjacencies.edgesConnectedCount++;
  55282. otherFaceAdjacencies.edgesConnectedCount++;
  55283. if (faceAdjacencies.edgesConnectedCount === 3) {
  55284. break;
  55285. }
  55286. }
  55287. }
  55288. }
  55289. // Create lines
  55290. for (index = 0; index < adjacencies.length; index++) {
  55291. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  55292. var current = adjacencies[index];
  55293. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  55294. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  55295. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  55296. }
  55297. // Merge into a single mesh
  55298. var engine = this._source.getScene().getEngine();
  55299. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  55300. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  55301. this._ib = engine.createIndexBuffer(this._linesIndices);
  55302. this._indicesCount = this._linesIndices.length;
  55303. };
  55304. EdgesRenderer.prototype.render = function () {
  55305. if (!this._lineShader.isReady()) {
  55306. return;
  55307. }
  55308. var scene = this._source.getScene();
  55309. var engine = scene.getEngine();
  55310. this._lineShader._preBind();
  55311. // VBOs
  55312. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  55313. scene.resetCachedMaterial();
  55314. this._lineShader.setColor4("color", this._source.edgesColor);
  55315. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  55316. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  55317. }
  55318. else {
  55319. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  55320. }
  55321. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  55322. this._lineShader.bind(this._source.getWorldMatrix());
  55323. // Draw order
  55324. engine.draw(true, 0, this._indicesCount);
  55325. this._lineShader.unbind();
  55326. engine.setDepthWrite(true);
  55327. };
  55328. return EdgesRenderer;
  55329. }());
  55330. BABYLON.EdgesRenderer = EdgesRenderer;
  55331. })(BABYLON || (BABYLON = {}));
  55332. //# sourceMappingURL=babylon.edgesRenderer.js.map
  55333. var BABYLON;
  55334. (function (BABYLON) {
  55335. var TonemappingOperator;
  55336. (function (TonemappingOperator) {
  55337. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55338. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55339. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55340. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55341. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55342. ;
  55343. var TonemapPostProcess = (function (_super) {
  55344. __extends(TonemapPostProcess, _super);
  55345. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55347. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55348. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  55349. _this._operator = _operator;
  55350. _this.exposureAdjustment = exposureAdjustment;
  55351. var defines = "#define ";
  55352. if (_this._operator === TonemappingOperator.Hable)
  55353. defines += "HABLE_TONEMAPPING";
  55354. else if (_this._operator === TonemappingOperator.Reinhard)
  55355. defines += "REINHARD_TONEMAPPING";
  55356. else if (_this._operator === TonemappingOperator.HejiDawson)
  55357. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55358. else if (_this._operator === TonemappingOperator.Photographic)
  55359. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55360. //sadly a second call to create the effect.
  55361. _this.updateEffect(defines);
  55362. _this.onApply = function (effect) {
  55363. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55364. };
  55365. return _this;
  55366. }
  55367. return TonemapPostProcess;
  55368. }(BABYLON.PostProcess));
  55369. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55370. })(BABYLON || (BABYLON = {}));
  55371. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  55372. var BABYLON;
  55373. (function (BABYLON) {
  55374. var ReflectionProbe = (function () {
  55375. function ReflectionProbe(name, size, scene, generateMipMaps) {
  55376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55377. var _this = this;
  55378. this.name = name;
  55379. this._viewMatrix = BABYLON.Matrix.Identity();
  55380. this._target = BABYLON.Vector3.Zero();
  55381. this._add = BABYLON.Vector3.Zero();
  55382. this.invertYAxis = false;
  55383. this.position = BABYLON.Vector3.Zero();
  55384. this._scene = scene;
  55385. this._scene.reflectionProbes.push(this);
  55386. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  55387. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  55388. switch (faceIndex) {
  55389. case 0:
  55390. _this._add.copyFromFloats(1, 0, 0);
  55391. break;
  55392. case 1:
  55393. _this._add.copyFromFloats(-1, 0, 0);
  55394. break;
  55395. case 2:
  55396. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  55397. break;
  55398. case 3:
  55399. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  55400. break;
  55401. case 4:
  55402. _this._add.copyFromFloats(0, 0, 1);
  55403. break;
  55404. case 5:
  55405. _this._add.copyFromFloats(0, 0, -1);
  55406. break;
  55407. }
  55408. if (_this._attachedMesh) {
  55409. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  55410. }
  55411. _this.position.addToRef(_this._add, _this._target);
  55412. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  55413. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  55414. });
  55415. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  55416. scene.updateTransformMatrix(true);
  55417. });
  55418. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  55419. }
  55420. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  55421. get: function () {
  55422. return this._renderTargetTexture.samples;
  55423. },
  55424. set: function (value) {
  55425. this._renderTargetTexture.samples = value;
  55426. },
  55427. enumerable: true,
  55428. configurable: true
  55429. });
  55430. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  55431. get: function () {
  55432. return this._renderTargetTexture.refreshRate;
  55433. },
  55434. set: function (value) {
  55435. this._renderTargetTexture.refreshRate = value;
  55436. },
  55437. enumerable: true,
  55438. configurable: true
  55439. });
  55440. ReflectionProbe.prototype.getScene = function () {
  55441. return this._scene;
  55442. };
  55443. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  55444. get: function () {
  55445. return this._renderTargetTexture;
  55446. },
  55447. enumerable: true,
  55448. configurable: true
  55449. });
  55450. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  55451. get: function () {
  55452. return this._renderTargetTexture.renderList;
  55453. },
  55454. enumerable: true,
  55455. configurable: true
  55456. });
  55457. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  55458. this._attachedMesh = mesh;
  55459. };
  55460. ReflectionProbe.prototype.dispose = function () {
  55461. var index = this._scene.reflectionProbes.indexOf(this);
  55462. if (index !== -1) {
  55463. // Remove from the scene if found
  55464. this._scene.reflectionProbes.splice(index, 1);
  55465. }
  55466. if (this._renderTargetTexture) {
  55467. this._renderTargetTexture.dispose();
  55468. this._renderTargetTexture = null;
  55469. }
  55470. };
  55471. return ReflectionProbe;
  55472. }());
  55473. BABYLON.ReflectionProbe = ReflectionProbe;
  55474. })(BABYLON || (BABYLON = {}));
  55475. //# sourceMappingURL=babylon.reflectionProbe.js.map
  55476. var BABYLON;
  55477. (function (BABYLON) {
  55478. var SolidParticle = (function () {
  55479. /**
  55480. * Creates a Solid Particle object.
  55481. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  55482. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  55483. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  55484. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  55485. * `shapeId` (integer) is the model shape identifier in the SPS.
  55486. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  55487. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  55488. */
  55489. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  55490. this.idx = 0; // particle global index
  55491. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  55492. this.position = BABYLON.Vector3.Zero(); // position
  55493. this.rotation = BABYLON.Vector3.Zero(); // rotation
  55494. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  55495. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  55496. this.velocity = BABYLON.Vector3.Zero(); // velocity
  55497. this.alive = true; // alive
  55498. this.isVisible = true; // visibility
  55499. this._pos = 0; // index of this particle in the global "positions" array
  55500. this.shapeId = 0; // model shape id
  55501. this.idxInShape = 0; // index of the particle in its shape id
  55502. this.idx = particleIndex;
  55503. this._pos = positionIndex;
  55504. this._model = model;
  55505. this.shapeId = shapeId;
  55506. this.idxInShape = idxInShape;
  55507. this._sps = sps;
  55508. if (modelBoundingInfo) {
  55509. this._modelBoundingInfo = modelBoundingInfo;
  55510. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  55511. }
  55512. }
  55513. Object.defineProperty(SolidParticle.prototype, "scale", {
  55514. /**
  55515. * legacy support, changed scale to scaling
  55516. */
  55517. get: function () {
  55518. return this.scaling;
  55519. },
  55520. set: function (scale) {
  55521. this.scaling = scale;
  55522. },
  55523. enumerable: true,
  55524. configurable: true
  55525. });
  55526. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55527. /**
  55528. * legacy support, changed quaternion to rotationQuaternion
  55529. */
  55530. get: function () {
  55531. return this.rotationQuaternion;
  55532. },
  55533. set: function (q) {
  55534. this.rotationQuaternion = q;
  55535. },
  55536. enumerable: true,
  55537. configurable: true
  55538. });
  55539. /**
  55540. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  55541. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  55542. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  55543. */
  55544. SolidParticle.prototype.intersectsMesh = function (target) {
  55545. if (!this._boundingInfo || !target._boundingInfo) {
  55546. return false;
  55547. }
  55548. if (this._sps._bSphereOnly) {
  55549. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  55550. }
  55551. return this._boundingInfo.intersects(target._boundingInfo, false);
  55552. };
  55553. return SolidParticle;
  55554. }());
  55555. BABYLON.SolidParticle = SolidParticle;
  55556. var ModelShape = (function () {
  55557. /**
  55558. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  55559. * SPS internal tool, don't use it manually.
  55560. */
  55561. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55562. this.shapeID = id;
  55563. this._shape = shape;
  55564. this._shapeUV = shapeUV;
  55565. this._positionFunction = posFunction;
  55566. this._vertexFunction = vtxFunction;
  55567. }
  55568. return ModelShape;
  55569. }());
  55570. BABYLON.ModelShape = ModelShape;
  55571. })(BABYLON || (BABYLON = {}));
  55572. //# sourceMappingURL=babylon.solidParticle.js.map
  55573. var BABYLON;
  55574. (function (BABYLON) {
  55575. /**
  55576. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55577. */
  55578. var SolidParticleSystem = (function () {
  55579. /**
  55580. * Creates a SPS (Solid Particle System) object.
  55581. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55582. * `scene` (Scene) is the scene in which the SPS is added.
  55583. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  55584. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  55585. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  55586. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  55587. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  55588. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  55589. */
  55590. function SolidParticleSystem(name, scene, options) {
  55591. // public members
  55592. /**
  55593. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55594. * Example : var p = SPS.particles[i];
  55595. */
  55596. this.particles = new Array();
  55597. /**
  55598. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55599. */
  55600. this.nbParticles = 0;
  55601. /**
  55602. * If the particles must ever face the camera (default false). Useful for planar particles.
  55603. */
  55604. this.billboard = false;
  55605. /**
  55606. * Recompute normals when adding a shape
  55607. */
  55608. this.recomputeNormals = true;
  55609. /**
  55610. * This a counter ofr your own usage. It's not set by any SPS functions.
  55611. */
  55612. this.counter = 0;
  55613. /**
  55614. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55615. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55616. */
  55617. this.vars = {};
  55618. this._positions = new Array();
  55619. this._indices = new Array();
  55620. this._normals = new Array();
  55621. this._colors = new Array();
  55622. this._uvs = new Array();
  55623. this._index = 0; // indices index
  55624. this._updatable = true;
  55625. this._pickable = false;
  55626. this._isVisibilityBoxLocked = false;
  55627. this._alwaysVisible = false;
  55628. this._shapeCounter = 0;
  55629. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  55630. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55631. this._computeParticleColor = true;
  55632. this._computeParticleTexture = true;
  55633. this._computeParticleRotation = true;
  55634. this._computeParticleVertex = false;
  55635. this._computeBoundingBox = false;
  55636. this._cam_axisZ = BABYLON.Vector3.Zero();
  55637. this._cam_axisY = BABYLON.Vector3.Zero();
  55638. this._cam_axisX = BABYLON.Vector3.Zero();
  55639. this._axisX = BABYLON.Axis.X;
  55640. this._axisY = BABYLON.Axis.Y;
  55641. this._axisZ = BABYLON.Axis.Z;
  55642. this._camDir = BABYLON.Vector3.Zero();
  55643. this._rotMatrix = new BABYLON.Matrix();
  55644. this._invertMatrix = new BABYLON.Matrix();
  55645. this._rotated = BABYLON.Vector3.Zero();
  55646. this._quaternion = new BABYLON.Quaternion();
  55647. this._vertex = BABYLON.Vector3.Zero();
  55648. this._normal = BABYLON.Vector3.Zero();
  55649. this._yaw = 0.0;
  55650. this._pitch = 0.0;
  55651. this._roll = 0.0;
  55652. this._halfroll = 0.0;
  55653. this._halfpitch = 0.0;
  55654. this._halfyaw = 0.0;
  55655. this._sinRoll = 0.0;
  55656. this._cosRoll = 0.0;
  55657. this._sinPitch = 0.0;
  55658. this._cosPitch = 0.0;
  55659. this._sinYaw = 0.0;
  55660. this._cosYaw = 0.0;
  55661. this._w = 0.0;
  55662. this._mustUnrotateFixedNormals = false;
  55663. this._minimum = BABYLON.Tmp.Vector3[0];
  55664. this._maximum = BABYLON.Tmp.Vector3[1];
  55665. this._scale = BABYLON.Tmp.Vector3[2];
  55666. this._translation = BABYLON.Tmp.Vector3[3];
  55667. this._minBbox = BABYLON.Tmp.Vector3[4];
  55668. this._maxBbox = BABYLON.Tmp.Vector3[5];
  55669. this._particlesIntersect = false;
  55670. this._bSphereOnly = false;
  55671. this._bSphereRadiusFactor = 1.0;
  55672. this.name = name;
  55673. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55674. this._camera = scene.activeCamera;
  55675. this._pickable = options ? options.isPickable : false;
  55676. this._particlesIntersect = options ? options.particleIntersection : false;
  55677. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  55678. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  55679. if (options && options.updatable) {
  55680. this._updatable = options.updatable;
  55681. }
  55682. else {
  55683. this._updatable = true;
  55684. }
  55685. if (this._pickable) {
  55686. this.pickedParticles = [];
  55687. }
  55688. }
  55689. /**
  55690. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55691. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55692. */
  55693. SolidParticleSystem.prototype.buildMesh = function () {
  55694. if (this.nbParticles === 0) {
  55695. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55696. this.addShape(triangle, 1);
  55697. triangle.dispose();
  55698. }
  55699. this._positions32 = new Float32Array(this._positions);
  55700. this._uvs32 = new Float32Array(this._uvs);
  55701. this._colors32 = new Float32Array(this._colors);
  55702. if (this.recomputeNormals) {
  55703. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55704. }
  55705. this._normals32 = new Float32Array(this._normals);
  55706. this._fixedNormal32 = new Float32Array(this._normals);
  55707. if (this._mustUnrotateFixedNormals) {
  55708. this._unrotateFixedNormals();
  55709. }
  55710. var vertexData = new BABYLON.VertexData();
  55711. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55712. vertexData.indices = this._indices;
  55713. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55714. if (this._uvs32) {
  55715. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55716. ;
  55717. }
  55718. if (this._colors32) {
  55719. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55720. }
  55721. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55722. vertexData.applyToMesh(mesh, this._updatable);
  55723. this.mesh = mesh;
  55724. this.mesh.isPickable = this._pickable;
  55725. // free memory
  55726. this._positions = null;
  55727. this._normals = null;
  55728. this._uvs = null;
  55729. this._colors = null;
  55730. if (!this._updatable) {
  55731. this.particles.length = 0;
  55732. }
  55733. return mesh;
  55734. };
  55735. /**
  55736. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55737. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55738. * Thus the particles generated from `digest()` have their property `position` set yet.
  55739. * `mesh` ( Mesh ) is the mesh to be digested
  55740. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55741. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55742. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55743. */
  55744. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55745. var size = (options && options.facetNb) || 1;
  55746. var number = (options && options.number);
  55747. var delta = (options && options.delta) || 0;
  55748. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55749. var meshInd = mesh.getIndices();
  55750. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55751. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55752. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55753. var f = 0; // facet counter
  55754. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55755. // compute size from number
  55756. if (number) {
  55757. number = (number > totalFacets) ? totalFacets : number;
  55758. size = Math.round(totalFacets / number);
  55759. delta = 0;
  55760. }
  55761. else {
  55762. size = (size > totalFacets) ? totalFacets : size;
  55763. }
  55764. var facetPos = []; // submesh positions
  55765. var facetInd = []; // submesh indices
  55766. var facetUV = []; // submesh UV
  55767. var facetCol = []; // submesh colors
  55768. var barycenter = BABYLON.Tmp.Vector3[0];
  55769. var rand;
  55770. var sizeO = size;
  55771. while (f < totalFacets) {
  55772. size = sizeO + Math.floor((1 + delta) * Math.random());
  55773. if (f > totalFacets - size) {
  55774. size = totalFacets - f;
  55775. }
  55776. // reset temp arrays
  55777. facetPos.length = 0;
  55778. facetInd.length = 0;
  55779. facetUV.length = 0;
  55780. facetCol.length = 0;
  55781. // iterate over "size" facets
  55782. var fi = 0;
  55783. for (var j = f * 3; j < (f + size) * 3; j++) {
  55784. facetInd.push(fi);
  55785. var i = meshInd[j];
  55786. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55787. if (meshUV) {
  55788. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55789. }
  55790. if (meshCol) {
  55791. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55792. }
  55793. fi++;
  55794. }
  55795. // create a model shape for each single particle
  55796. var idx = this.nbParticles;
  55797. var shape = this._posToShape(facetPos);
  55798. var shapeUV = this._uvsToShapeUV(facetUV);
  55799. // compute the barycenter of the shape
  55800. var v;
  55801. for (v = 0; v < shape.length; v++) {
  55802. barycenter.addInPlace(shape[v]);
  55803. }
  55804. barycenter.scaleInPlace(1 / shape.length);
  55805. // shift the shape from its barycenter to the origin
  55806. for (v = 0; v < shape.length; v++) {
  55807. shape[v].subtractInPlace(barycenter);
  55808. }
  55809. var bInfo;
  55810. if (this._particlesIntersect) {
  55811. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  55812. }
  55813. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55814. // add the particle in the SPS
  55815. var currentPos = this._positions.length;
  55816. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  55817. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  55818. // initialize the particle position
  55819. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55820. this._index += shape.length;
  55821. idx++;
  55822. this.nbParticles++;
  55823. this._shapeCounter++;
  55824. f += size;
  55825. }
  55826. return this;
  55827. };
  55828. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  55829. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  55830. var index = 0;
  55831. var idx = 0;
  55832. for (var p = 0; p < this.particles.length; p++) {
  55833. this._particle = this.particles[p];
  55834. this._shape = this._particle._model._shape;
  55835. if (this._particle.rotationQuaternion) {
  55836. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55837. }
  55838. else {
  55839. this._yaw = this._particle.rotation.y;
  55840. this._pitch = this._particle.rotation.x;
  55841. this._roll = this._particle.rotation.z;
  55842. this._quaternionRotationYPR();
  55843. }
  55844. this._quaternionToRotationMatrix();
  55845. this._rotMatrix.invertToRef(this._invertMatrix);
  55846. for (var pt = 0; pt < this._shape.length; pt++) {
  55847. idx = index + pt * 3;
  55848. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  55849. this._fixedNormal32[idx] = this._normal.x;
  55850. this._fixedNormal32[idx + 1] = this._normal.y;
  55851. this._fixedNormal32[idx + 2] = this._normal.z;
  55852. }
  55853. index = idx + 3;
  55854. }
  55855. };
  55856. //reset copy
  55857. SolidParticleSystem.prototype._resetCopy = function () {
  55858. this._copy.position.x = 0;
  55859. this._copy.position.y = 0;
  55860. this._copy.position.z = 0;
  55861. this._copy.rotation.x = 0;
  55862. this._copy.rotation.y = 0;
  55863. this._copy.rotation.z = 0;
  55864. this._copy.rotationQuaternion = null;
  55865. this._copy.scaling.x = 1;
  55866. this._copy.scaling.y = 1;
  55867. this._copy.scaling.z = 1;
  55868. this._copy.uvs.x = 0;
  55869. this._copy.uvs.y = 0;
  55870. this._copy.uvs.z = 1;
  55871. this._copy.uvs.w = 1;
  55872. this._copy.color = null;
  55873. };
  55874. // _meshBuilder : inserts the shape model in the global SPS mesh
  55875. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  55876. var i;
  55877. var u = 0;
  55878. var c = 0;
  55879. var n = 0;
  55880. this._resetCopy();
  55881. if (options && options.positionFunction) {
  55882. options.positionFunction(this._copy, idx, idxInShape);
  55883. this._mustUnrotateFixedNormals = true;
  55884. }
  55885. if (this._copy.rotationQuaternion) {
  55886. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55887. }
  55888. else {
  55889. this._yaw = this._copy.rotation.y;
  55890. this._pitch = this._copy.rotation.x;
  55891. this._roll = this._copy.rotation.z;
  55892. this._quaternionRotationYPR();
  55893. }
  55894. this._quaternionToRotationMatrix();
  55895. for (i = 0; i < shape.length; i++) {
  55896. this._vertex.x = shape[i].x;
  55897. this._vertex.y = shape[i].y;
  55898. this._vertex.z = shape[i].z;
  55899. if (options && options.vertexFunction) {
  55900. options.vertexFunction(this._copy, this._vertex, i);
  55901. }
  55902. this._vertex.x *= this._copy.scaling.x;
  55903. this._vertex.y *= this._copy.scaling.y;
  55904. this._vertex.z *= this._copy.scaling.z;
  55905. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55906. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55907. if (meshUV) {
  55908. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  55909. u += 2;
  55910. }
  55911. if (this._copy.color) {
  55912. this._color = this._copy.color;
  55913. }
  55914. else if (meshCol && meshCol[c] !== undefined) {
  55915. this._color.r = meshCol[c];
  55916. this._color.g = meshCol[c + 1];
  55917. this._color.b = meshCol[c + 2];
  55918. this._color.a = meshCol[c + 3];
  55919. }
  55920. else {
  55921. this._color.r = 1;
  55922. this._color.g = 1;
  55923. this._color.b = 1;
  55924. this._color.a = 1;
  55925. }
  55926. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55927. c += 4;
  55928. if (!this.recomputeNormals && meshNor) {
  55929. this._normal.x = meshNor[n];
  55930. this._normal.y = meshNor[n + 1];
  55931. this._normal.z = meshNor[n + 2];
  55932. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  55933. normals.push(this._normal.x, this._normal.y, this._normal.z);
  55934. n += 3;
  55935. }
  55936. }
  55937. for (i = 0; i < meshInd.length; i++) {
  55938. indices.push(p + meshInd[i]);
  55939. }
  55940. if (this._pickable) {
  55941. var nbfaces = meshInd.length / 3;
  55942. for (i = 0; i < nbfaces; i++) {
  55943. this.pickedParticles.push({ idx: idx, faceId: i });
  55944. }
  55945. }
  55946. return this._copy;
  55947. };
  55948. // returns a shape array from positions array
  55949. SolidParticleSystem.prototype._posToShape = function (positions) {
  55950. var shape = [];
  55951. for (var i = 0; i < positions.length; i += 3) {
  55952. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55953. }
  55954. return shape;
  55955. };
  55956. // returns a shapeUV array from a Vector4 uvs
  55957. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55958. var shapeUV = [];
  55959. if (uvs) {
  55960. for (var i = 0; i < uvs.length; i++)
  55961. shapeUV.push(uvs[i]);
  55962. }
  55963. return shapeUV;
  55964. };
  55965. // adds a new particle object in the particles array
  55966. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  55967. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  55968. this.particles.push(sp);
  55969. return sp;
  55970. };
  55971. /**
  55972. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55973. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55974. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55975. * `nb` (positive integer) the number of particles to be created from this model
  55976. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55977. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55978. */
  55979. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55980. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55981. var meshInd = mesh.getIndices();
  55982. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55983. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55984. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55985. var bbInfo;
  55986. if (this._particlesIntersect) {
  55987. bbInfo = mesh.getBoundingInfo();
  55988. }
  55989. var shape = this._posToShape(meshPos);
  55990. var shapeUV = this._uvsToShapeUV(meshUV);
  55991. var posfunc = options ? options.positionFunction : null;
  55992. var vtxfunc = options ? options.vertexFunction : null;
  55993. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55994. // particles
  55995. var sp;
  55996. var currentCopy;
  55997. var idx = this.nbParticles;
  55998. for (var i = 0; i < nb; i++) {
  55999. var currentPos = this._positions.length;
  56000. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  56001. if (this._updatable) {
  56002. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  56003. sp.position.copyFrom(currentCopy.position);
  56004. sp.rotation.copyFrom(currentCopy.rotation);
  56005. if (currentCopy.rotationQuaternion) {
  56006. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  56007. }
  56008. if (currentCopy.color) {
  56009. sp.color.copyFrom(currentCopy.color);
  56010. }
  56011. sp.scaling.copyFrom(currentCopy.scaling);
  56012. sp.uvs.copyFrom(currentCopy.uvs);
  56013. }
  56014. this._index += shape.length;
  56015. idx++;
  56016. }
  56017. this.nbParticles += nb;
  56018. this._shapeCounter++;
  56019. return this._shapeCounter - 1;
  56020. };
  56021. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  56022. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  56023. this._resetCopy();
  56024. if (particle._model._positionFunction) {
  56025. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  56026. }
  56027. if (this._copy.rotationQuaternion) {
  56028. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56029. }
  56030. else {
  56031. this._yaw = this._copy.rotation.y;
  56032. this._pitch = this._copy.rotation.x;
  56033. this._roll = this._copy.rotation.z;
  56034. this._quaternionRotationYPR();
  56035. }
  56036. this._quaternionToRotationMatrix();
  56037. this._shape = particle._model._shape;
  56038. for (var pt = 0; pt < this._shape.length; pt++) {
  56039. this._vertex.x = this._shape[pt].x;
  56040. this._vertex.y = this._shape[pt].y;
  56041. this._vertex.z = this._shape[pt].z;
  56042. if (particle._model._vertexFunction) {
  56043. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  56044. }
  56045. this._vertex.x *= this._copy.scaling.x;
  56046. this._vertex.y *= this._copy.scaling.y;
  56047. this._vertex.z *= this._copy.scaling.z;
  56048. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56049. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  56050. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  56051. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  56052. }
  56053. particle.position.x = 0.0;
  56054. particle.position.y = 0.0;
  56055. particle.position.z = 0.0;
  56056. particle.rotation.x = 0.0;
  56057. particle.rotation.y = 0.0;
  56058. particle.rotation.z = 0.0;
  56059. particle.rotationQuaternion = null;
  56060. particle.scaling.x = 1.0;
  56061. particle.scaling.y = 1.0;
  56062. particle.scaling.z = 1.0;
  56063. };
  56064. /**
  56065. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  56066. * Returns the SPS.
  56067. */
  56068. SolidParticleSystem.prototype.rebuildMesh = function () {
  56069. for (var p = 0; p < this.particles.length; p++) {
  56070. this._rebuildParticle(this.particles[p]);
  56071. }
  56072. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56073. return this;
  56074. };
  56075. /**
  56076. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  56077. * This method calls `updateParticle()` for each particle of the SPS.
  56078. * For an animated SPS, it is usually called within the render loop.
  56079. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  56080. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  56081. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  56082. * Returns the SPS.
  56083. */
  56084. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  56085. if (start === void 0) { start = 0; }
  56086. if (end === void 0) { end = this.nbParticles - 1; }
  56087. if (update === void 0) { update = true; }
  56088. if (!this._updatable) {
  56089. return;
  56090. }
  56091. // custom beforeUpdate
  56092. this.beforeUpdateParticles(start, end, update);
  56093. this._cam_axisX.x = 1.0;
  56094. this._cam_axisX.y = 0.0;
  56095. this._cam_axisX.z = 0.0;
  56096. this._cam_axisY.x = 0.0;
  56097. this._cam_axisY.y = 1.0;
  56098. this._cam_axisY.z = 0.0;
  56099. this._cam_axisZ.x = 0.0;
  56100. this._cam_axisZ.y = 0.0;
  56101. this._cam_axisZ.z = 1.0;
  56102. // if the particles will always face the camera
  56103. if (this.billboard) {
  56104. this.mesh.computeWorldMatrix(true);
  56105. // compute the camera position and un-rotate it by the current mesh rotation
  56106. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  56107. this._quaternionToRotationMatrix();
  56108. this._rotMatrix.invertToRef(this._invertMatrix);
  56109. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  56110. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  56111. this._cam_axisZ.normalize();
  56112. // same for camera up vector extracted from the cam view matrix
  56113. var view = this._camera.getViewMatrix(true);
  56114. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  56115. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  56116. this._cam_axisY.normalize();
  56117. this._cam_axisX.normalize();
  56118. }
  56119. }
  56120. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  56121. var idx = 0; // current position index in the global array positions32
  56122. var index = 0; // position start index in the global array positions32 of the current particle
  56123. var colidx = 0; // current color index in the global array colors32
  56124. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  56125. var uvidx = 0; // current uv index in the global array uvs32
  56126. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  56127. var pt = 0; // current index in the particle model shape
  56128. if (this.mesh.isFacetDataEnabled) {
  56129. this._computeBoundingBox = true;
  56130. }
  56131. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  56132. if (this._computeBoundingBox) {
  56133. if (start == 0 && end == this.nbParticles - 1) {
  56134. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  56135. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  56136. }
  56137. else {
  56138. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  56139. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  56140. }
  56141. }
  56142. // particle loop
  56143. index = this.particles[start]._pos;
  56144. var vpos = (index / 3) | 0;
  56145. colorIndex = vpos * 4;
  56146. uvIndex = vpos * 2;
  56147. for (var p = start; p <= end; p++) {
  56148. this._particle = this.particles[p];
  56149. this._shape = this._particle._model._shape;
  56150. this._shapeUV = this._particle._model._shapeUV;
  56151. // call to custom user function to update the particle properties
  56152. this.updateParticle(this._particle);
  56153. if (this._particle.isVisible) {
  56154. // particle rotation matrix
  56155. if (this.billboard) {
  56156. this._particle.rotation.x = 0.0;
  56157. this._particle.rotation.y = 0.0;
  56158. }
  56159. if (this._computeParticleRotation || this.billboard) {
  56160. if (this._particle.rotationQuaternion) {
  56161. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56162. }
  56163. else {
  56164. this._yaw = this._particle.rotation.y;
  56165. this._pitch = this._particle.rotation.x;
  56166. this._roll = this._particle.rotation.z;
  56167. this._quaternionRotationYPR();
  56168. }
  56169. this._quaternionToRotationMatrix();
  56170. }
  56171. // particle vertex loop
  56172. for (pt = 0; pt < this._shape.length; pt++) {
  56173. idx = index + pt * 3;
  56174. colidx = colorIndex + pt * 4;
  56175. uvidx = uvIndex + pt * 2;
  56176. this._vertex.x = this._shape[pt].x;
  56177. this._vertex.y = this._shape[pt].y;
  56178. this._vertex.z = this._shape[pt].z;
  56179. if (this._computeParticleVertex) {
  56180. this.updateParticleVertex(this._particle, this._vertex, pt);
  56181. }
  56182. // positions
  56183. this._vertex.x *= this._particle.scaling.x;
  56184. this._vertex.y *= this._particle.scaling.y;
  56185. this._vertex.z *= this._particle.scaling.z;
  56186. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  56187. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  56188. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  56189. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  56190. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  56191. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  56192. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  56193. if (this._computeBoundingBox) {
  56194. if (this._positions32[idx] < this._minimum.x) {
  56195. this._minimum.x = this._positions32[idx];
  56196. }
  56197. if (this._positions32[idx] > this._maximum.x) {
  56198. this._maximum.x = this._positions32[idx];
  56199. }
  56200. if (this._positions32[idx + 1] < this._minimum.y) {
  56201. this._minimum.y = this._positions32[idx + 1];
  56202. }
  56203. if (this._positions32[idx + 1] > this._maximum.y) {
  56204. this._maximum.y = this._positions32[idx + 1];
  56205. }
  56206. if (this._positions32[idx + 2] < this._minimum.z) {
  56207. this._minimum.z = this._positions32[idx + 2];
  56208. }
  56209. if (this._positions32[idx + 2] > this._maximum.z) {
  56210. this._maximum.z = this._positions32[idx + 2];
  56211. }
  56212. }
  56213. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  56214. if (!this._computeParticleVertex) {
  56215. this._normal.x = this._fixedNormal32[idx];
  56216. this._normal.y = this._fixedNormal32[idx + 1];
  56217. this._normal.z = this._fixedNormal32[idx + 2];
  56218. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]);
  56219. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]);
  56220. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]);
  56221. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  56222. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  56223. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  56224. }
  56225. if (this._computeParticleColor) {
  56226. this._colors32[colidx] = this._particle.color.r;
  56227. this._colors32[colidx + 1] = this._particle.color.g;
  56228. this._colors32[colidx + 2] = this._particle.color.b;
  56229. this._colors32[colidx + 3] = this._particle.color.a;
  56230. }
  56231. if (this._computeParticleTexture) {
  56232. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  56233. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  56234. }
  56235. }
  56236. }
  56237. else {
  56238. for (pt = 0; pt < this._shape.length; pt++) {
  56239. idx = index + pt * 3;
  56240. colidx = colorIndex + pt * 4;
  56241. uvidx = uvIndex + pt * 2;
  56242. this._positions32[idx] = this._camera.position.x;
  56243. this._positions32[idx + 1] = this._camera.position.y;
  56244. this._positions32[idx + 2] = this._camera.position.z;
  56245. this._normals32[idx] = 0.0;
  56246. this._normals32[idx + 1] = 0.0;
  56247. this._normals32[idx + 2] = 0.0;
  56248. if (this._computeParticleColor) {
  56249. this._colors32[colidx] = this._particle.color.r;
  56250. this._colors32[colidx + 1] = this._particle.color.g;
  56251. this._colors32[colidx + 2] = this._particle.color.b;
  56252. this._colors32[colidx + 3] = this._particle.color.a;
  56253. }
  56254. if (this._computeParticleTexture) {
  56255. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  56256. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  56257. }
  56258. }
  56259. }
  56260. // if the particle intersections must be computed : update the bbInfo
  56261. if (this._particlesIntersect) {
  56262. var bInfo = this._particle._boundingInfo;
  56263. var bBox = bInfo.boundingBox;
  56264. var bSphere = bInfo.boundingSphere;
  56265. if (!this._bSphereOnly) {
  56266. // place, scale and rotate the particle bbox within the SPS local system, then update it
  56267. for (var b = 0; b < bBox.vectors.length; b++) {
  56268. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  56269. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  56270. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  56271. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  56272. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  56273. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  56274. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  56275. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  56276. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  56277. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  56278. }
  56279. bBox._update(this.mesh._worldMatrix);
  56280. }
  56281. // place and scale the particle bouding sphere in the SPS local system, then update it
  56282. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  56283. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  56284. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  56285. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  56286. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  56287. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  56288. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  56289. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  56290. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  56291. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  56292. bSphere._update(this.mesh._worldMatrix);
  56293. }
  56294. // increment indexes for the next particle
  56295. index = idx + 3;
  56296. colorIndex = colidx + 4;
  56297. uvIndex = uvidx + 2;
  56298. }
  56299. // if the VBO must be updated
  56300. if (update) {
  56301. if (this._computeParticleColor) {
  56302. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  56303. }
  56304. if (this._computeParticleTexture) {
  56305. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  56306. }
  56307. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  56308. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  56309. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  56310. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  56311. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  56312. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  56313. for (var i = 0; i < this._normals32.length; i++) {
  56314. this._fixedNormal32[i] = this._normals32[i];
  56315. }
  56316. }
  56317. if (!this.mesh.areNormalsFrozen) {
  56318. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  56319. }
  56320. }
  56321. }
  56322. if (this._computeBoundingBox) {
  56323. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  56324. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  56325. }
  56326. this.afterUpdateParticles(start, end, update);
  56327. return this;
  56328. };
  56329. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  56330. this._halfroll = this._roll * 0.5;
  56331. this._halfpitch = this._pitch * 0.5;
  56332. this._halfyaw = this._yaw * 0.5;
  56333. this._sinRoll = Math.sin(this._halfroll);
  56334. this._cosRoll = Math.cos(this._halfroll);
  56335. this._sinPitch = Math.sin(this._halfpitch);
  56336. this._cosPitch = Math.cos(this._halfpitch);
  56337. this._sinYaw = Math.sin(this._halfyaw);
  56338. this._cosYaw = Math.cos(this._halfyaw);
  56339. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  56340. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  56341. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  56342. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  56343. };
  56344. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  56345. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  56346. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  56347. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  56348. this._rotMatrix.m[3] = 0;
  56349. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  56350. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  56351. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  56352. this._rotMatrix.m[7] = 0;
  56353. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  56354. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  56355. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  56356. this._rotMatrix.m[11] = 0;
  56357. this._rotMatrix.m[12] = 0;
  56358. this._rotMatrix.m[13] = 0;
  56359. this._rotMatrix.m[14] = 0;
  56360. this._rotMatrix.m[15] = 1.0;
  56361. };
  56362. /**
  56363. * Disposes the SPS.
  56364. * Returns nothing.
  56365. */
  56366. SolidParticleSystem.prototype.dispose = function () {
  56367. this.mesh.dispose();
  56368. this.vars = null;
  56369. // drop references to internal big arrays for the GC
  56370. this._positions = null;
  56371. this._indices = null;
  56372. this._normals = null;
  56373. this._uvs = null;
  56374. this._colors = null;
  56375. this._positions32 = null;
  56376. this._normals32 = null;
  56377. this._fixedNormal32 = null;
  56378. this._uvs32 = null;
  56379. this._colors32 = null;
  56380. this.pickedParticles = null;
  56381. };
  56382. /**
  56383. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  56384. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56385. * Returns the SPS.
  56386. */
  56387. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  56388. if (!this._isVisibilityBoxLocked) {
  56389. this.mesh.refreshBoundingInfo();
  56390. }
  56391. return this;
  56392. };
  56393. /**
  56394. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  56395. * @param size the size (float) of the visibility box
  56396. * note : this doesn't lock the SPS mesh bounding box.
  56397. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56398. */
  56399. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  56400. var vis = size / 2;
  56401. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  56402. };
  56403. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  56404. // getter and setter
  56405. get: function () {
  56406. return this._alwaysVisible;
  56407. },
  56408. /**
  56409. * Sets the SPS as always visible or not
  56410. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56411. */
  56412. set: function (val) {
  56413. this._alwaysVisible = val;
  56414. this.mesh.alwaysSelectAsActiveMesh = val;
  56415. },
  56416. enumerable: true,
  56417. configurable: true
  56418. });
  56419. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  56420. get: function () {
  56421. return this._isVisibilityBoxLocked;
  56422. },
  56423. /**
  56424. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  56425. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  56426. */
  56427. set: function (val) {
  56428. this._isVisibilityBoxLocked = val;
  56429. this.mesh.getBoundingInfo().isLocked = val;
  56430. },
  56431. enumerable: true,
  56432. configurable: true
  56433. });
  56434. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  56435. // getters
  56436. get: function () {
  56437. return this._computeParticleRotation;
  56438. },
  56439. // Optimizer setters
  56440. /**
  56441. * Tells to `setParticles()` to compute the particle rotations or not.
  56442. * Default value : true. The SPS is faster when it's set to false.
  56443. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  56444. */
  56445. set: function (val) {
  56446. this._computeParticleRotation = val;
  56447. },
  56448. enumerable: true,
  56449. configurable: true
  56450. });
  56451. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  56452. get: function () {
  56453. return this._computeParticleColor;
  56454. },
  56455. /**
  56456. * Tells to `setParticles()` to compute the particle colors or not.
  56457. * Default value : true. The SPS is faster when it's set to false.
  56458. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  56459. */
  56460. set: function (val) {
  56461. this._computeParticleColor = val;
  56462. },
  56463. enumerable: true,
  56464. configurable: true
  56465. });
  56466. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  56467. get: function () {
  56468. return this._computeParticleTexture;
  56469. },
  56470. /**
  56471. * Tells to `setParticles()` to compute the particle textures or not.
  56472. * Default value : true. The SPS is faster when it's set to false.
  56473. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  56474. */
  56475. set: function (val) {
  56476. this._computeParticleTexture = val;
  56477. },
  56478. enumerable: true,
  56479. configurable: true
  56480. });
  56481. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  56482. get: function () {
  56483. return this._computeParticleVertex;
  56484. },
  56485. /**
  56486. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  56487. * Default value : false. The SPS is faster when it's set to false.
  56488. * Note : the particle custom vertex positions aren't stored values.
  56489. */
  56490. set: function (val) {
  56491. this._computeParticleVertex = val;
  56492. },
  56493. enumerable: true,
  56494. configurable: true
  56495. });
  56496. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  56497. get: function () {
  56498. return this._computeBoundingBox;
  56499. },
  56500. /**
  56501. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  56502. */
  56503. set: function (val) {
  56504. this._computeBoundingBox = val;
  56505. },
  56506. enumerable: true,
  56507. configurable: true
  56508. });
  56509. // =======================================================================
  56510. // Particle behavior logic
  56511. // these following methods may be overwritten by the user to fit his needs
  56512. /**
  56513. * This function does nothing. It may be overwritten to set all the particle first values.
  56514. * The SPS doesn't call this function, you may have to call it by your own.
  56515. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56516. */
  56517. SolidParticleSystem.prototype.initParticles = function () {
  56518. };
  56519. /**
  56520. * This function does nothing. It may be overwritten to recycle a particle.
  56521. * The SPS doesn't call this function, you may have to call it by your own.
  56522. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56523. */
  56524. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  56525. return particle;
  56526. };
  56527. /**
  56528. * Updates a particle : this function should be overwritten by the user.
  56529. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  56530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56531. * ex : just set a particle position or velocity and recycle conditions
  56532. */
  56533. SolidParticleSystem.prototype.updateParticle = function (particle) {
  56534. return particle;
  56535. };
  56536. /**
  56537. * Updates a vertex of a particle : it can be overwritten by the user.
  56538. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  56539. * @param particle the current particle
  56540. * @param vertex the current index of the current particle
  56541. * @param pt the index of the current vertex in the particle shape
  56542. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  56543. * ex : just set a vertex particle position
  56544. */
  56545. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  56546. return vertex;
  56547. };
  56548. /**
  56549. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  56550. * This does nothing and may be overwritten by the user.
  56551. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56552. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56553. * @param update the boolean update value actually passed to setParticles()
  56554. */
  56555. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56556. };
  56557. /**
  56558. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56559. * This will be passed three parameters.
  56560. * This does nothing and may be overwritten by the user.
  56561. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56562. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56563. * @param update the boolean update value actually passed to setParticles()
  56564. */
  56565. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56566. };
  56567. return SolidParticleSystem;
  56568. }());
  56569. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56570. })(BABYLON || (BABYLON = {}));
  56571. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  56572. var BABYLON;
  56573. (function (BABYLON) {
  56574. var Internals;
  56575. (function (Internals) {
  56576. var FileFaceOrientation = (function () {
  56577. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56578. this.name = name;
  56579. this.worldAxisForNormal = worldAxisForNormal;
  56580. this.worldAxisForFileX = worldAxisForFileX;
  56581. this.worldAxisForFileY = worldAxisForFileY;
  56582. }
  56583. return FileFaceOrientation;
  56584. }());
  56585. ;
  56586. /**
  56587. * Helper class dealing with the extraction of spherical polynomial dataArray
  56588. * from a cube map.
  56589. */
  56590. var CubeMapToSphericalPolynomialTools = (function () {
  56591. function CubeMapToSphericalPolynomialTools() {
  56592. }
  56593. /**
  56594. * Converts a cubemap to the according Spherical Polynomial data.
  56595. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56596. *
  56597. * @param cubeInfo The Cube map to extract the information from.
  56598. * @return The Spherical Polynomial data.
  56599. */
  56600. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56601. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56602. var totalSolidAngle = 0.0;
  56603. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56604. var du = 2.0 / cubeInfo.size;
  56605. var dv = du;
  56606. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56607. var minUV = du * 0.5 - 1.0;
  56608. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56609. var fileFace = this.FileFaces[faceIndex];
  56610. var dataArray = cubeInfo[fileFace.name];
  56611. var v = minUV;
  56612. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56613. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56614. // Because SP is still linear, so summation is fine in that basis.
  56615. for (var y = 0; y < cubeInfo.size; y++) {
  56616. var u = minUV;
  56617. for (var x = 0; x < cubeInfo.size; x++) {
  56618. // World direction (not normalised)
  56619. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56620. worldDirection.normalize();
  56621. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56622. if (1) {
  56623. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56624. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56625. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56626. var color = new BABYLON.Color3(r, g, b);
  56627. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56628. }
  56629. else {
  56630. if (faceIndex == 0) {
  56631. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56632. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56633. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56634. }
  56635. else if (faceIndex == 1) {
  56636. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56637. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56638. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56639. }
  56640. else if (faceIndex == 2) {
  56641. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56642. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56643. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56644. }
  56645. else if (faceIndex == 3) {
  56646. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56647. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56648. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56649. }
  56650. else if (faceIndex == 4) {
  56651. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56652. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56653. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56654. }
  56655. else if (faceIndex == 5) {
  56656. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56657. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56658. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56659. }
  56660. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  56661. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56662. }
  56663. totalSolidAngle += deltaSolidAngle;
  56664. u += du;
  56665. }
  56666. v += dv;
  56667. }
  56668. }
  56669. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56670. var correction = correctSolidAngle / totalSolidAngle;
  56671. sphericalHarmonics.scale(correction);
  56672. // Additionally scale by pi -- audit needed
  56673. sphericalHarmonics.scale(1.0 / Math.PI);
  56674. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56675. };
  56676. return CubeMapToSphericalPolynomialTools;
  56677. }());
  56678. CubeMapToSphericalPolynomialTools.FileFaces = [
  56679. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56680. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56681. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56682. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56683. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56684. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56685. ];
  56686. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56687. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56688. })(BABYLON || (BABYLON = {}));
  56689. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  56690. var BABYLON;
  56691. (function (BABYLON) {
  56692. var Internals;
  56693. (function (Internals) {
  56694. /**
  56695. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56696. */
  56697. var PanoramaToCubeMapTools = (function () {
  56698. function PanoramaToCubeMapTools() {
  56699. }
  56700. /**
  56701. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56702. *
  56703. * @param float32Array The source data.
  56704. * @param inputWidth The width of the input panorama.
  56705. * @param inputhHeight The height of the input panorama.
  56706. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56707. * @return The cubemap data
  56708. */
  56709. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56710. if (!float32Array) {
  56711. throw "ConvertPanoramaToCubemap: input cannot be null";
  56712. }
  56713. if (float32Array.length != inputWidth * inputHeight * 3) {
  56714. throw "ConvertPanoramaToCubemap: input size is wrong";
  56715. }
  56716. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56717. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56718. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56719. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56720. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56721. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56722. return {
  56723. front: textureFront,
  56724. back: textureBack,
  56725. left: textureLeft,
  56726. right: textureRight,
  56727. up: textureUp,
  56728. down: textureDown,
  56729. size: size
  56730. };
  56731. };
  56732. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56733. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56734. var textureArray = new Float32Array(buffer);
  56735. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56736. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56737. var dy = 1 / texSize;
  56738. var fy = 0;
  56739. for (var y = 0; y < texSize; y++) {
  56740. var xv1 = faceData[0];
  56741. var xv2 = faceData[2];
  56742. for (var x = 0; x < texSize; x++) {
  56743. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56744. v.normalize();
  56745. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56746. // 3 channels per pixels
  56747. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56748. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56749. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56750. xv1 = xv1.add(rotDX1);
  56751. xv2 = xv2.add(rotDX2);
  56752. }
  56753. fy += dy;
  56754. }
  56755. return textureArray;
  56756. };
  56757. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56758. var theta = Math.atan2(vDir.z, vDir.x);
  56759. var phi = Math.acos(vDir.y);
  56760. while (theta < -Math.PI)
  56761. theta += 2 * Math.PI;
  56762. while (theta > Math.PI)
  56763. theta -= 2 * Math.PI;
  56764. var dx = theta / Math.PI;
  56765. var dy = phi / Math.PI;
  56766. // recenter.
  56767. dx = dx * 0.5 + 0.5;
  56768. var px = Math.round(dx * inputWidth);
  56769. if (px < 0)
  56770. px = 0;
  56771. else if (px >= inputWidth)
  56772. px = inputWidth - 1;
  56773. var py = Math.round(dy * inputHeight);
  56774. if (py < 0)
  56775. py = 0;
  56776. else if (py >= inputHeight)
  56777. py = inputHeight - 1;
  56778. var inputY = (inputHeight - py - 1);
  56779. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56780. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56781. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56782. return {
  56783. r: r,
  56784. g: g,
  56785. b: b
  56786. };
  56787. };
  56788. return PanoramaToCubeMapTools;
  56789. }());
  56790. PanoramaToCubeMapTools.FACE_FRONT = [
  56791. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56792. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56793. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56794. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56795. ];
  56796. PanoramaToCubeMapTools.FACE_BACK = [
  56797. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56798. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56799. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56800. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56801. ];
  56802. PanoramaToCubeMapTools.FACE_RIGHT = [
  56803. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56804. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56805. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56806. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56807. ];
  56808. PanoramaToCubeMapTools.FACE_LEFT = [
  56809. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56810. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56811. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56812. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56813. ];
  56814. PanoramaToCubeMapTools.FACE_DOWN = [
  56815. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56816. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56817. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56818. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56819. ];
  56820. PanoramaToCubeMapTools.FACE_UP = [
  56821. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56822. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56823. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56824. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56825. ];
  56826. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56827. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56828. })(BABYLON || (BABYLON = {}));
  56829. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  56830. var BABYLON;
  56831. (function (BABYLON) {
  56832. var Internals;
  56833. (function (Internals) {
  56834. ;
  56835. /**
  56836. * This groups tools to convert HDR texture to native colors array.
  56837. */
  56838. var HDRTools = (function () {
  56839. function HDRTools() {
  56840. }
  56841. HDRTools.Ldexp = function (mantissa, exponent) {
  56842. if (exponent > 1023) {
  56843. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56844. }
  56845. if (exponent < -1074) {
  56846. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56847. }
  56848. return mantissa * Math.pow(2, exponent);
  56849. };
  56850. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56851. if (exponent > 0) {
  56852. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56853. float32array[index + 0] = red * exponent;
  56854. float32array[index + 1] = green * exponent;
  56855. float32array[index + 2] = blue * exponent;
  56856. }
  56857. else {
  56858. float32array[index + 0] = 0;
  56859. float32array[index + 1] = 0;
  56860. float32array[index + 2] = 0;
  56861. }
  56862. };
  56863. HDRTools.readStringLine = function (uint8array, startIndex) {
  56864. var line = "";
  56865. var character = "";
  56866. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56867. character = String.fromCharCode(uint8array[i]);
  56868. if (character == "\n") {
  56869. break;
  56870. }
  56871. line += character;
  56872. }
  56873. return line;
  56874. };
  56875. /**
  56876. * Reads header information from an RGBE texture stored in a native array.
  56877. * More information on this format are available here:
  56878. * https://en.wikipedia.org/wiki/RGBE_image_format
  56879. *
  56880. * @param uint8array The binary file stored in native array.
  56881. * @return The header information.
  56882. */
  56883. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56884. var height = 0;
  56885. var width = 0;
  56886. var line = this.readStringLine(uint8array, 0);
  56887. if (line[0] != '#' || line[1] != '?') {
  56888. throw "Bad HDR Format.";
  56889. }
  56890. var endOfHeader = false;
  56891. var findFormat = false;
  56892. var lineIndex = 0;
  56893. do {
  56894. lineIndex += (line.length + 1);
  56895. line = this.readStringLine(uint8array, lineIndex);
  56896. if (line == "FORMAT=32-bit_rle_rgbe") {
  56897. findFormat = true;
  56898. }
  56899. else if (line.length == 0) {
  56900. endOfHeader = true;
  56901. }
  56902. } while (!endOfHeader);
  56903. if (!findFormat) {
  56904. throw "HDR Bad header format, unsupported FORMAT";
  56905. }
  56906. lineIndex += (line.length + 1);
  56907. line = this.readStringLine(uint8array, lineIndex);
  56908. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56909. var match = sizeRegexp.exec(line);
  56910. // TODO. Support +Y and -X if needed.
  56911. if (match.length < 3) {
  56912. throw "HDR Bad header format, no size";
  56913. }
  56914. width = parseInt(match[2]);
  56915. height = parseInt(match[1]);
  56916. if (width < 8 || width > 0x7fff) {
  56917. throw "HDR Bad header format, unsupported size";
  56918. }
  56919. lineIndex += (line.length + 1);
  56920. return {
  56921. height: height,
  56922. width: width,
  56923. dataPosition: lineIndex
  56924. };
  56925. };
  56926. /**
  56927. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56928. * This RGBE texture needs to store the information as a panorama.
  56929. *
  56930. * More information on this format are available here:
  56931. * https://en.wikipedia.org/wiki/RGBE_image_format
  56932. *
  56933. * @param buffer The binary file stored in an array buffer.
  56934. * @param size The expected size of the extracted cubemap.
  56935. * @return The Cube Map information.
  56936. */
  56937. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56938. var uint8array = new Uint8Array(buffer);
  56939. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56940. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56941. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56942. return cubeMapData;
  56943. };
  56944. /**
  56945. * Returns the pixels data extracted from an RGBE texture.
  56946. * This pixels will be stored left to right up to down in the R G B order in one array.
  56947. *
  56948. * More information on this format are available here:
  56949. * https://en.wikipedia.org/wiki/RGBE_image_format
  56950. *
  56951. * @param uint8array The binary file stored in an array buffer.
  56952. * @param hdrInfo The header information of the file.
  56953. * @return The pixels data in RGB right to left up to down order.
  56954. */
  56955. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56956. // Keep for multi format supports.
  56957. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56958. };
  56959. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56960. var num_scanlines = hdrInfo.height;
  56961. var scanline_width = hdrInfo.width;
  56962. var a, b, c, d, count;
  56963. var dataIndex = hdrInfo.dataPosition;
  56964. var index = 0, endIndex = 0, i = 0;
  56965. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56966. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56967. // 3 channels of 4 bytes per pixel in float.
  56968. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56969. var resultArray = new Float32Array(resultBuffer);
  56970. // read in each successive scanline
  56971. while (num_scanlines > 0) {
  56972. a = uint8array[dataIndex++];
  56973. b = uint8array[dataIndex++];
  56974. c = uint8array[dataIndex++];
  56975. d = uint8array[dataIndex++];
  56976. if (a != 2 || b != 2 || (c & 0x80)) {
  56977. // this file is not run length encoded
  56978. throw "HDR Bad header format, not RLE";
  56979. }
  56980. if (((c << 8) | d) != scanline_width) {
  56981. throw "HDR Bad header format, wrong scan line width";
  56982. }
  56983. index = 0;
  56984. // read each of the four channels for the scanline into the buffer
  56985. for (i = 0; i < 4; i++) {
  56986. endIndex = (i + 1) * scanline_width;
  56987. while (index < endIndex) {
  56988. a = uint8array[dataIndex++];
  56989. b = uint8array[dataIndex++];
  56990. if (a > 128) {
  56991. // a run of the same value
  56992. count = a - 128;
  56993. if ((count == 0) || (count > endIndex - index)) {
  56994. throw "HDR Bad Format, bad scanline data (run)";
  56995. }
  56996. while (count-- > 0) {
  56997. scanLineArray[index++] = b;
  56998. }
  56999. }
  57000. else {
  57001. // a non-run
  57002. count = a;
  57003. if ((count == 0) || (count > endIndex - index)) {
  57004. throw "HDR Bad Format, bad scanline data (non-run)";
  57005. }
  57006. scanLineArray[index++] = b;
  57007. if (--count > 0) {
  57008. for (var j = 0; j < count; j++) {
  57009. scanLineArray[index++] = uint8array[dataIndex++];
  57010. }
  57011. }
  57012. }
  57013. }
  57014. }
  57015. // now convert data from buffer into floats
  57016. for (i = 0; i < scanline_width; i++) {
  57017. a = scanLineArray[i];
  57018. b = scanLineArray[i + scanline_width];
  57019. c = scanLineArray[i + 2 * scanline_width];
  57020. d = scanLineArray[i + 3 * scanline_width];
  57021. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57022. }
  57023. num_scanlines--;
  57024. }
  57025. return resultArray;
  57026. };
  57027. return HDRTools;
  57028. }());
  57029. Internals.HDRTools = HDRTools;
  57030. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57031. })(BABYLON || (BABYLON = {}));
  57032. //# sourceMappingURL=babylon.hdr.js.map
  57033. //_______________________________________________________________
  57034. // Extracted from CubeMapGen:
  57035. // https://code.google.com/archive/p/cubemapgen/
  57036. //
  57037. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57038. //_______________________________________________________________
  57039. var BABYLON;
  57040. (function (BABYLON) {
  57041. var Internals;
  57042. (function (Internals) {
  57043. /**
  57044. * The bounding box information used during the conversion process.
  57045. */
  57046. var CMGBoundinBox = (function () {
  57047. function CMGBoundinBox() {
  57048. this.min = new BABYLON.Vector3(0, 0, 0);
  57049. this.max = new BABYLON.Vector3(0, 0, 0);
  57050. this.clear();
  57051. }
  57052. CMGBoundinBox.prototype.clear = function () {
  57053. this.min.x = CMGBoundinBox.MAX;
  57054. this.min.y = CMGBoundinBox.MAX;
  57055. this.min.z = CMGBoundinBox.MAX;
  57056. this.max.x = CMGBoundinBox.MIN;
  57057. this.max.y = CMGBoundinBox.MIN;
  57058. this.max.z = CMGBoundinBox.MIN;
  57059. };
  57060. CMGBoundinBox.prototype.augment = function (x, y, z) {
  57061. this.min.x = Math.min(this.min.x, x);
  57062. this.min.y = Math.min(this.min.y, y);
  57063. this.min.z = Math.min(this.min.z, z);
  57064. this.max.x = Math.max(this.max.x, x);
  57065. this.max.y = Math.max(this.max.y, y);
  57066. this.max.z = Math.max(this.max.z, z);
  57067. };
  57068. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  57069. this.min.x = Math.max(this.min.x, x);
  57070. this.min.y = Math.max(this.min.y, y);
  57071. this.min.z = Math.max(this.min.z, z);
  57072. };
  57073. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  57074. this.max.x = Math.min(this.max.x, x);
  57075. this.max.y = Math.min(this.max.y, y);
  57076. this.max.z = Math.min(this.max.z, z);
  57077. };
  57078. CMGBoundinBox.prototype.empty = function () {
  57079. if ((this.min.x > this.max.y) ||
  57080. (this.min.y > this.max.y) ||
  57081. (this.min.z > this.max.y)) {
  57082. return true;
  57083. }
  57084. else {
  57085. return false;
  57086. }
  57087. };
  57088. return CMGBoundinBox;
  57089. }());
  57090. CMGBoundinBox.MAX = Number.MAX_VALUE;
  57091. CMGBoundinBox.MIN = Number.MIN_VALUE;
  57092. /**
  57093. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  57094. * required by the glossinees of a material.
  57095. *
  57096. * This only supports the cosine drop power as well as Warp fixup generation method.
  57097. *
  57098. * This is using the process from CubeMapGen described here:
  57099. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  57100. */
  57101. var PMREMGenerator = (function () {
  57102. /**
  57103. * Constructor of the generator.
  57104. *
  57105. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  57106. * @param inputSize The size of the cubemap faces
  57107. * @param outputSize The size of the output cubemap faces
  57108. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  57109. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  57110. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  57111. * @param specularPower The max specular level of the desired cubemap
  57112. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  57113. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  57114. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  57115. */
  57116. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  57117. this.input = input;
  57118. this.inputSize = inputSize;
  57119. this.outputSize = outputSize;
  57120. this.maxNumMipLevels = maxNumMipLevels;
  57121. this.numChannels = numChannels;
  57122. this.isFloat = isFloat;
  57123. this.specularPower = specularPower;
  57124. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  57125. this.excludeBase = excludeBase;
  57126. this.fixup = fixup;
  57127. this._outputSurface = [];
  57128. this._numMipLevels = 0;
  57129. }
  57130. /**
  57131. * Launches the filter process and return the result.
  57132. *
  57133. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  57134. */
  57135. PMREMGenerator.prototype.filterCubeMap = function () {
  57136. // Init cubemap processor
  57137. this.init();
  57138. // Filters the cubemap
  57139. this.filterCubeMapMipChain();
  57140. // Returns the filtered mips.
  57141. return this._outputSurface;
  57142. };
  57143. PMREMGenerator.prototype.init = function () {
  57144. var i;
  57145. var j;
  57146. var mipLevelSize;
  57147. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  57148. if (this.maxNumMipLevels == 0) {
  57149. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  57150. }
  57151. //first miplevel size
  57152. mipLevelSize = this.outputSize;
  57153. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  57154. for (j = 0; j < this.maxNumMipLevels; j++) {
  57155. this._outputSurface.length++;
  57156. this._outputSurface[j] = [];
  57157. //Iterate over faces for output images
  57158. for (i = 0; i < 6; i++) {
  57159. this._outputSurface[j].length++;
  57160. // Initializes a new array for the output.
  57161. if (this.isFloat) {
  57162. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57163. }
  57164. else {
  57165. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  57166. }
  57167. }
  57168. //next mip level is half size
  57169. mipLevelSize >>= 1;
  57170. this._numMipLevels++;
  57171. //terminate if mip chain becomes too small
  57172. if (mipLevelSize == 0) {
  57173. this.maxNumMipLevels = j;
  57174. return;
  57175. }
  57176. }
  57177. };
  57178. //--------------------------------------------------------------------------------------
  57179. //Cube map filtering and mip chain generation.
  57180. // the cube map filtereing is specified using a number of parameters:
  57181. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  57182. // indicates the region of the hemisphere to filter over for each tap.
  57183. //
  57184. // Note that the top mip level is also a filtered version of the original input images
  57185. // as well in order to create mip chains for diffuse environment illumination.
  57186. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  57187. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  57188. //
  57189. // Then the mip angle used to genreate the next level of the mip chain from the first level
  57190. // is a_InitialMipAngle
  57191. //
  57192. // The angle for the subsequent levels of the mip chain are specified by their parents
  57193. // filtering angle and a per-level scale and bias
  57194. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  57195. //
  57196. //--------------------------------------------------------------------------------------
  57197. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  57198. // First, take count of the lighting model to modify SpecularPower
  57199. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  57200. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  57201. //Cone angle start (for generating subsequent mip levels)
  57202. var currentSpecularPower = this.specularPower;
  57203. //Build filter lookup tables based on the source miplevel size
  57204. this.precomputeFilterLookupTables(this.inputSize);
  57205. // Note that we need to filter the first level before generating mipmap
  57206. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  57207. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  57208. // TODO : Write a function to copy and scale the base mipmap in output
  57209. // I am just lazy here and just put a high specular power value, and do some if.
  57210. if (this.excludeBase && (levelIndex == 0)) {
  57211. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  57212. currentSpecularPower = 100000.0;
  57213. }
  57214. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  57215. var srcCubeImage = this.input;
  57216. var dstCubeImage = this._outputSurface[levelIndex];
  57217. var dstSize = this.outputSize >> levelIndex;
  57218. // Compute required angle.
  57219. var angle = this.getBaseFilterAngle(currentSpecularPower);
  57220. // filter cube surfaces
  57221. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  57222. // fix seams
  57223. if (this.fixup) {
  57224. this.fixupCubeEdges(dstCubeImage, dstSize);
  57225. }
  57226. // Decrease the specular power to generate the mipmap chain
  57227. // TODO : Use another method for Exclude (see first comment at start of the function
  57228. if (this.excludeBase && (levelIndex == 0)) {
  57229. currentSpecularPower = this.specularPower;
  57230. }
  57231. currentSpecularPower *= this.cosinePowerDropPerMip;
  57232. }
  57233. };
  57234. //--------------------------------------------------------------------------------------
  57235. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  57236. // It allow to optimize the texel to access base on the specular power.
  57237. //--------------------------------------------------------------------------------------
  57238. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  57239. // We want to find the alpha such that:
  57240. // cos(alpha)^cosinePower = epsilon
  57241. // That's: acos(epsilon^(1/cosinePower))
  57242. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  57243. var angle = 180.0;
  57244. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  57245. angle *= 180.0 / Math.PI; // Convert to degree
  57246. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  57247. return angle;
  57248. };
  57249. //--------------------------------------------------------------------------------------
  57250. //Builds the following lookup tables prior to filtering:
  57251. // -normalizer cube map
  57252. // -tap weight lookup table
  57253. //
  57254. //--------------------------------------------------------------------------------------
  57255. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  57256. var srcTexelAngle;
  57257. var iCubeFace;
  57258. //clear pre-existing normalizer cube map
  57259. this._normCubeMap = [];
  57260. //Normalized vectors per cubeface and per-texel solid angle
  57261. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  57262. };
  57263. //--------------------------------------------------------------------------------------
  57264. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  57265. //
  57266. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  57267. //
  57268. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  57269. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  57270. // below
  57271. //--------------------------------------------------------------------------------------
  57272. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  57273. var iCubeFace;
  57274. var u;
  57275. var v;
  57276. //iterate over cube faces
  57277. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57278. //First three channels for norm cube, and last channel for solid angle
  57279. this._normCubeMap.push(new Float32Array(size * size * 4));
  57280. //fast texture walk, build normalizer cube map
  57281. var facesData = this.input[iCubeFace];
  57282. for (v = 0; v < size; v++) {
  57283. for (u = 0; u < size; u++) {
  57284. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  57285. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  57286. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  57287. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  57288. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  57289. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  57290. }
  57291. }
  57292. }
  57293. };
  57294. //--------------------------------------------------------------------------------------
  57295. // Convert cubemap face texel coordinates and face idx to 3D vector
  57296. // note the U and V coords are integer coords and range from 0 to size-1
  57297. // this routine can be used to generate a normalizer cube map
  57298. //--------------------------------------------------------------------------------------
  57299. // SL BEGIN
  57300. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  57301. var nvcU;
  57302. var nvcV;
  57303. var tempVec;
  57304. // Change from original AMD code
  57305. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  57306. // + 0.5f is for texel center addressing
  57307. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  57308. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  57309. // warp fixup
  57310. if (fixup && size > 1) {
  57311. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  57312. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  57313. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  57314. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  57315. }
  57316. // Get current vector
  57317. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  57318. // U contribution
  57319. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  57320. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  57321. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  57322. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  57323. // V contribution and Sum
  57324. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  57325. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  57326. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  57327. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  57328. //add face axis
  57329. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  57330. PMREMGenerator._vectorTemp.x += faceAxis[0];
  57331. PMREMGenerator._vectorTemp.y += faceAxis[1];
  57332. PMREMGenerator._vectorTemp.z += faceAxis[2];
  57333. //normalize vector
  57334. PMREMGenerator._vectorTemp.normalize();
  57335. return PMREMGenerator._vectorTemp;
  57336. };
  57337. //--------------------------------------------------------------------------------------
  57338. // Convert 3D vector to cubemap face texel coordinates and face idx
  57339. // note the U and V coords are integer coords and range from 0 to size-1
  57340. // this routine can be used to generate a normalizer cube map
  57341. //
  57342. // returns face IDX and texel coords
  57343. //--------------------------------------------------------------------------------------
  57344. // SL BEGIN
  57345. /*
  57346. Mapping Texture Coordinates to Cube Map Faces
  57347. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  57348. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  57349. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  57350. map arrangement in Pixar's RenderMan package.
  57351. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  57352. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  57353. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  57354. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  57355. the major axis direction). The target column in the table below explains how the major axis direction
  57356. maps to the 2D image of a particular cube map target.
  57357. major axis
  57358. direction target sc tc ma
  57359. ---------- --------------------------------- --- --- ---
  57360. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  57361. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  57362. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  57363. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  57364. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  57365. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  57366. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  57367. an updated (s,t) is calculated as follows
  57368. s = ( sc/|ma| + 1 ) / 2
  57369. t = ( tc/|ma| + 1 ) / 2
  57370. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  57371. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  57372. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  57373. */
  57374. // Note this method return U and V in range from 0 to size-1
  57375. // SL END
  57376. // Store the information in vector3 for convenience (faceindex, u, v)
  57377. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  57378. var maxCoord;
  57379. var faceIdx;
  57380. //absolute value 3
  57381. var absX = Math.abs(x);
  57382. var absY = Math.abs(y);
  57383. var absZ = Math.abs(z);
  57384. if (absX >= absY && absX >= absZ) {
  57385. maxCoord = absX;
  57386. if (x >= 0) {
  57387. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  57388. }
  57389. else {
  57390. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57391. }
  57392. }
  57393. else if (absY >= absX && absY >= absZ) {
  57394. maxCoord = absY;
  57395. if (y >= 0) {
  57396. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57397. }
  57398. else {
  57399. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57400. }
  57401. }
  57402. else {
  57403. maxCoord = absZ;
  57404. if (z >= 0) {
  57405. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57406. }
  57407. else {
  57408. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57409. }
  57410. }
  57411. //divide through by max coord so face vector lies on cube face
  57412. var scale = 1 / maxCoord;
  57413. x *= scale;
  57414. y *= scale;
  57415. z *= scale;
  57416. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  57417. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  57418. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  57419. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  57420. // Modify original AMD code to return value from 0 to Size - 1
  57421. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  57422. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  57423. PMREMGenerator._vectorTemp.x = faceIdx;
  57424. PMREMGenerator._vectorTemp.y = u;
  57425. PMREMGenerator._vectorTemp.z = v;
  57426. return PMREMGenerator._vectorTemp;
  57427. };
  57428. //--------------------------------------------------------------------------------------
  57429. //Original code from Ignacio CastaÒo
  57430. // This formula is from Manne ÷hrstrˆm's thesis.
  57431. // Take two coordiantes in the range [-1, 1] that define a portion of a
  57432. // cube face and return the area of the projection of that portion on the
  57433. // surface of the sphere.
  57434. //--------------------------------------------------------------------------------------
  57435. PMREMGenerator.prototype.areaElement = function (x, y) {
  57436. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  57437. };
  57438. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  57439. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  57440. // (+ 0.5f is for texel center addressing)
  57441. u = (2.0 * (u + 0.5) / size) - 1.0;
  57442. v = (2.0 * (v + 0.5) / size) - 1.0;
  57443. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  57444. var invResolution = 1.0 / size;
  57445. // U and V are the -1..1 texture coordinate on the current face.
  57446. // Get projected area for this texel
  57447. var x0 = u - invResolution;
  57448. var y0 = v - invResolution;
  57449. var x1 = u + invResolution;
  57450. var y1 = v + invResolution;
  57451. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  57452. return solidAngle;
  57453. };
  57454. //--------------------------------------------------------------------------------------
  57455. //The key to the speed of these filtering routines is to quickly define a per-face
  57456. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  57457. // Later these pixels are selectively processed based on their dot products to see if
  57458. // they reside within the filtering cone.
  57459. //
  57460. //This is done by computing the smallest per-texel angle to get a conservative estimate
  57461. // of the number of texels needed to be covered in width and height order to filter the
  57462. // region. the bounding box for the center taps face is defined first, and if the
  57463. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  57464. // defined next
  57465. //--------------------------------------------------------------------------------------
  57466. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  57467. // note that pixels within these regions may be rejected
  57468. // based on the anlge
  57469. var iCubeFace;
  57470. var u;
  57471. var v;
  57472. // bounding box per face to specify region to process
  57473. var filterExtents = [];
  57474. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57475. filterExtents.push(new CMGBoundinBox());
  57476. }
  57477. // min angle a src texel can cover (in degrees)
  57478. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  57479. // angle about center tap to define filter cone
  57480. // filter angle is 1/2 the cone angle
  57481. var filterAngle = filterConeAngle / 2.0;
  57482. //ensure filter angle is larger than a texel
  57483. if (filterAngle < srcTexelAngle) {
  57484. filterAngle = srcTexelAngle;
  57485. }
  57486. //ensure filter cone is always smaller than the hemisphere
  57487. if (filterAngle > 90.0) {
  57488. filterAngle = 90.0;
  57489. }
  57490. // the maximum number of texels in 1D the filter cone angle will cover
  57491. // used to determine bounding box size for filter extents
  57492. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  57493. // ensure conservative region always covers at least one texel
  57494. if (filterSize < 1) {
  57495. filterSize = 1;
  57496. }
  57497. // dotProdThresh threshold based on cone angle to determine whether or not taps
  57498. // reside within the cone angle
  57499. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  57500. // process required faces
  57501. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57502. //iterate over dst cube map face texel
  57503. for (v = 0; v < dstSize; v++) {
  57504. for (u = 0; u < dstSize; u++) {
  57505. //get center tap direction
  57506. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  57507. //clear old per-face filter extents
  57508. this.clearFilterExtents(filterExtents);
  57509. //define per-face filter extents
  57510. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  57511. //perform filtering of src faces using filter extents
  57512. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  57513. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  57514. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  57515. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  57516. }
  57517. }
  57518. }
  57519. };
  57520. //--------------------------------------------------------------------------------------
  57521. //Clear filter extents for the 6 cube map faces
  57522. //--------------------------------------------------------------------------------------
  57523. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  57524. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  57525. filterExtents[iCubeFaces].clear();
  57526. }
  57527. };
  57528. //--------------------------------------------------------------------------------------
  57529. //Define per-face bounding box filter extents
  57530. //
  57531. // These define conservative texel regions in each of the faces the filter can possibly
  57532. // process. When the pixels in the regions are actually processed, the dot product
  57533. // between the tap vector and the center tap vector is used to determine the weight of
  57534. // the tap and whether or not the tap is within the cone.
  57535. //
  57536. //--------------------------------------------------------------------------------------
  57537. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  57538. //neighboring face and bleed over amount, and width of BBOX for
  57539. // left, right, top, and bottom edges of this face
  57540. var bleedOverAmount = [0, 0, 0, 0];
  57541. var bleedOverBBoxMin = [0, 0, 0, 0];
  57542. var bleedOverBBoxMax = [0, 0, 0, 0];
  57543. var neighborFace;
  57544. var neighborEdge;
  57545. var oppositeFaceIdx;
  57546. //get face idx, and u, v info from center tap dir
  57547. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  57548. var faceIdx = result.x;
  57549. var u = result.y;
  57550. var v = result.z;
  57551. //define bbox size within face
  57552. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  57553. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  57554. filterExtents[faceIdx].clampMin(0, 0, 0);
  57555. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  57556. //u and v extent in face corresponding to center tap
  57557. var minU = filterExtents[faceIdx].min.x;
  57558. var minV = filterExtents[faceIdx].min.y;
  57559. var maxU = filterExtents[faceIdx].max.x;
  57560. var maxV = filterExtents[faceIdx].max.y;
  57561. //bleed over amounts for face across u=0 edge (left)
  57562. bleedOverAmount[0] = (bboxSize - u);
  57563. bleedOverBBoxMin[0] = minV;
  57564. bleedOverBBoxMax[0] = maxV;
  57565. //bleed over amounts for face across u=1 edge (right)
  57566. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  57567. bleedOverBBoxMin[1] = minV;
  57568. bleedOverBBoxMax[1] = maxV;
  57569. //bleed over to face across v=0 edge (up)
  57570. bleedOverAmount[2] = (bboxSize - v);
  57571. bleedOverBBoxMin[2] = minU;
  57572. bleedOverBBoxMax[2] = maxU;
  57573. //bleed over to face across v=1 edge (down)
  57574. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  57575. bleedOverBBoxMin[3] = minU;
  57576. bleedOverBBoxMax[3] = maxU;
  57577. //compute bleed over regions in neighboring faces
  57578. for (var i = 0; i < 4; i++) {
  57579. if (bleedOverAmount[i] > 0) {
  57580. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  57581. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  57582. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  57583. // be flipped: the cases are
  57584. // if a left edge mates with a left or bottom edge on the neighbor
  57585. // if a top edge mates with a top or right edge on the neighbor
  57586. // if a right edge mates with a right or top edge on the neighbor
  57587. // if a bottom edge mates with a bottom or left edge on the neighbor
  57588. //Seeing as the edges are enumerated as follows
  57589. // left =0
  57590. // right =1
  57591. // top =2
  57592. // bottom =3
  57593. //
  57594. // so if the edge enums are the same, or the sum of the enums == 3,
  57595. // the bbox needs to be flipped
  57596. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  57597. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  57598. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  57599. }
  57600. //The way the bounding box is extended onto the neighboring face
  57601. // depends on which edge of neighboring face abuts with this one
  57602. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  57603. case PMREMGenerator.CP_EDGE_LEFT:
  57604. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  57605. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57606. break;
  57607. case PMREMGenerator.CP_EDGE_RIGHT:
  57608. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57609. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57610. break;
  57611. case PMREMGenerator.CP_EDGE_TOP:
  57612. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57613. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57614. break;
  57615. case PMREMGenerator.CP_EDGE_BOTTOM:
  57616. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57617. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57618. break;
  57619. }
  57620. //clamp filter extents in non-center tap faces to remain within surface
  57621. filterExtents[neighborFace].clampMin(0, 0, 0);
  57622. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57623. }
  57624. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57625. // from the center tap face, then process the opposite face entirely for now.
  57626. //Note that the cases in which this happens, what usually happens is that
  57627. // more than one edge bleeds onto the opposite face, and the bounding box
  57628. // encompasses the entire cube map face.
  57629. if (bleedOverAmount[i] > srcSize) {
  57630. //determine opposite face
  57631. switch (faceIdx) {
  57632. case PMREMGenerator.CP_FACE_X_POS:
  57633. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57634. break;
  57635. case PMREMGenerator.CP_FACE_X_NEG:
  57636. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57637. break;
  57638. case PMREMGenerator.CP_FACE_Y_POS:
  57639. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57640. break;
  57641. case PMREMGenerator.CP_FACE_Y_NEG:
  57642. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57643. break;
  57644. case PMREMGenerator.CP_FACE_Z_POS:
  57645. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57646. break;
  57647. case PMREMGenerator.CP_FACE_Z_NEG:
  57648. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57649. break;
  57650. default:
  57651. break;
  57652. }
  57653. //just encompass entire face for now
  57654. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57655. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57656. }
  57657. }
  57658. };
  57659. //--------------------------------------------------------------------------------------
  57660. //ProcessFilterExtents
  57661. // Process bounding box in each cube face
  57662. //
  57663. //--------------------------------------------------------------------------------------
  57664. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57665. //accumulators are 64-bit floats in order to have the precision needed
  57666. // over a summation of a large number of pixels
  57667. var dstAccum = [0, 0, 0, 0];
  57668. var weightAccum = 0;
  57669. var k = 0;
  57670. var nSrcChannels = this.numChannels;
  57671. // norm cube map and srcCubeMap have same face width
  57672. var faceWidth = srcSize;
  57673. //amount to add to pointer to move to next scanline in images
  57674. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57675. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57676. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57677. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57678. // iterate over cubefaces
  57679. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57680. //if bbox is non empty
  57681. if (!filterExtents[iFaceIdx].empty()) {
  57682. var uStart = filterExtents[iFaceIdx].min.x;
  57683. var vStart = filterExtents[iFaceIdx].min.y;
  57684. var uEnd = filterExtents[iFaceIdx].max.x;
  57685. var vEnd = filterExtents[iFaceIdx].max.y;
  57686. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57687. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57688. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57689. for (var v = vStart; v <= vEnd; v++) {
  57690. var normCubeRowWalk = 0;
  57691. var srcCubeRowWalk = 0;
  57692. for (var u = uStart; u <= uEnd; u++) {
  57693. //pointer to direction in cube map associated with texel
  57694. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57695. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57696. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57697. //check dot product to see if texel is within cone
  57698. var tapDotProd = texelVectX * centerTapDir.x +
  57699. texelVectY * centerTapDir.y +
  57700. texelVectZ * centerTapDir.z;
  57701. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57702. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57703. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57704. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57705. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57706. // so just adding one to specularpower do the trick.
  57707. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57708. //iterate over channels
  57709. for (k = 0; k < nSrcChannels; k++) {
  57710. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57711. srcCubeRowWalk++;
  57712. }
  57713. weightAccum += weight; //accumulate weight
  57714. }
  57715. else {
  57716. //step across source pixel
  57717. srcCubeRowWalk += nSrcChannels;
  57718. }
  57719. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57720. }
  57721. startIndexNormCubeMap += normCubePitch;
  57722. startIndexSrcCubeMap += srcCubePitch;
  57723. }
  57724. }
  57725. }
  57726. //divide through by weights if weight is non zero
  57727. if (weightAccum != 0.0) {
  57728. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57729. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57730. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57731. if (this.numChannels > 3) {
  57732. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57733. }
  57734. }
  57735. else {
  57736. // otherwise sample nearest
  57737. // get face idx and u, v texel coordinate in face
  57738. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57739. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57740. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57741. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57742. if (this.numChannels > 3) {
  57743. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57744. }
  57745. }
  57746. return PMREMGenerator._vectorTemp;
  57747. };
  57748. //--------------------------------------------------------------------------------------
  57749. // Fixup cube edges
  57750. //
  57751. // average texels on cube map faces across the edges
  57752. // WARP/BENT Method Only.
  57753. //--------------------------------------------------------------------------------------
  57754. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57755. var k;
  57756. var j;
  57757. var i;
  57758. var iFace;
  57759. var iCorner = 0;
  57760. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57761. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57762. // note that if functionality to filter across the three texels for each corner, then
  57763. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57764. var cornerPtr = [
  57765. [[], [], []],
  57766. [[], [], []],
  57767. [[], [], []],
  57768. [[], [], []],
  57769. [[], [], []],
  57770. [[], [], []],
  57771. [[], [], []],
  57772. [[], [], []]
  57773. ];
  57774. //if there is no fixup, or fixup width = 0, do nothing
  57775. if (cubeMapSize < 1) {
  57776. return;
  57777. }
  57778. //special case 1x1 cubemap, average face colors
  57779. if (cubeMapSize == 1) {
  57780. //iterate over channels
  57781. for (k = 0; k < this.numChannels; k++) {
  57782. var accum = 0.0;
  57783. //iterate over faces to accumulate face colors
  57784. for (iFace = 0; iFace < 6; iFace++) {
  57785. accum += cubeMap[iFace][k];
  57786. }
  57787. //compute average over 6 face colors
  57788. accum /= 6.0;
  57789. //iterate over faces to distribute face colors
  57790. for (iFace = 0; iFace < 6; iFace++) {
  57791. cubeMap[iFace][k] = accum;
  57792. }
  57793. }
  57794. return;
  57795. }
  57796. //iterate over faces to collect list of corner texel pointers
  57797. for (iFace = 0; iFace < 6; iFace++) {
  57798. //the 4 corner pointers for this face
  57799. faceCornerStartIndicies[0] = [iFace, 0];
  57800. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57801. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57802. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57803. //iterate over face corners to collect cube corner pointers
  57804. for (iCorner = 0; iCorner < 4; iCorner++) {
  57805. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57806. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57807. cornerNumPtrs[corner]++;
  57808. }
  57809. }
  57810. //iterate over corners to average across corner tap values
  57811. for (iCorner = 0; iCorner < 8; iCorner++) {
  57812. for (k = 0; k < this.numChannels; k++) {
  57813. var cornerTapAccum = 0.0;
  57814. //iterate over corner texels and average results
  57815. for (i = 0; i < 3; i++) {
  57816. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57817. }
  57818. //divide by 3 to compute average of corner tap values
  57819. cornerTapAccum *= (1.0 / 3.0);
  57820. //iterate over corner texels and average results
  57821. for (i = 0; i < 3; i++) {
  57822. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57823. }
  57824. }
  57825. }
  57826. //iterate over the twelve edges of the cube to average across edges
  57827. for (i = 0; i < 12; i++) {
  57828. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57829. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57830. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57831. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57832. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57833. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57834. var edgeWalk = 0;
  57835. var neighborEdgeWalk = 0;
  57836. //Determine walking pointers based on edge type
  57837. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57838. switch (edge) {
  57839. case PMREMGenerator.CP_EDGE_LEFT:
  57840. // no change to faceEdgeStartPtr
  57841. edgeWalk = this.numChannels * cubeMapSize;
  57842. break;
  57843. case PMREMGenerator.CP_EDGE_RIGHT:
  57844. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57845. edgeWalk = this.numChannels * cubeMapSize;
  57846. break;
  57847. case PMREMGenerator.CP_EDGE_TOP:
  57848. // no change to faceEdgeStartPtr
  57849. edgeWalk = this.numChannels;
  57850. break;
  57851. case PMREMGenerator.CP_EDGE_BOTTOM:
  57852. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57853. edgeWalk = this.numChannels;
  57854. break;
  57855. }
  57856. //For certain types of edge abutments, the neighbor edge walk needs to
  57857. // be flipped: the cases are
  57858. // if a left edge mates with a left or bottom edge on the neighbor
  57859. // if a top edge mates with a top or right edge on the neighbor
  57860. // if a right edge mates with a right or top edge on the neighbor
  57861. // if a bottom edge mates with a bottom or left edge on the neighbor
  57862. //Seeing as the edges are enumerated as follows
  57863. // left =0
  57864. // right =1
  57865. // top =2
  57866. // bottom =3
  57867. //
  57868. //If the edge enums are the same, or the sum of the enums == 3,
  57869. // the neighbor edge walk needs to be flipped
  57870. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57871. switch (neighborEdge) {
  57872. case PMREMGenerator.CP_EDGE_LEFT:
  57873. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57874. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57875. break;
  57876. case PMREMGenerator.CP_EDGE_RIGHT:
  57877. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57878. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57879. break;
  57880. case PMREMGenerator.CP_EDGE_TOP:
  57881. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57882. neighborEdgeWalk = -this.numChannels;
  57883. break;
  57884. case PMREMGenerator.CP_EDGE_BOTTOM:
  57885. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57886. neighborEdgeWalk = -this.numChannels;
  57887. break;
  57888. }
  57889. }
  57890. else {
  57891. //swapped direction neighbor edge walk
  57892. switch (neighborEdge) {
  57893. case PMREMGenerator.CP_EDGE_LEFT:
  57894. //no change to neighborEdgeStartPtr for this case since it points
  57895. // to the upper left corner already
  57896. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57897. break;
  57898. case PMREMGenerator.CP_EDGE_RIGHT:
  57899. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57900. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57901. break;
  57902. case PMREMGenerator.CP_EDGE_TOP:
  57903. //no change to neighborEdgeStartPtr for this case since it points
  57904. // to the upper left corner already
  57905. neighborEdgeWalk = this.numChannels;
  57906. break;
  57907. case PMREMGenerator.CP_EDGE_BOTTOM:
  57908. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57909. neighborEdgeWalk = this.numChannels;
  57910. break;
  57911. }
  57912. }
  57913. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57914. //nearby neighborhood
  57915. //step ahead one texel on edge
  57916. edgeStartIndex += edgeWalk;
  57917. neighborEdgeStartIndex += neighborEdgeWalk;
  57918. // note that this loop does not process the corner texels, since they have already been
  57919. // averaged across faces across earlier
  57920. for (j = 1; j < (cubeMapSize - 1); j++) {
  57921. //for each set of taps along edge, average them
  57922. // and rewrite the results into the edges
  57923. for (k = 0; k < this.numChannels; k++) {
  57924. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57925. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57926. //compute average of tap intensity values
  57927. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57928. //propagate average of taps to edge taps
  57929. cubeMap[face][edgeStartIndex + k] = avgTap;
  57930. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57931. }
  57932. edgeStartIndex += edgeWalk;
  57933. neighborEdgeStartIndex += neighborEdgeWalk;
  57934. }
  57935. }
  57936. };
  57937. return PMREMGenerator;
  57938. }());
  57939. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57940. PMREMGenerator.CP_UDIR = 0;
  57941. PMREMGenerator.CP_VDIR = 1;
  57942. PMREMGenerator.CP_FACEAXIS = 2;
  57943. //used to index cube faces
  57944. PMREMGenerator.CP_FACE_X_POS = 0;
  57945. PMREMGenerator.CP_FACE_X_NEG = 1;
  57946. PMREMGenerator.CP_FACE_Y_POS = 2;
  57947. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57948. PMREMGenerator.CP_FACE_Z_POS = 4;
  57949. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57950. //used to index image edges
  57951. // NOTE.. the actual number corresponding to the edge is important
  57952. // do not change these, or the code will break
  57953. //
  57954. // CP_EDGE_LEFT is u = 0
  57955. // CP_EDGE_RIGHT is u = width-1
  57956. // CP_EDGE_TOP is v = 0
  57957. // CP_EDGE_BOTTOM is v = height-1
  57958. PMREMGenerator.CP_EDGE_LEFT = 0;
  57959. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57960. PMREMGenerator.CP_EDGE_TOP = 2;
  57961. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57962. //corners of CUBE map (P or N specifys if it corresponds to the
  57963. // positive or negative direction each of X, Y, and Z
  57964. PMREMGenerator.CP_CORNER_NNN = 0;
  57965. PMREMGenerator.CP_CORNER_NNP = 1;
  57966. PMREMGenerator.CP_CORNER_NPN = 2;
  57967. PMREMGenerator.CP_CORNER_NPP = 3;
  57968. PMREMGenerator.CP_CORNER_PNN = 4;
  57969. PMREMGenerator.CP_CORNER_PNP = 5;
  57970. PMREMGenerator.CP_CORNER_PPN = 6;
  57971. PMREMGenerator.CP_CORNER_PPP = 7;
  57972. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57973. //3x2 matrices that map cube map indexing vectors in 3d
  57974. // (after face selection and divide through by the
  57975. // _ABSOLUTE VALUE_ of the max coord)
  57976. // into NVC space
  57977. //Note this currently assumes the D3D cube face ordering and orientation
  57978. PMREMGenerator._sgFace2DMapping = [
  57979. //XPOS face
  57980. [[0, 0, -1],
  57981. [0, -1, 0],
  57982. [1, 0, 0]],
  57983. //XNEG face
  57984. [[0, 0, 1],
  57985. [0, -1, 0],
  57986. [-1, 0, 0]],
  57987. //YPOS face
  57988. [[1, 0, 0],
  57989. [0, 0, 1],
  57990. [0, 1, 0]],
  57991. //YNEG face
  57992. [[1, 0, 0],
  57993. [0, 0, -1],
  57994. [0, -1, 0]],
  57995. //ZPOS face
  57996. [[1, 0, 0],
  57997. [0, -1, 0],
  57998. [0, 0, 1]],
  57999. //ZNEG face
  58000. [[-1, 0, 0],
  58001. [0, -1, 0],
  58002. [0, 0, -1]],
  58003. ];
  58004. //------------------------------------------------------------------------------
  58005. // D3D cube map face specification
  58006. // mapping from 3D x,y,z cube map lookup coordinates
  58007. // to 2D within face u,v coordinates
  58008. //
  58009. // --------------------> U direction
  58010. // | (within-face texture space)
  58011. // | _____
  58012. // | | |
  58013. // | | +Y |
  58014. // | _____|_____|_____ _____
  58015. // | | | | | |
  58016. // | | -X | +Z | +X | -Z |
  58017. // | |_____|_____|_____|_____|
  58018. // | | |
  58019. // | | -Y |
  58020. // | |_____|
  58021. // |
  58022. // v V direction
  58023. // (within-face texture space)
  58024. //------------------------------------------------------------------------------
  58025. //Information about neighbors and how texture coorrdinates change across faces
  58026. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  58027. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  58028. //Note this currently assumes the D3D cube face ordering and orientation
  58029. PMREMGenerator._sgCubeNgh = [
  58030. //XPOS face
  58031. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58032. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58033. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58034. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  58035. //XNEG face
  58036. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58037. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  58038. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  58039. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  58040. //YPOS face
  58041. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58042. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58043. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58044. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  58045. //YNEG face
  58046. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58047. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58048. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58049. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  58050. //ZPOS face
  58051. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58052. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58053. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58054. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  58055. //ZNEG face
  58056. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58057. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58058. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  58059. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  58060. ];
  58061. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  58062. // this table is used to average over the edges.
  58063. PMREMGenerator._sgCubeEdgeList = [
  58064. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  58065. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  58066. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  58067. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58068. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  58069. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  58070. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  58071. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  58072. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  58073. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  58074. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  58075. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  58076. ];
  58077. //Information about which of the 8 cube corners are correspond to the
  58078. // the 4 corners in each cube face
  58079. // the order is upper left, upper right, lower left, lower right
  58080. PMREMGenerator._sgCubeCornerList = [
  58081. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  58082. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  58083. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  58084. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  58085. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  58086. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  58087. ];
  58088. Internals.PMREMGenerator = PMREMGenerator;
  58089. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58090. })(BABYLON || (BABYLON = {}));
  58091. //# sourceMappingURL=babylon.pmremgenerator.js.map
  58092. var BABYLON;
  58093. (function (BABYLON) {
  58094. /**
  58095. * This represents a texture coming from an HDR input.
  58096. *
  58097. * The only supported format is currently panorama picture stored in RGBE format.
  58098. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58099. */
  58100. var HDRCubeTexture = (function (_super) {
  58101. __extends(HDRCubeTexture, _super);
  58102. /**
  58103. * Instantiates an HDRTexture from the following parameters.
  58104. *
  58105. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58106. * @param scene The scene the texture will be used in
  58107. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  58108. * @param noMipmap Forces to not generate the mipmap if true
  58109. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58110. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  58111. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58112. */
  58113. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  58114. if (noMipmap === void 0) { noMipmap = false; }
  58115. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58116. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58117. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58118. if (onLoad === void 0) { onLoad = null; }
  58119. if (onError === void 0) { onError = null; }
  58120. var _this = _super.call(this, scene) || this;
  58121. _this._useInGammaSpace = false;
  58122. _this._generateHarmonics = true;
  58123. _this._isBABYLONPreprocessed = false;
  58124. _this._onLoad = null;
  58125. _this._onError = null;
  58126. /**
  58127. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58128. */
  58129. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58130. /**
  58131. * The spherical polynomial data extracted from the texture.
  58132. */
  58133. _this.sphericalPolynomial = null;
  58134. /**
  58135. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58136. * This is usefull at run time to apply the good shader.
  58137. */
  58138. _this.isPMREM = false;
  58139. if (!url) {
  58140. return _this;
  58141. }
  58142. _this.name = url;
  58143. _this.url = url;
  58144. _this.hasAlpha = false;
  58145. _this.isCube = true;
  58146. _this._textureMatrix = BABYLON.Matrix.Identity();
  58147. _this._onLoad = onLoad;
  58148. _this._onError = onError;
  58149. if (size) {
  58150. _this._isBABYLONPreprocessed = false;
  58151. _this._noMipmap = noMipmap;
  58152. _this._size = size;
  58153. _this._useInGammaSpace = useInGammaSpace;
  58154. _this._usePMREMGenerator = usePMREMGenerator &&
  58155. scene.getEngine().getCaps().textureLOD &&
  58156. _this.getScene().getEngine().getCaps().textureFloat &&
  58157. !_this._useInGammaSpace;
  58158. }
  58159. else {
  58160. _this._isBABYLONPreprocessed = true;
  58161. _this._noMipmap = false;
  58162. _this._useInGammaSpace = false;
  58163. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58164. _this.getScene().getEngine().getCaps().textureFloat &&
  58165. !_this._useInGammaSpace;
  58166. }
  58167. _this.isPMREM = _this._usePMREMGenerator;
  58168. _this._texture = _this._getFromCache(url, _this._noMipmap);
  58169. if (!_this._texture) {
  58170. if (!scene.useDelayedTextureLoading) {
  58171. _this.loadTexture();
  58172. }
  58173. else {
  58174. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58175. }
  58176. }
  58177. return _this;
  58178. }
  58179. /**
  58180. * Occurs when the file is a preprocessed .babylon.hdr file.
  58181. */
  58182. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58183. var _this = this;
  58184. var mipLevels = 0;
  58185. var floatArrayView = null;
  58186. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58187. var mips = [];
  58188. var startIndex = 30;
  58189. for (var level = 0; level < mipLevels; level++) {
  58190. mips.push([]);
  58191. // Fill each pixel of the mip level.
  58192. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58193. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58194. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58195. mips[level].push(faceData);
  58196. startIndex += faceSize;
  58197. }
  58198. }
  58199. return mips;
  58200. } : null;
  58201. var callback = function (buffer) {
  58202. // Create Native Array Views
  58203. var intArrayView = new Int32Array(buffer);
  58204. floatArrayView = new Float32Array(buffer);
  58205. // Fill header.
  58206. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58207. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58208. // Update Texture Information.
  58209. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  58210. // Fill polynomial information.
  58211. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  58212. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  58213. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  58214. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  58215. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  58216. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  58217. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  58218. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  58219. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  58220. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  58221. // Fill pixel data.
  58222. mipLevels = intArrayView[29]; // Number of mip levels.
  58223. var startIndex = 30;
  58224. var data = [];
  58225. var faceSize = Math.pow(_this._size, 2) * 3;
  58226. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58227. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  58228. startIndex += faceSize;
  58229. }
  58230. var results = [];
  58231. var byteArray = null;
  58232. // Push each faces.
  58233. for (var k = 0; k < 6; k++) {
  58234. var dataFace = null;
  58235. // If special cases.
  58236. if (!mipmapGenerator) {
  58237. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  58238. dataFace = data[j];
  58239. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58240. // 3 channels of 1 bytes per pixel in bytes.
  58241. var byteBuffer = new ArrayBuffer(faceSize);
  58242. byteArray = new Uint8Array(byteBuffer);
  58243. }
  58244. for (var i = 0; i < _this._size * _this._size; i++) {
  58245. // Put in gamma space if requested.
  58246. if (_this._useInGammaSpace) {
  58247. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58248. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58249. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58250. }
  58251. // Convert to int texture for fallback.
  58252. if (byteArray) {
  58253. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58254. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58255. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58256. // May use luminance instead if the result is not accurate.
  58257. var max = Math.max(Math.max(r, g), b);
  58258. if (max > 255) {
  58259. var scale = 255 / max;
  58260. r *= scale;
  58261. g *= scale;
  58262. b *= scale;
  58263. }
  58264. byteArray[(i * 3) + 0] = r;
  58265. byteArray[(i * 3) + 1] = g;
  58266. byteArray[(i * 3) + 2] = b;
  58267. }
  58268. }
  58269. }
  58270. else {
  58271. dataFace = data[k];
  58272. }
  58273. // Fill the array accordingly.
  58274. if (byteArray) {
  58275. results.push(byteArray);
  58276. }
  58277. else {
  58278. results.push(dataFace);
  58279. }
  58280. }
  58281. return results;
  58282. };
  58283. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  58284. };
  58285. /**
  58286. * Occurs when the file is raw .hdr file.
  58287. */
  58288. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58289. var _this = this;
  58290. var callback = function (buffer) {
  58291. // Extract the raw linear data.
  58292. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58293. // Generate harmonics if needed.
  58294. if (_this._generateHarmonics) {
  58295. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58296. }
  58297. var results = [];
  58298. var byteArray = null;
  58299. // Push each faces.
  58300. for (var j = 0; j < 6; j++) {
  58301. // Create uintarray fallback.
  58302. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58303. // 3 channels of 1 bytes per pixel in bytes.
  58304. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58305. byteArray = new Uint8Array(byteBuffer);
  58306. }
  58307. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58308. // If special cases.
  58309. if (_this._useInGammaSpace || byteArray) {
  58310. for (var i = 0; i < _this._size * _this._size; i++) {
  58311. // Put in gamma space if requested.
  58312. if (_this._useInGammaSpace) {
  58313. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58314. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58315. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58316. }
  58317. // Convert to int texture for fallback.
  58318. if (byteArray) {
  58319. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58320. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58321. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58322. // May use luminance instead if the result is not accurate.
  58323. var max = Math.max(Math.max(r, g), b);
  58324. if (max > 255) {
  58325. var scale = 255 / max;
  58326. r *= scale;
  58327. g *= scale;
  58328. b *= scale;
  58329. }
  58330. byteArray[(i * 3) + 0] = r;
  58331. byteArray[(i * 3) + 1] = g;
  58332. byteArray[(i * 3) + 2] = b;
  58333. }
  58334. }
  58335. }
  58336. if (byteArray) {
  58337. results.push(byteArray);
  58338. }
  58339. else {
  58340. results.push(dataFace);
  58341. }
  58342. }
  58343. return results;
  58344. };
  58345. var mipmapGenerator = null;
  58346. if (!this._noMipmap &&
  58347. this._usePMREMGenerator) {
  58348. mipmapGenerator = function (data) {
  58349. // Custom setup of the generator matching with the PBR shader values.
  58350. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  58351. return generator.filterCubeMap();
  58352. };
  58353. }
  58354. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  58355. };
  58356. /**
  58357. * Starts the loading process of the texture.
  58358. */
  58359. HDRCubeTexture.prototype.loadTexture = function () {
  58360. if (this._isBABYLONPreprocessed) {
  58361. this.loadBabylonTexture();
  58362. }
  58363. else {
  58364. this.loadHDRTexture();
  58365. }
  58366. };
  58367. HDRCubeTexture.prototype.clone = function () {
  58368. var size = this._isBABYLONPreprocessed ? null : this._size;
  58369. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58370. // Base texture
  58371. newTexture.level = this.level;
  58372. newTexture.wrapU = this.wrapU;
  58373. newTexture.wrapV = this.wrapV;
  58374. newTexture.coordinatesIndex = this.coordinatesIndex;
  58375. newTexture.coordinatesMode = this.coordinatesMode;
  58376. return newTexture;
  58377. };
  58378. // Methods
  58379. HDRCubeTexture.prototype.delayLoad = function () {
  58380. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58381. return;
  58382. }
  58383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58384. this._texture = this._getFromCache(this.url, this._noMipmap);
  58385. if (!this._texture) {
  58386. this.loadTexture();
  58387. }
  58388. };
  58389. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58390. return this._textureMatrix;
  58391. };
  58392. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58393. var texture = null;
  58394. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58395. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58396. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58397. texture.name = parsedTexture.name;
  58398. texture.hasAlpha = parsedTexture.hasAlpha;
  58399. texture.level = parsedTexture.level;
  58400. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58401. }
  58402. return texture;
  58403. };
  58404. HDRCubeTexture.prototype.serialize = function () {
  58405. if (!this.name) {
  58406. return null;
  58407. }
  58408. var serializationObject = {};
  58409. serializationObject.name = this.name;
  58410. serializationObject.hasAlpha = this.hasAlpha;
  58411. serializationObject.isCube = true;
  58412. serializationObject.level = this.level;
  58413. serializationObject.size = this._size;
  58414. serializationObject.coordinatesMode = this.coordinatesMode;
  58415. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58416. serializationObject.generateHarmonics = this._generateHarmonics;
  58417. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58418. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58419. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58420. serializationObject.noMipmap = this._noMipmap;
  58421. return serializationObject;
  58422. };
  58423. /**
  58424. * Saves as a file the data contained in the texture in a binary format.
  58425. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58426. * as the spherical used in the lighting.
  58427. * @param url The HDR file url.
  58428. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58429. * @param onError Method called if any error happens during download.
  58430. * @return The packed binary data.
  58431. */
  58432. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58433. if (onError === void 0) { onError = null; }
  58434. var callback = function (buffer) {
  58435. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58436. // Returns a URL you can use as a href.
  58437. var objUrl = window.URL.createObjectURL(data);
  58438. // Simulates a link to it and click to dowload.
  58439. var a = document.createElement("a");
  58440. document.body.appendChild(a);
  58441. a.style.display = "none";
  58442. a.href = objUrl;
  58443. a.download = "envmap.babylon.hdr";
  58444. a.click();
  58445. };
  58446. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58447. };
  58448. /**
  58449. * Serializes the data contained in the texture in a binary format.
  58450. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58451. * as the spherical used in the lighting.
  58452. * @param url The HDR file url.
  58453. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58454. * @param onError Method called if any error happens during download.
  58455. * @return The packed binary data.
  58456. */
  58457. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58458. if (onError === void 0) { onError = null; }
  58459. // Needs the url tho create the texture.
  58460. if (!url) {
  58461. return null;
  58462. }
  58463. // Check Power of two size.
  58464. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58465. return null;
  58466. }
  58467. var getDataCallback = function (dataBuffer) {
  58468. // Extract the raw linear data.
  58469. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  58470. // Generate harmonics if needed.
  58471. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  58472. // Generate seamless faces
  58473. var mipGeneratorArray = [];
  58474. // Data are known to be in +X +Y +Z -X -Y -Z
  58475. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  58476. mipGeneratorArray.push(cubeData.right); // +X
  58477. mipGeneratorArray.push(cubeData.left); // -X
  58478. mipGeneratorArray.push(cubeData.up); // +Y
  58479. mipGeneratorArray.push(cubeData.down); // -Y
  58480. mipGeneratorArray.push(cubeData.front); // +Z
  58481. mipGeneratorArray.push(cubeData.back); // -Z
  58482. // Custom setup of the generator matching with the PBR shader values.
  58483. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  58484. var mippedData = generator.filterCubeMap();
  58485. // Compute required byte length.
  58486. var byteLength = 1 * 4; // Raw Data Version int32.
  58487. byteLength += 4; // CubeMap max mip face size int32.
  58488. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  58489. // Add data size.
  58490. byteLength += 4; // Number of mip levels int32.
  58491. for (var level = 0; level < mippedData.length; level++) {
  58492. var mipSize = size >> level;
  58493. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  58494. }
  58495. // Prepare binary structure.
  58496. var buffer = new ArrayBuffer(byteLength);
  58497. var intArrayView = new Int32Array(buffer);
  58498. var floatArrayView = new Float32Array(buffer);
  58499. // Fill header.
  58500. intArrayView[0] = 1; // Version 1.
  58501. intArrayView[1] = size; // CubeMap max mip face size.
  58502. // Fill polynomial information.
  58503. sphericalPolynomial.x.toArray(floatArrayView, 2);
  58504. sphericalPolynomial.y.toArray(floatArrayView, 5);
  58505. sphericalPolynomial.z.toArray(floatArrayView, 8);
  58506. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  58507. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  58508. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  58509. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  58510. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  58511. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  58512. // Fill pixel data.
  58513. intArrayView[29] = mippedData.length; // Number of mip levels.
  58514. var startIndex = 30;
  58515. for (var level = 0; level < mippedData.length; level++) {
  58516. // Fill each pixel of the mip level.
  58517. var faceSize = Math.pow(size >> level, 2) * 3;
  58518. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58519. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  58520. startIndex += faceSize;
  58521. }
  58522. }
  58523. // Callback.
  58524. callback(buffer);
  58525. };
  58526. // Download and process.
  58527. BABYLON.Tools.LoadFile(url, function (data) {
  58528. getDataCallback(data);
  58529. }, null, null, true, onError);
  58530. };
  58531. return HDRCubeTexture;
  58532. }(BABYLON.BaseTexture));
  58533. HDRCubeTexture._facesMapping = [
  58534. "right",
  58535. "up",
  58536. "front",
  58537. "left",
  58538. "down",
  58539. "back"
  58540. ];
  58541. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58542. })(BABYLON || (BABYLON = {}));
  58543. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58544. var BABYLON;
  58545. (function (BABYLON) {
  58546. var Debug;
  58547. (function (Debug) {
  58548. /**
  58549. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58550. */
  58551. var SkeletonViewer = (function () {
  58552. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58553. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58554. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58555. this.skeleton = skeleton;
  58556. this.mesh = mesh;
  58557. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58558. this.renderingGroupId = renderingGroupId;
  58559. this.color = BABYLON.Color3.White();
  58560. this._debugLines = [];
  58561. this._isEnabled = false;
  58562. this._scene = scene;
  58563. this.update();
  58564. this._renderFunction = this.update.bind(this);
  58565. }
  58566. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58567. get: function () {
  58568. return this._isEnabled;
  58569. },
  58570. set: function (value) {
  58571. if (this._isEnabled === value) {
  58572. return;
  58573. }
  58574. this._isEnabled = value;
  58575. if (value) {
  58576. this._scene.registerBeforeRender(this._renderFunction);
  58577. }
  58578. else {
  58579. this._scene.unregisterBeforeRender(this._renderFunction);
  58580. }
  58581. },
  58582. enumerable: true,
  58583. configurable: true
  58584. });
  58585. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58586. if (x === void 0) { x = 0; }
  58587. if (y === void 0) { y = 0; }
  58588. if (z === void 0) { z = 0; }
  58589. var tmat = BABYLON.Tmp.Matrix[0];
  58590. var parentBone = bone.getParent();
  58591. tmat.copyFrom(bone.getLocalMatrix());
  58592. if (x !== 0 || y !== 0 || z !== 0) {
  58593. var tmat2 = BABYLON.Tmp.Matrix[1];
  58594. BABYLON.Matrix.IdentityToRef(tmat2);
  58595. tmat2.m[12] = x;
  58596. tmat2.m[13] = y;
  58597. tmat2.m[14] = z;
  58598. tmat2.multiplyToRef(tmat, tmat);
  58599. }
  58600. if (parentBone) {
  58601. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58602. }
  58603. tmat.multiplyToRef(meshMat, tmat);
  58604. position.x = tmat.m[12];
  58605. position.y = tmat.m[13];
  58606. position.z = tmat.m[14];
  58607. };
  58608. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58609. var len = bones.length;
  58610. for (var i = 0; i < len; i++) {
  58611. var bone = bones[i];
  58612. var points = this._debugLines[i];
  58613. if (!points) {
  58614. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58615. this._debugLines[i] = points;
  58616. }
  58617. this._getBonePosition(points[0], bone, meshMat);
  58618. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58619. }
  58620. };
  58621. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58622. var len = bones.length;
  58623. var boneNum = 0;
  58624. for (var i = len - 1; i >= 0; i--) {
  58625. var childBone = bones[i];
  58626. var parentBone = childBone.getParent();
  58627. if (!parentBone) {
  58628. continue;
  58629. }
  58630. var points = this._debugLines[boneNum];
  58631. if (!points) {
  58632. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58633. this._debugLines[boneNum] = points;
  58634. }
  58635. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58636. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58637. boneNum++;
  58638. }
  58639. };
  58640. SkeletonViewer.prototype.update = function () {
  58641. if (this.autoUpdateBonesMatrices) {
  58642. this.skeleton.computeAbsoluteTransforms();
  58643. }
  58644. if (this.skeleton.bones[0].length === undefined) {
  58645. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58646. }
  58647. else {
  58648. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58649. }
  58650. if (!this._debugMesh) {
  58651. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58652. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58653. }
  58654. else {
  58655. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58656. }
  58657. this._debugMesh.color = this.color;
  58658. };
  58659. SkeletonViewer.prototype.dispose = function () {
  58660. if (this._debugMesh) {
  58661. this.isEnabled = false;
  58662. this._debugMesh.dispose();
  58663. this._debugMesh = null;
  58664. }
  58665. };
  58666. return SkeletonViewer;
  58667. }());
  58668. Debug.SkeletonViewer = SkeletonViewer;
  58669. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58670. })(BABYLON || (BABYLON = {}));
  58671. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58672. var BABYLON;
  58673. (function (BABYLON) {
  58674. var Debug;
  58675. (function (Debug) {
  58676. var AxesViewer = (function () {
  58677. function AxesViewer(scene, scaleLines) {
  58678. if (scaleLines === void 0) { scaleLines = 1; }
  58679. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58680. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58681. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58682. this.scaleLines = 1;
  58683. this.scaleLines = scaleLines;
  58684. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58685. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58686. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58687. this._xmesh.renderingGroupId = 2;
  58688. this._ymesh.renderingGroupId = 2;
  58689. this._zmesh.renderingGroupId = 2;
  58690. this._xmesh.material.checkReadyOnlyOnce = true;
  58691. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58692. this._ymesh.material.checkReadyOnlyOnce = true;
  58693. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58694. this._zmesh.material.checkReadyOnlyOnce = true;
  58695. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58696. this.scene = scene;
  58697. }
  58698. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58699. var scaleLines = this.scaleLines;
  58700. var point1 = this._xline[0];
  58701. var point2 = this._xline[1];
  58702. point1.x = position.x;
  58703. point1.y = position.y;
  58704. point1.z = position.z;
  58705. point2.x = point1.x + xaxis.x * scaleLines;
  58706. point2.y = point1.y + xaxis.y * scaleLines;
  58707. point2.z = point1.z + xaxis.z * scaleLines;
  58708. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  58709. point1 = this._yline[0];
  58710. point2 = this._yline[1];
  58711. point1.x = position.x;
  58712. point1.y = position.y;
  58713. point1.z = position.z;
  58714. point2.x = point1.x + yaxis.x * scaleLines;
  58715. point2.y = point1.y + yaxis.y * scaleLines;
  58716. point2.z = point1.z + yaxis.z * scaleLines;
  58717. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  58718. point1 = this._zline[0];
  58719. point2 = this._zline[1];
  58720. point1.x = position.x;
  58721. point1.y = position.y;
  58722. point1.z = position.z;
  58723. point2.x = point1.x + zaxis.x * scaleLines;
  58724. point2.y = point1.y + zaxis.y * scaleLines;
  58725. point2.z = point1.z + zaxis.z * scaleLines;
  58726. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  58727. };
  58728. AxesViewer.prototype.dispose = function () {
  58729. if (this._xmesh) {
  58730. this._xmesh.dispose();
  58731. this._ymesh.dispose();
  58732. this._zmesh.dispose();
  58733. this._xmesh = null;
  58734. this._ymesh = null;
  58735. this._zmesh = null;
  58736. this._xline = null;
  58737. this._yline = null;
  58738. this._zline = null;
  58739. this.scene = null;
  58740. }
  58741. };
  58742. return AxesViewer;
  58743. }());
  58744. Debug.AxesViewer = AxesViewer;
  58745. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58746. })(BABYLON || (BABYLON = {}));
  58747. //# sourceMappingURL=babylon.axesViewer.js.map
  58748. var BABYLON;
  58749. (function (BABYLON) {
  58750. var Debug;
  58751. (function (Debug) {
  58752. var BoneAxesViewer = (function (_super) {
  58753. __extends(BoneAxesViewer, _super);
  58754. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58755. if (scaleLines === void 0) { scaleLines = 1; }
  58756. var _this = _super.call(this, scene, scaleLines) || this;
  58757. _this.pos = BABYLON.Vector3.Zero();
  58758. _this.xaxis = BABYLON.Vector3.Zero();
  58759. _this.yaxis = BABYLON.Vector3.Zero();
  58760. _this.zaxis = BABYLON.Vector3.Zero();
  58761. _this.mesh = mesh;
  58762. _this.bone = bone;
  58763. return _this;
  58764. }
  58765. BoneAxesViewer.prototype.update = function () {
  58766. var bone = this.bone;
  58767. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58768. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58769. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58770. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58771. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58772. };
  58773. BoneAxesViewer.prototype.dispose = function () {
  58774. if (this.pos) {
  58775. this.pos = null;
  58776. this.xaxis = null;
  58777. this.yaxis = null;
  58778. this.zaxis = null;
  58779. this.mesh = null;
  58780. this.bone = null;
  58781. _super.prototype.dispose.call(this);
  58782. }
  58783. };
  58784. return BoneAxesViewer;
  58785. }(Debug.AxesViewer));
  58786. Debug.BoneAxesViewer = BoneAxesViewer;
  58787. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58788. })(BABYLON || (BABYLON = {}));
  58789. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58790. var BABYLON;
  58791. (function (BABYLON) {
  58792. /**
  58793. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58794. * It can help converting any input color in a desired output one. This can then be used to create effects
  58795. * from sepia, black and white to sixties or futuristic rendering...
  58796. *
  58797. * The only supported format is currently 3dl.
  58798. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58799. */
  58800. var ColorGradingTexture = (function (_super) {
  58801. __extends(ColorGradingTexture, _super);
  58802. /**
  58803. * Instantiates a ColorGradingTexture from the following parameters.
  58804. *
  58805. * @param url The location of the color gradind data (currently only supporting 3dl)
  58806. * @param scene The scene the texture will be used in
  58807. */
  58808. function ColorGradingTexture(url, scene) {
  58809. var _this = _super.call(this, scene) || this;
  58810. if (!url) {
  58811. return _this;
  58812. }
  58813. _this._textureMatrix = BABYLON.Matrix.Identity();
  58814. _this.name = url;
  58815. _this.url = url;
  58816. _this.hasAlpha = false;
  58817. _this.isCube = false;
  58818. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58819. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58820. _this.anisotropicFilteringLevel = 1;
  58821. _this._texture = _this._getFromCache(url, true);
  58822. if (!_this._texture) {
  58823. if (!scene.useDelayedTextureLoading) {
  58824. _this.loadTexture();
  58825. }
  58826. else {
  58827. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58828. }
  58829. }
  58830. return _this;
  58831. }
  58832. /**
  58833. * Returns the texture matrix used in most of the material.
  58834. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58835. */
  58836. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58837. return this._textureMatrix;
  58838. };
  58839. /**
  58840. * Occurs when the file being loaded is a .3dl LUT file.
  58841. */
  58842. ColorGradingTexture.prototype.load3dlTexture = function () {
  58843. var _this = this;
  58844. var mipLevels = 0;
  58845. var floatArrayView = null;
  58846. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58847. this._texture = texture;
  58848. var callback = function (text) {
  58849. var data;
  58850. var tempData;
  58851. var line;
  58852. var lines = text.split('\n');
  58853. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58854. var maxColor = 0;
  58855. for (var i = 0; i < lines.length; i++) {
  58856. line = lines[i];
  58857. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58858. continue;
  58859. if (line.indexOf('#') === 0)
  58860. continue;
  58861. var words = line.split(" ");
  58862. if (size === 0) {
  58863. // Number of space + one
  58864. size = words.length;
  58865. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58866. tempData = new Float32Array(size * size * size * 4);
  58867. continue;
  58868. }
  58869. if (size != 0) {
  58870. var r = Math.max(parseInt(words[0]), 0);
  58871. var g = Math.max(parseInt(words[1]), 0);
  58872. var b = Math.max(parseInt(words[2]), 0);
  58873. maxColor = Math.max(r, maxColor);
  58874. maxColor = Math.max(g, maxColor);
  58875. maxColor = Math.max(b, maxColor);
  58876. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58877. tempData[pixelStorageIndex + 0] = r;
  58878. tempData[pixelStorageIndex + 1] = g;
  58879. tempData[pixelStorageIndex + 2] = b;
  58880. tempData[pixelStorageIndex + 3] = 0;
  58881. pixelIndexSlice++;
  58882. if (pixelIndexSlice % size == 0) {
  58883. pixelIndexH++;
  58884. pixelIndexSlice = 0;
  58885. if (pixelIndexH % size == 0) {
  58886. pixelIndexW++;
  58887. pixelIndexH = 0;
  58888. }
  58889. }
  58890. }
  58891. }
  58892. for (var i = 0; i < tempData.length; i++) {
  58893. var value = tempData[i];
  58894. data[i] = (value / maxColor * 255);
  58895. }
  58896. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58897. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58898. };
  58899. BABYLON.Tools.LoadFile(this.url, callback);
  58900. return this._texture;
  58901. };
  58902. /**
  58903. * Starts the loading process of the texture.
  58904. */
  58905. ColorGradingTexture.prototype.loadTexture = function () {
  58906. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58907. this.load3dlTexture();
  58908. }
  58909. };
  58910. /**
  58911. * Clones the color gradind texture.
  58912. */
  58913. ColorGradingTexture.prototype.clone = function () {
  58914. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58915. // Base texture
  58916. newTexture.level = this.level;
  58917. return newTexture;
  58918. };
  58919. /**
  58920. * Called during delayed load for textures.
  58921. */
  58922. ColorGradingTexture.prototype.delayLoad = function () {
  58923. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58924. return;
  58925. }
  58926. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58927. this._texture = this._getFromCache(this.url, true);
  58928. if (!this._texture) {
  58929. this.loadTexture();
  58930. }
  58931. };
  58932. /**
  58933. * Binds the color grading to the shader.
  58934. * @param colorGrading The texture to bind
  58935. * @param effect The effect to bind to
  58936. */
  58937. ColorGradingTexture.Bind = function (colorGrading, effect) {
  58938. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  58939. var x = colorGrading.level; // Texture Level
  58940. var y = colorGrading.getSize().height; // Texture Size example with 8
  58941. var z = y - 1.0; // SizeMinusOne 8 - 1
  58942. var w = 1 / y; // Space of 1 slice 1 / 8
  58943. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  58944. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  58945. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  58946. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  58947. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  58948. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58949. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58950. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  58951. };
  58952. /**
  58953. * Prepare the list of uniforms associated with the ColorGrading effects.
  58954. * @param uniformsList The list of uniforms used in the effect
  58955. * @param samplersList The list of samplers used in the effect
  58956. */
  58957. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  58958. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  58959. samplersList.push("cameraColorGrading2DSampler");
  58960. };
  58961. /**
  58962. * Parses a color grading texture serialized by Babylon.
  58963. * @param parsedTexture The texture information being parsedTexture
  58964. * @param scene The scene to load the texture in
  58965. * @param rootUrl The root url of the data assets to load
  58966. * @return A color gradind texture
  58967. */
  58968. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58969. var texture = null;
  58970. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58971. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58972. texture.name = parsedTexture.name;
  58973. texture.level = parsedTexture.level;
  58974. }
  58975. return texture;
  58976. };
  58977. /**
  58978. * Serializes the LUT texture to json format.
  58979. */
  58980. ColorGradingTexture.prototype.serialize = function () {
  58981. if (!this.name) {
  58982. return null;
  58983. }
  58984. var serializationObject = {};
  58985. serializationObject.name = this.name;
  58986. serializationObject.level = this.level;
  58987. serializationObject.customType = "BABYLON.ColorGradingTexture";
  58988. return serializationObject;
  58989. };
  58990. return ColorGradingTexture;
  58991. }(BABYLON.BaseTexture));
  58992. /**
  58993. * Empty line regex stored for GC.
  58994. */
  58995. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58996. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58997. })(BABYLON || (BABYLON = {}));
  58998. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  58999. var BABYLON;
  59000. (function (BABYLON) {
  59001. /**
  59002. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59003. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59004. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  59005. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59006. */
  59007. var ColorCurves = (function () {
  59008. function ColorCurves() {
  59009. this._dirty = true;
  59010. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59011. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59012. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59013. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59014. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59015. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59016. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59017. this._globalHue = 30;
  59018. this._globalDensity = 0;
  59019. this._globalSaturation = 0;
  59020. this._globalExposure = 0;
  59021. this._highlightsHue = 30;
  59022. this._highlightsDensity = 0;
  59023. this._highlightsSaturation = 0;
  59024. this._highlightsExposure = 0;
  59025. this._midtonesHue = 30;
  59026. this._midtonesDensity = 0;
  59027. this._midtonesSaturation = 0;
  59028. this._midtonesExposure = 0;
  59029. this._shadowsHue = 30;
  59030. this._shadowsDensity = 0;
  59031. this._shadowsSaturation = 0;
  59032. this._shadowsExposure = 0;
  59033. }
  59034. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  59035. /**
  59036. * Gets the global Hue value.
  59037. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59038. */
  59039. get: function () {
  59040. return this._globalHue;
  59041. },
  59042. /**
  59043. * Sets the global Hue value.
  59044. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59045. */
  59046. set: function (value) {
  59047. this._globalHue = value;
  59048. this._dirty = true;
  59049. },
  59050. enumerable: true,
  59051. configurable: true
  59052. });
  59053. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  59054. /**
  59055. * Gets the global Density value.
  59056. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59057. * Values less than zero provide a filter of opposite hue.
  59058. */
  59059. get: function () {
  59060. return this._globalDensity;
  59061. },
  59062. /**
  59063. * Sets the global Density value.
  59064. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59065. * Values less than zero provide a filter of opposite hue.
  59066. */
  59067. set: function (value) {
  59068. this._globalDensity = value;
  59069. this._dirty = true;
  59070. },
  59071. enumerable: true,
  59072. configurable: true
  59073. });
  59074. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  59075. /**
  59076. * Gets the global Saturation value.
  59077. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59078. */
  59079. get: function () {
  59080. return this._globalSaturation;
  59081. },
  59082. /**
  59083. * Sets the global Saturation value.
  59084. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59085. */
  59086. set: function (value) {
  59087. this._globalSaturation = value;
  59088. this._dirty = true;
  59089. },
  59090. enumerable: true,
  59091. configurable: true
  59092. });
  59093. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  59094. /**
  59095. * Gets the highlights Hue value.
  59096. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59097. */
  59098. get: function () {
  59099. return this._highlightsHue;
  59100. },
  59101. /**
  59102. * Sets the highlights Hue value.
  59103. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59104. */
  59105. set: function (value) {
  59106. this._highlightsHue = value;
  59107. this._dirty = true;
  59108. },
  59109. enumerable: true,
  59110. configurable: true
  59111. });
  59112. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  59113. /**
  59114. * Gets the highlights Density value.
  59115. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59116. * Values less than zero provide a filter of opposite hue.
  59117. */
  59118. get: function () {
  59119. return this._highlightsDensity;
  59120. },
  59121. /**
  59122. * Sets the highlights Density value.
  59123. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59124. * Values less than zero provide a filter of opposite hue.
  59125. */
  59126. set: function (value) {
  59127. this._highlightsDensity = value;
  59128. this._dirty = true;
  59129. },
  59130. enumerable: true,
  59131. configurable: true
  59132. });
  59133. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  59134. /**
  59135. * Gets the highlights Saturation value.
  59136. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59137. */
  59138. get: function () {
  59139. return this._highlightsSaturation;
  59140. },
  59141. /**
  59142. * Sets the highlights Saturation value.
  59143. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59144. */
  59145. set: function (value) {
  59146. this._highlightsSaturation = value;
  59147. this._dirty = true;
  59148. },
  59149. enumerable: true,
  59150. configurable: true
  59151. });
  59152. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  59153. /**
  59154. * Gets the highlights Exposure value.
  59155. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59156. */
  59157. get: function () {
  59158. return this._highlightsExposure;
  59159. },
  59160. /**
  59161. * Sets the highlights Exposure value.
  59162. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59163. */
  59164. set: function (value) {
  59165. this._highlightsExposure = value;
  59166. this._dirty = true;
  59167. },
  59168. enumerable: true,
  59169. configurable: true
  59170. });
  59171. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  59172. /**
  59173. * Gets the midtones Hue value.
  59174. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59175. */
  59176. get: function () {
  59177. return this._midtonesHue;
  59178. },
  59179. /**
  59180. * Sets the midtones Hue value.
  59181. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59182. */
  59183. set: function (value) {
  59184. this._midtonesHue = value;
  59185. this._dirty = true;
  59186. },
  59187. enumerable: true,
  59188. configurable: true
  59189. });
  59190. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  59191. /**
  59192. * Gets the midtones Density value.
  59193. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59194. * Values less than zero provide a filter of opposite hue.
  59195. */
  59196. get: function () {
  59197. return this._midtonesDensity;
  59198. },
  59199. /**
  59200. * Sets the midtones Density value.
  59201. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59202. * Values less than zero provide a filter of opposite hue.
  59203. */
  59204. set: function (value) {
  59205. this._midtonesDensity = value;
  59206. this._dirty = true;
  59207. },
  59208. enumerable: true,
  59209. configurable: true
  59210. });
  59211. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  59212. /**
  59213. * Gets the midtones Saturation value.
  59214. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59215. */
  59216. get: function () {
  59217. return this._midtonesSaturation;
  59218. },
  59219. /**
  59220. * Sets the midtones Saturation value.
  59221. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59222. */
  59223. set: function (value) {
  59224. this._midtonesSaturation = value;
  59225. this._dirty = true;
  59226. },
  59227. enumerable: true,
  59228. configurable: true
  59229. });
  59230. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  59231. /**
  59232. * Gets the midtones Exposure value.
  59233. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59234. */
  59235. get: function () {
  59236. return this._midtonesExposure;
  59237. },
  59238. /**
  59239. * Sets the midtones Exposure value.
  59240. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59241. */
  59242. set: function (value) {
  59243. this._midtonesExposure = value;
  59244. this._dirty = true;
  59245. },
  59246. enumerable: true,
  59247. configurable: true
  59248. });
  59249. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  59250. /**
  59251. * Gets the shadows Hue value.
  59252. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59253. */
  59254. get: function () {
  59255. return this._shadowsHue;
  59256. },
  59257. /**
  59258. * Sets the shadows Hue value.
  59259. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59260. */
  59261. set: function (value) {
  59262. this._shadowsHue = value;
  59263. this._dirty = true;
  59264. },
  59265. enumerable: true,
  59266. configurable: true
  59267. });
  59268. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  59269. /**
  59270. * Gets the shadows Density value.
  59271. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59272. * Values less than zero provide a filter of opposite hue.
  59273. */
  59274. get: function () {
  59275. return this._shadowsDensity;
  59276. },
  59277. /**
  59278. * Sets the shadows Density value.
  59279. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59280. * Values less than zero provide a filter of opposite hue.
  59281. */
  59282. set: function (value) {
  59283. this._shadowsDensity = value;
  59284. this._dirty = true;
  59285. },
  59286. enumerable: true,
  59287. configurable: true
  59288. });
  59289. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  59290. /**
  59291. * Gets the shadows Saturation value.
  59292. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59293. */
  59294. get: function () {
  59295. return this._shadowsSaturation;
  59296. },
  59297. /**
  59298. * Sets the shadows Saturation value.
  59299. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59300. */
  59301. set: function (value) {
  59302. this._shadowsSaturation = value;
  59303. this._dirty = true;
  59304. },
  59305. enumerable: true,
  59306. configurable: true
  59307. });
  59308. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  59309. /**
  59310. * Gets the shadows Exposure value.
  59311. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59312. */
  59313. get: function () {
  59314. return this._shadowsExposure;
  59315. },
  59316. /**
  59317. * Sets the shadows Exposure value.
  59318. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59319. */
  59320. set: function (value) {
  59321. this._shadowsExposure = value;
  59322. this._dirty = true;
  59323. },
  59324. enumerable: true,
  59325. configurable: true
  59326. });
  59327. /**
  59328. * Binds the color curves to the shader.
  59329. * @param colorCurves The color curve to bind
  59330. * @param effect The effect to bind to
  59331. */
  59332. ColorCurves.Bind = function (colorCurves, effect) {
  59333. if (colorCurves._dirty) {
  59334. colorCurves._dirty = false;
  59335. // Fill in global info.
  59336. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  59337. // Compute highlights info.
  59338. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  59339. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  59340. // Compute midtones info.
  59341. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  59342. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  59343. // Compute shadows info.
  59344. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  59345. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  59346. // Compute deltas (neutral is midtones).
  59347. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  59348. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  59349. }
  59350. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  59351. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  59352. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  59353. };
  59354. /**
  59355. * Prepare the list of uniforms associated with the ColorCurves effects.
  59356. * @param uniformsList The list of uniforms used in the effect
  59357. */
  59358. ColorCurves.PrepareUniforms = function (uniformsList) {
  59359. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  59360. };
  59361. /**
  59362. * Returns color grading data based on a hue, density, saturation and exposure value.
  59363. * @param filterHue The hue of the color filter.
  59364. * @param filterDensity The density of the color filter.
  59365. * @param saturation The saturation.
  59366. * @param exposure The exposure.
  59367. * @param result The result data container.
  59368. */
  59369. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  59370. if (hue == null) {
  59371. return;
  59372. }
  59373. hue = ColorCurves.clamp(hue, 0, 360);
  59374. density = ColorCurves.clamp(density, -100, 100);
  59375. saturation = ColorCurves.clamp(saturation, -100, 100);
  59376. exposure = ColorCurves.clamp(exposure, -100, 100);
  59377. // Remap the slider/config filter density with non-linear mapping and also scale by half
  59378. // so that the maximum filter density is only 50% control. This provides fine control
  59379. // for small values and reasonable range.
  59380. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  59381. density *= 0.5;
  59382. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  59383. if (density < 0) {
  59384. density *= -1;
  59385. hue = (hue + 180) % 360;
  59386. }
  59387. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  59388. result.scaleToRef(2, result);
  59389. result.a = 1 + 0.01 * saturation;
  59390. };
  59391. /**
  59392. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  59393. * @param value The input slider value in range [-100,100].
  59394. * @returns Adjusted value.
  59395. */
  59396. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  59397. value /= 100;
  59398. var x = Math.abs(value);
  59399. x = Math.pow(x, 2);
  59400. if (value < 0) {
  59401. x *= -1;
  59402. }
  59403. x *= 100;
  59404. return x;
  59405. };
  59406. /**
  59407. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  59408. * @param hue The hue (H) input.
  59409. * @param saturation The saturation (S) input.
  59410. * @param brightness The brightness (B) input.
  59411. * @result An RGBA color represented as Vector4.
  59412. */
  59413. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  59414. var h = ColorCurves.clamp(hue, 0, 360);
  59415. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  59416. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  59417. if (s === 0) {
  59418. result.r = v;
  59419. result.g = v;
  59420. result.b = v;
  59421. }
  59422. else {
  59423. // sector 0 to 5
  59424. h /= 60;
  59425. var i = Math.floor(h);
  59426. // fractional part of h
  59427. var f = h - i;
  59428. var p = v * (1 - s);
  59429. var q = v * (1 - s * f);
  59430. var t = v * (1 - s * (1 - f));
  59431. switch (i) {
  59432. case 0:
  59433. result.r = v;
  59434. result.g = t;
  59435. result.b = p;
  59436. break;
  59437. case 1:
  59438. result.r = q;
  59439. result.g = v;
  59440. result.b = p;
  59441. break;
  59442. case 2:
  59443. result.r = p;
  59444. result.g = v;
  59445. result.b = t;
  59446. break;
  59447. case 3:
  59448. result.r = p;
  59449. result.g = q;
  59450. result.b = v;
  59451. break;
  59452. case 4:
  59453. result.r = t;
  59454. result.g = p;
  59455. result.b = v;
  59456. break;
  59457. default:
  59458. result.r = v;
  59459. result.g = p;
  59460. result.b = q;
  59461. break;
  59462. }
  59463. }
  59464. result.a = 1;
  59465. };
  59466. /**
  59467. * Returns a value clamped between min and max
  59468. * @param value The value to clamp
  59469. * @param min The minimum of value
  59470. * @param max The maximum of value
  59471. * @returns The clamped value.
  59472. */
  59473. ColorCurves.clamp = function (value, min, max) {
  59474. return Math.min(Math.max(value, min), max);
  59475. };
  59476. /**
  59477. * Clones the current color curve instance.
  59478. * @return The cloned curves
  59479. */
  59480. ColorCurves.prototype.clone = function () {
  59481. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  59482. };
  59483. /**
  59484. * Serializes the current color curve instance to a json representation.
  59485. * @return a JSON representation
  59486. */
  59487. ColorCurves.prototype.serialize = function () {
  59488. return BABYLON.SerializationHelper.Serialize(this);
  59489. };
  59490. /**
  59491. * Parses the color curve from a json representation.
  59492. * @param source the JSON source to parse
  59493. * @return The parsed curves
  59494. */
  59495. ColorCurves.Parse = function (source) {
  59496. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  59497. };
  59498. return ColorCurves;
  59499. }());
  59500. __decorate([
  59501. BABYLON.serialize()
  59502. ], ColorCurves.prototype, "_globalHue", void 0);
  59503. __decorate([
  59504. BABYLON.serialize()
  59505. ], ColorCurves.prototype, "_globalDensity", void 0);
  59506. __decorate([
  59507. BABYLON.serialize()
  59508. ], ColorCurves.prototype, "_globalSaturation", void 0);
  59509. __decorate([
  59510. BABYLON.serialize()
  59511. ], ColorCurves.prototype, "_globalExposure", void 0);
  59512. __decorate([
  59513. BABYLON.serialize()
  59514. ], ColorCurves.prototype, "_highlightsHue", void 0);
  59515. __decorate([
  59516. BABYLON.serialize()
  59517. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  59518. __decorate([
  59519. BABYLON.serialize()
  59520. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  59521. __decorate([
  59522. BABYLON.serialize()
  59523. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  59524. __decorate([
  59525. BABYLON.serialize()
  59526. ], ColorCurves.prototype, "_midtonesHue", void 0);
  59527. __decorate([
  59528. BABYLON.serialize()
  59529. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  59530. __decorate([
  59531. BABYLON.serialize()
  59532. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  59533. __decorate([
  59534. BABYLON.serialize()
  59535. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  59536. BABYLON.ColorCurves = ColorCurves;
  59537. })(BABYLON || (BABYLON = {}));
  59538. //# sourceMappingURL=babylon.colorCurves.js.map
  59539. var BABYLON;
  59540. (function (BABYLON) {
  59541. var PBRMaterialDefines = (function (_super) {
  59542. __extends(PBRMaterialDefines, _super);
  59543. function PBRMaterialDefines() {
  59544. var _this = _super.call(this) || this;
  59545. _this.ALBEDO = false;
  59546. _this.AMBIENT = false;
  59547. _this.AMBIENTINGRAYSCALE = false;
  59548. _this.OPACITY = false;
  59549. _this.OPACITYRGB = false;
  59550. _this.REFLECTION = false;
  59551. _this.EMISSIVE = false;
  59552. _this.REFLECTIVITY = false;
  59553. _this.BUMP = false;
  59554. _this.PARALLAX = false;
  59555. _this.PARALLAXOCCLUSION = false;
  59556. _this.SPECULAROVERALPHA = false;
  59557. _this.CLIPPLANE = false;
  59558. _this.ALPHATEST = false;
  59559. _this.ALPHAFROMALBEDO = false;
  59560. _this.POINTSIZE = false;
  59561. _this.FOG = false;
  59562. _this.SPECULARTERM = false;
  59563. _this.OPACITYFRESNEL = false;
  59564. _this.EMISSIVEFRESNEL = false;
  59565. _this.FRESNEL = false;
  59566. _this.NORMAL = false;
  59567. _this.TANGENT = false;
  59568. _this.UV1 = false;
  59569. _this.UV2 = false;
  59570. _this.VERTEXCOLOR = false;
  59571. _this.VERTEXALPHA = false;
  59572. _this.NUM_BONE_INFLUENCERS = 0;
  59573. _this.BonesPerMesh = 0;
  59574. _this.INSTANCES = false;
  59575. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  59576. _this.MICROSURFACEAUTOMATIC = false;
  59577. _this.EMISSIVEASILLUMINATION = false;
  59578. _this.LINKEMISSIVEWITHALBEDO = false;
  59579. _this.LIGHTMAP = false;
  59580. _this.USELIGHTMAPASSHADOWMAP = false;
  59581. _this.REFLECTIONMAP_3D = false;
  59582. _this.REFLECTIONMAP_SPHERICAL = false;
  59583. _this.REFLECTIONMAP_PLANAR = false;
  59584. _this.REFLECTIONMAP_CUBIC = false;
  59585. _this.REFLECTIONMAP_PROJECTION = false;
  59586. _this.REFLECTIONMAP_SKYBOX = false;
  59587. _this.REFLECTIONMAP_EXPLICIT = false;
  59588. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  59589. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  59590. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  59591. _this.INVERTCUBICMAP = false;
  59592. _this.LOGARITHMICDEPTH = false;
  59593. _this.CAMERATONEMAP = false;
  59594. _this.CAMERACONTRAST = false;
  59595. _this.CAMERACOLORGRADING = false;
  59596. _this.CAMERACOLORCURVES = false;
  59597. _this.OVERLOADEDVALUES = false;
  59598. _this.OVERLOADEDSHADOWVALUES = false;
  59599. _this.USESPHERICALFROMREFLECTIONMAP = false;
  59600. _this.REFRACTION = false;
  59601. _this.REFRACTIONMAP_3D = false;
  59602. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  59603. _this.REFRACTIONMAPINLINEARSPACE = false;
  59604. _this.LODBASEDMICROSFURACE = false;
  59605. _this.USEPHYSICALLIGHTFALLOFF = false;
  59606. _this.RADIANCEOVERALPHA = false;
  59607. _this.USEPMREMREFLECTION = false;
  59608. _this.USEPMREMREFRACTION = false;
  59609. _this.INVERTNORMALMAPX = false;
  59610. _this.INVERTNORMALMAPY = false;
  59611. _this.TWOSIDEDLIGHTING = false;
  59612. _this.SHADOWFULLFLOAT = false;
  59613. _this.METALLICWORKFLOW = false;
  59614. _this.METALLICMAP = false;
  59615. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  59616. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  59617. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  59618. _this.AOSTOREINMETALMAPRED = false;
  59619. _this.MICROSURFACEMAP = false;
  59620. _this.MORPHTARGETS = false;
  59621. _this.MORPHTARGETS_NORMAL = false;
  59622. _this.NUM_MORPH_INFLUENCERS = 0;
  59623. _this.rebuild();
  59624. return _this;
  59625. }
  59626. return PBRMaterialDefines;
  59627. }(BABYLON.MaterialDefines));
  59628. /**
  59629. * The Physically based material of BJS.
  59630. *
  59631. * This offers the main features of a standard PBR material.
  59632. * For more information, please refer to the documentation :
  59633. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  59634. */
  59635. var PBRMaterial = (function (_super) {
  59636. __extends(PBRMaterial, _super);
  59637. /**
  59638. * Instantiates a new PBRMaterial instance.
  59639. *
  59640. * @param name The material name
  59641. * @param scene The scene the material will be use in.
  59642. */
  59643. function PBRMaterial(name, scene) {
  59644. var _this = _super.call(this, name, scene) || this;
  59645. /**
  59646. * Intensity of the direct lights e.g. the four lights available in your scene.
  59647. * This impacts both the direct diffuse and specular highlights.
  59648. */
  59649. _this.directIntensity = 1.0;
  59650. /**
  59651. * Intensity of the emissive part of the material.
  59652. * This helps controlling the emissive effect without modifying the emissive color.
  59653. */
  59654. _this.emissiveIntensity = 1.0;
  59655. /**
  59656. * Intensity of the environment e.g. how much the environment will light the object
  59657. * either through harmonics for rough material or through the refelction for shiny ones.
  59658. */
  59659. _this.environmentIntensity = 1.0;
  59660. /**
  59661. * This is a special control allowing the reduction of the specular highlights coming from the
  59662. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  59663. */
  59664. _this.specularIntensity = 1.0;
  59665. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  59666. /**
  59667. * Debug Control allowing disabling the bump map on this material.
  59668. */
  59669. _this.disableBumpMap = false;
  59670. /**
  59671. * Debug Control helping enforcing or dropping the darkness of shadows.
  59672. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  59673. */
  59674. _this.overloadedShadowIntensity = 1.0;
  59675. /**
  59676. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  59677. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  59678. */
  59679. _this.overloadedShadeIntensity = 1.0;
  59680. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  59681. /**
  59682. * The camera exposure used on this material.
  59683. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  59684. * This corresponds to a photographic exposure.
  59685. */
  59686. _this.cameraExposure = 1.0;
  59687. /**
  59688. * The camera contrast used on this material.
  59689. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  59690. */
  59691. _this.cameraContrast = 1.0;
  59692. /**
  59693. * Color Grading 2D Lookup Texture.
  59694. * This allows special effects like sepia, black and white to sixties rendering style.
  59695. */
  59696. _this.cameraColorGradingTexture = null;
  59697. /**
  59698. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59699. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59700. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  59701. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59702. */
  59703. _this.cameraColorCurves = null;
  59704. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  59705. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  59706. /**
  59707. * Debug Control allowing to overload the ambient color.
  59708. * This as to be use with the overloadedAmbientIntensity parameter.
  59709. */
  59710. _this.overloadedAmbient = BABYLON.Color3.White();
  59711. /**
  59712. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  59713. */
  59714. _this.overloadedAmbientIntensity = 0.0;
  59715. /**
  59716. * Debug Control allowing to overload the albedo color.
  59717. * This as to be use with the overloadedAlbedoIntensity parameter.
  59718. */
  59719. _this.overloadedAlbedo = BABYLON.Color3.White();
  59720. /**
  59721. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  59722. */
  59723. _this.overloadedAlbedoIntensity = 0.0;
  59724. /**
  59725. * Debug Control allowing to overload the reflectivity color.
  59726. * This as to be use with the overloadedReflectivityIntensity parameter.
  59727. */
  59728. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  59729. /**
  59730. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  59731. */
  59732. _this.overloadedReflectivityIntensity = 0.0;
  59733. /**
  59734. * Debug Control allowing to overload the emissive color.
  59735. * This as to be use with the overloadedEmissiveIntensity parameter.
  59736. */
  59737. _this.overloadedEmissive = BABYLON.Color3.White();
  59738. /**
  59739. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  59740. */
  59741. _this.overloadedEmissiveIntensity = 0.0;
  59742. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  59743. /**
  59744. * Debug Control allowing to overload the reflection color.
  59745. * This as to be use with the overloadedReflectionIntensity parameter.
  59746. */
  59747. _this.overloadedReflection = BABYLON.Color3.White();
  59748. /**
  59749. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59750. */
  59751. _this.overloadedReflectionIntensity = 0.0;
  59752. /**
  59753. * Debug Control allowing to overload the microsurface.
  59754. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59755. */
  59756. _this.overloadedMicroSurface = 0.0;
  59757. /**
  59758. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59759. */
  59760. _this.overloadedMicroSurfaceIntensity = 0.0;
  59761. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  59762. /**
  59763. * AKA Occlusion Texture Intensity in other nomenclature.
  59764. */
  59765. _this.ambientTextureStrength = 1.0;
  59766. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59767. /**
  59768. * AKA Diffuse Color in other nomenclature.
  59769. */
  59770. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59771. /**
  59772. * AKA Specular Color in other nomenclature.
  59773. */
  59774. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59775. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  59776. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59777. /**
  59778. * AKA Glossiness in other nomenclature.
  59779. */
  59780. _this.microSurface = 0.9;
  59781. /**
  59782. * source material index of refraction (IOR)' / 'destination material IOR.
  59783. */
  59784. _this.indexOfRefraction = 0.66;
  59785. /**
  59786. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59787. */
  59788. _this.invertRefractionY = false;
  59789. /**
  59790. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59791. * Materials half opaque for instance using refraction could benefit from this control.
  59792. */
  59793. _this.linkRefractionWithTransparency = false;
  59794. /**
  59795. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59796. */
  59797. _this.linkEmissiveWithAlbedo = false;
  59798. _this.useLightmapAsShadowmap = false;
  59799. /**
  59800. * In this mode, the emissive informtaion will always be added to the lighting once.
  59801. * A light for instance can be thought as emissive.
  59802. */
  59803. _this.useEmissiveAsIllumination = false;
  59804. /**
  59805. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59806. */
  59807. _this.useAlphaFromAlbedoTexture = false;
  59808. /**
  59809. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59810. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59811. */
  59812. _this.useSpecularOverAlpha = true;
  59813. /**
  59814. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59815. */
  59816. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59817. /**
  59818. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  59819. */
  59820. _this.useRoughnessFromMetallicTextureAlpha = true;
  59821. /**
  59822. * Specifies if the metallic texture contains the roughness information in its green channel.
  59823. */
  59824. _this.useRoughnessFromMetallicTextureGreen = false;
  59825. /**
  59826. * Specifies if the metallic texture contains the metallness information in its blue channel.
  59827. */
  59828. _this.useMetallnessFromMetallicTextureBlue = false;
  59829. /**
  59830. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  59831. */
  59832. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  59833. /**
  59834. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  59835. */
  59836. _this.useAmbientInGrayScale = false;
  59837. /**
  59838. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59839. * The material will try to infer what glossiness each pixel should be.
  59840. */
  59841. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  59842. /**
  59843. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59844. * the creation of the material.
  59845. */
  59846. _this.useScalarInLinearSpace = false;
  59847. /**
  59848. * BJS is using an harcoded light falloff based on a manually sets up range.
  59849. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59850. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59851. */
  59852. _this.usePhysicalLightFalloff = true;
  59853. /**
  59854. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59855. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59856. */
  59857. _this.useRadianceOverAlpha = true;
  59858. /**
  59859. * Allows using the bump map in parallax mode.
  59860. */
  59861. _this.useParallax = false;
  59862. /**
  59863. * Allows using the bump map in parallax occlusion mode.
  59864. */
  59865. _this.useParallaxOcclusion = false;
  59866. /**
  59867. * Controls the scale bias of the parallax mode.
  59868. */
  59869. _this.parallaxScaleBias = 0.05;
  59870. /**
  59871. * If sets to true, disables all the lights affecting the material.
  59872. */
  59873. _this.disableLighting = false;
  59874. /**
  59875. * Number of Simultaneous lights allowed on the material.
  59876. */
  59877. _this.maxSimultaneousLights = 4;
  59878. /**
  59879. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59880. */
  59881. _this.invertNormalMapX = false;
  59882. /**
  59883. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59884. */
  59885. _this.invertNormalMapY = false;
  59886. /**
  59887. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  59888. */
  59889. _this.twoSidedLighting = false;
  59890. _this._renderTargets = new BABYLON.SmartArray(16);
  59891. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59892. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59893. _this._tempColor = new BABYLON.Color3();
  59894. _this._defines = new PBRMaterialDefines();
  59895. _this._cachedDefines = new PBRMaterialDefines();
  59896. _this._myScene = null;
  59897. _this._myShadowGenerator = null;
  59898. _this._cachedDefines.BonesPerMesh = -1;
  59899. _this.getRenderTargetTextures = function () {
  59900. _this._renderTargets.reset();
  59901. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59902. _this._renderTargets.push(_this.reflectionTexture);
  59903. }
  59904. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59905. _this._renderTargets.push(_this.refractionTexture);
  59906. }
  59907. return _this._renderTargets;
  59908. };
  59909. return _this;
  59910. }
  59911. PBRMaterial.prototype.getClassName = function () {
  59912. return "PBRMaterial";
  59913. };
  59914. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59915. get: function () {
  59916. return this._useLogarithmicDepth;
  59917. },
  59918. set: function (value) {
  59919. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59920. },
  59921. enumerable: true,
  59922. configurable: true
  59923. });
  59924. PBRMaterial.prototype.needAlphaBlending = function () {
  59925. if (this.linkRefractionWithTransparency) {
  59926. return false;
  59927. }
  59928. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59929. };
  59930. PBRMaterial.prototype.needAlphaTesting = function () {
  59931. if (this.linkRefractionWithTransparency) {
  59932. return false;
  59933. }
  59934. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59935. };
  59936. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59937. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59938. };
  59939. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59940. return this.albedoTexture;
  59941. };
  59942. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59943. if (!mesh) {
  59944. return true;
  59945. }
  59946. if (this._defines.INSTANCES !== useInstances) {
  59947. return false;
  59948. }
  59949. return false;
  59950. };
  59951. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59952. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59953. };
  59954. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59955. if (!useScalarInLinear) {
  59956. color.toLinearSpaceToRef(ref);
  59957. }
  59958. else {
  59959. ref.r = color.r;
  59960. ref.g = color.g;
  59961. ref.b = color.b;
  59962. }
  59963. };
  59964. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59965. var lightIndex = 0;
  59966. var depthValuesAlreadySet = false;
  59967. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  59968. var light = _a[_i];
  59969. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59970. // GAMMA CORRECTION.
  59971. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59972. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59973. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59974. if (defines["SPECULARTERM"]) {
  59975. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59976. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59977. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59978. }
  59979. // Shadows
  59980. if (scene.shadowsEnabled) {
  59981. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59982. }
  59983. lightIndex++;
  59984. if (lightIndex === maxSimultaneousLights)
  59985. break;
  59986. }
  59987. };
  59988. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59989. if (this.isFrozen) {
  59990. if (this._wasPreviouslyReady) {
  59991. return true;
  59992. }
  59993. }
  59994. var scene = this.getScene();
  59995. var engine = scene.getEngine();
  59996. var needUVs = false;
  59997. this._defines.reset();
  59998. if (scene.lightsEnabled && !this.disableLighting) {
  59999. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  60000. }
  60001. if (!this.checkReadyOnEveryCall) {
  60002. if (this._renderId === scene.getRenderId()) {
  60003. if (this._checkCache(scene, mesh, useInstances)) {
  60004. return true;
  60005. }
  60006. }
  60007. }
  60008. if (scene.texturesEnabled) {
  60009. if (scene.getEngine().getCaps().textureLOD) {
  60010. this._defines.LODBASEDMICROSFURACE = true;
  60011. }
  60012. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60013. if (!this.albedoTexture.isReady()) {
  60014. return false;
  60015. }
  60016. needUVs = true;
  60017. this._defines.ALBEDO = true;
  60018. }
  60019. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60020. if (!this.ambientTexture.isReady()) {
  60021. return false;
  60022. }
  60023. needUVs = true;
  60024. this._defines.AMBIENT = true;
  60025. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  60026. }
  60027. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60028. if (!this.opacityTexture.isReady()) {
  60029. return false;
  60030. }
  60031. needUVs = true;
  60032. this._defines.OPACITY = true;
  60033. if (this.opacityTexture.getAlphaFromRGB) {
  60034. this._defines.OPACITYRGB = true;
  60035. }
  60036. }
  60037. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60038. if (!this.reflectionTexture.isReady()) {
  60039. return false;
  60040. }
  60041. this._defines.REFLECTION = true;
  60042. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  60043. this._defines.INVERTCUBICMAP = true;
  60044. }
  60045. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  60046. switch (this.reflectionTexture.coordinatesMode) {
  60047. case BABYLON.Texture.CUBIC_MODE:
  60048. case BABYLON.Texture.INVCUBIC_MODE:
  60049. this._defines.REFLECTIONMAP_CUBIC = true;
  60050. break;
  60051. case BABYLON.Texture.EXPLICIT_MODE:
  60052. this._defines.REFLECTIONMAP_EXPLICIT = true;
  60053. break;
  60054. case BABYLON.Texture.PLANAR_MODE:
  60055. this._defines.REFLECTIONMAP_PLANAR = true;
  60056. break;
  60057. case BABYLON.Texture.PROJECTION_MODE:
  60058. this._defines.REFLECTIONMAP_PROJECTION = true;
  60059. break;
  60060. case BABYLON.Texture.SKYBOX_MODE:
  60061. this._defines.REFLECTIONMAP_SKYBOX = true;
  60062. break;
  60063. case BABYLON.Texture.SPHERICAL_MODE:
  60064. this._defines.REFLECTIONMAP_SPHERICAL = true;
  60065. break;
  60066. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  60067. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  60068. break;
  60069. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  60070. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  60071. break;
  60072. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  60073. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  60074. break;
  60075. }
  60076. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  60077. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  60078. if (this.reflectionTexture.isPMREM) {
  60079. this._defines.USEPMREMREFLECTION = true;
  60080. }
  60081. }
  60082. }
  60083. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60084. if (!this.lightmapTexture.isReady()) {
  60085. return false;
  60086. }
  60087. needUVs = true;
  60088. this._defines.LIGHTMAP = true;
  60089. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  60090. }
  60091. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60092. if (!this.emissiveTexture.isReady()) {
  60093. return false;
  60094. }
  60095. needUVs = true;
  60096. this._defines.EMISSIVE = true;
  60097. }
  60098. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60099. if (this.metallicTexture) {
  60100. if (!this.metallicTexture.isReady()) {
  60101. return false;
  60102. }
  60103. needUVs = true;
  60104. this._defines.METALLICWORKFLOW = true;
  60105. this._defines.METALLICMAP = true;
  60106. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  60107. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  60108. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  60109. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  60110. }
  60111. else if (this.reflectivityTexture) {
  60112. if (!this.reflectivityTexture.isReady()) {
  60113. return false;
  60114. }
  60115. needUVs = true;
  60116. this._defines.REFLECTIVITY = true;
  60117. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  60118. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  60119. }
  60120. if (this.microSurfaceTexture) {
  60121. if (!this.microSurfaceTexture.isReady()) {
  60122. return false;
  60123. }
  60124. needUVs = true;
  60125. this._defines.MICROSURFACEMAP = true;
  60126. }
  60127. }
  60128. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60129. if (!this.bumpTexture.isReady()) {
  60130. return false;
  60131. }
  60132. needUVs = true;
  60133. this._defines.BUMP = true;
  60134. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60135. this._defines.PARALLAX = true;
  60136. if (this.useParallaxOcclusion) {
  60137. this._defines.PARALLAXOCCLUSION = true;
  60138. }
  60139. }
  60140. if (this.invertNormalMapX) {
  60141. this._defines.INVERTNORMALMAPX = true;
  60142. }
  60143. if (this.invertNormalMapY) {
  60144. this._defines.INVERTNORMALMAPY = true;
  60145. }
  60146. if (scene._mirroredCameraPosition) {
  60147. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  60148. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  60149. }
  60150. }
  60151. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60152. if (!this.refractionTexture.isReady()) {
  60153. return false;
  60154. }
  60155. needUVs = true;
  60156. this._defines.REFRACTION = true;
  60157. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  60158. if (this.linkRefractionWithTransparency) {
  60159. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  60160. }
  60161. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  60162. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  60163. if (this.refractionTexture.isPMREM) {
  60164. this._defines.USEPMREMREFRACTION = true;
  60165. }
  60166. }
  60167. }
  60168. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60169. if (!this.cameraColorGradingTexture.isReady()) {
  60170. return false;
  60171. }
  60172. this._defines.CAMERACOLORGRADING = true;
  60173. }
  60174. if (!this.backFaceCulling && this.twoSidedLighting) {
  60175. this._defines.TWOSIDEDLIGHTING = true;
  60176. }
  60177. }
  60178. // Effect
  60179. if (scene.clipPlane) {
  60180. this._defines.CLIPPLANE = true;
  60181. }
  60182. if (engine.getAlphaTesting()) {
  60183. this._defines.ALPHATEST = true;
  60184. }
  60185. if (this._shouldUseAlphaFromAlbedoTexture()) {
  60186. this._defines.ALPHAFROMALBEDO = true;
  60187. }
  60188. if (this.useEmissiveAsIllumination) {
  60189. this._defines.EMISSIVEASILLUMINATION = true;
  60190. }
  60191. if (this.linkEmissiveWithAlbedo) {
  60192. this._defines.LINKEMISSIVEWITHALBEDO = true;
  60193. }
  60194. if (this.useLogarithmicDepth) {
  60195. this._defines.LOGARITHMICDEPTH = true;
  60196. }
  60197. if (this.cameraContrast != 1) {
  60198. this._defines.CAMERACONTRAST = true;
  60199. }
  60200. if (this.cameraExposure != 1) {
  60201. this._defines.CAMERATONEMAP = true;
  60202. }
  60203. if (this.cameraColorCurves) {
  60204. this._defines.CAMERACOLORCURVES = true;
  60205. }
  60206. if (this.overloadedShadeIntensity != 1 ||
  60207. this.overloadedShadowIntensity != 1) {
  60208. this._defines.OVERLOADEDSHADOWVALUES = true;
  60209. }
  60210. if (this.overloadedMicroSurfaceIntensity > 0 ||
  60211. this.overloadedEmissiveIntensity > 0 ||
  60212. this.overloadedReflectivityIntensity > 0 ||
  60213. this.overloadedAlbedoIntensity > 0 ||
  60214. this.overloadedAmbientIntensity > 0 ||
  60215. this.overloadedReflectionIntensity > 0) {
  60216. this._defines.OVERLOADEDVALUES = true;
  60217. }
  60218. // Point size
  60219. if (this.pointsCloud || scene.forcePointsCloud) {
  60220. this._defines.POINTSIZE = true;
  60221. }
  60222. // Fog
  60223. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  60224. this._defines.FOG = true;
  60225. }
  60226. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60227. // Fresnel
  60228. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  60229. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60230. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60231. this._defines.OPACITYFRESNEL = true;
  60232. }
  60233. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60234. this._defines.EMISSIVEFRESNEL = true;
  60235. }
  60236. this._defines.FRESNEL = true;
  60237. }
  60238. }
  60239. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  60240. this._defines.SPECULAROVERALPHA = true;
  60241. }
  60242. if (this.usePhysicalLightFalloff) {
  60243. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  60244. }
  60245. if (this.useRadianceOverAlpha) {
  60246. this._defines.RADIANCEOVERALPHA = true;
  60247. }
  60248. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  60249. this._defines.METALLICWORKFLOW = true;
  60250. }
  60251. // Attribs
  60252. if (mesh) {
  60253. if (!mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60254. mesh.createNormals(true);
  60255. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  60256. }
  60257. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60258. this._defines.NORMAL = true;
  60259. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  60260. this._defines.TANGENT = true;
  60261. }
  60262. }
  60263. if (needUVs) {
  60264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60265. this._defines.UV1 = true;
  60266. }
  60267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60268. this._defines.UV2 = true;
  60269. }
  60270. }
  60271. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60272. this._defines.VERTEXCOLOR = true;
  60273. if (mesh.hasVertexAlpha) {
  60274. this._defines.VERTEXALPHA = true;
  60275. }
  60276. }
  60277. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60278. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  60279. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  60280. }
  60281. // Instances
  60282. if (useInstances) {
  60283. this._defines.INSTANCES = true;
  60284. }
  60285. if (mesh.morphTargetManager) {
  60286. var manager = mesh.morphTargetManager;
  60287. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  60288. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  60289. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  60290. }
  60291. }
  60292. // Get correct effect
  60293. if (!this._defines.isEqual(this._cachedDefines)) {
  60294. this._defines.cloneTo(this._cachedDefines);
  60295. scene.resetCachedMaterial();
  60296. // Fallbacks
  60297. var fallbacks = new BABYLON.EffectFallbacks();
  60298. if (this._defines.REFLECTION) {
  60299. fallbacks.addFallback(0, "REFLECTION");
  60300. }
  60301. if (this._defines.REFRACTION) {
  60302. fallbacks.addFallback(0, "REFRACTION");
  60303. }
  60304. if (this._defines.REFLECTIVITY) {
  60305. fallbacks.addFallback(0, "REFLECTIVITY");
  60306. }
  60307. if (this._defines.BUMP) {
  60308. fallbacks.addFallback(0, "BUMP");
  60309. }
  60310. if (this._defines.PARALLAX) {
  60311. fallbacks.addFallback(1, "PARALLAX");
  60312. }
  60313. if (this._defines.PARALLAXOCCLUSION) {
  60314. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  60315. }
  60316. if (this._defines.SPECULAROVERALPHA) {
  60317. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  60318. }
  60319. if (this._defines.FOG) {
  60320. fallbacks.addFallback(1, "FOG");
  60321. }
  60322. if (this._defines.POINTSIZE) {
  60323. fallbacks.addFallback(0, "POINTSIZE");
  60324. }
  60325. if (this._defines.LOGARITHMICDEPTH) {
  60326. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  60327. }
  60328. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  60329. if (this._defines.SPECULARTERM) {
  60330. fallbacks.addFallback(0, "SPECULARTERM");
  60331. }
  60332. if (this._defines.OPACITYFRESNEL) {
  60333. fallbacks.addFallback(1, "OPACITYFRESNEL");
  60334. }
  60335. if (this._defines.EMISSIVEFRESNEL) {
  60336. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  60337. }
  60338. if (this._defines.FRESNEL) {
  60339. fallbacks.addFallback(3, "FRESNEL");
  60340. }
  60341. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  60342. fallbacks.addCPUSkinningFallback(0, mesh);
  60343. }
  60344. //Attributes
  60345. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60346. if (this._defines.NORMAL) {
  60347. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60348. }
  60349. if (this._defines.TANGENT) {
  60350. attribs.push(BABYLON.VertexBuffer.TangentKind);
  60351. }
  60352. if (this._defines.UV1) {
  60353. attribs.push(BABYLON.VertexBuffer.UVKind);
  60354. }
  60355. if (this._defines.UV2) {
  60356. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60357. }
  60358. if (this._defines.VERTEXCOLOR) {
  60359. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60360. }
  60361. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  60362. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  60363. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  60364. // Legacy browser patch
  60365. var join = this._defines.toString();
  60366. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  60367. "vFogInfos", "vFogColor", "pointSize",
  60368. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  60369. "mBones",
  60370. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  60371. "depthValues",
  60372. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  60373. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  60374. "logarithmicDepthConstant",
  60375. "vSphericalX", "vSphericalY", "vSphericalZ",
  60376. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  60377. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  60378. "vMicrosurfaceTextureLods",
  60379. "vCameraInfos"
  60380. ];
  60381. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  60382. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  60383. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  60384. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  60385. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS });
  60386. }
  60387. if (!this._effect.isReady()) {
  60388. return false;
  60389. }
  60390. this._renderId = scene.getRenderId();
  60391. this._wasPreviouslyReady = true;
  60392. return true;
  60393. };
  60394. PBRMaterial.prototype.unbind = function () {
  60395. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  60396. this._effect.setTexture("reflection2DSampler", null);
  60397. }
  60398. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  60399. this._effect.setTexture("refraction2DSampler", null);
  60400. }
  60401. _super.prototype.unbind.call(this);
  60402. };
  60403. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60404. this._effect.setMatrix("world", world);
  60405. };
  60406. PBRMaterial.prototype.bind = function (world, mesh) {
  60407. this._myScene = this.getScene();
  60408. // Matrices
  60409. this.bindOnlyWorldMatrix(world);
  60410. // Bones
  60411. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60412. if (this._myScene.getCachedMaterial() !== this) {
  60413. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  60414. if (BABYLON.StandardMaterial.FresnelEnabled) {
  60415. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  60416. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  60417. }
  60418. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  60419. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  60420. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  60421. }
  60422. }
  60423. // Textures
  60424. if (this._myScene.texturesEnabled) {
  60425. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60426. this._effect.setTexture("albedoSampler", this.albedoTexture);
  60427. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  60428. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  60429. }
  60430. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60431. this._effect.setTexture("ambientSampler", this.ambientTexture);
  60432. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  60433. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  60434. }
  60435. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  60436. this._effect.setTexture("opacitySampler", this.opacityTexture);
  60437. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  60438. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  60439. }
  60440. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  60441. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  60442. if (this.reflectionTexture.isCube) {
  60443. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  60444. }
  60445. else {
  60446. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  60447. }
  60448. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  60449. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  60450. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  60451. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  60452. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  60453. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  60454. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  60455. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  60456. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  60457. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  60458. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  60459. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  60460. }
  60461. }
  60462. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  60463. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  60464. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  60465. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  60466. }
  60467. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  60468. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  60469. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  60470. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  60471. }
  60472. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  60473. if (this.metallicTexture) {
  60474. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  60475. this._effect.setFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  60476. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  60477. }
  60478. else if (this.reflectivityTexture) {
  60479. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  60480. this._effect.setFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  60481. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  60482. }
  60483. if (this.microSurfaceTexture) {
  60484. this._effect.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  60485. this._effect.setFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  60486. this._effect.setMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  60487. }
  60488. }
  60489. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  60490. this._effect.setTexture("bumpSampler", this.bumpTexture);
  60491. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  60492. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  60493. }
  60494. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  60495. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  60496. var depth = 1.0;
  60497. if (this.refractionTexture.isCube) {
  60498. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  60499. }
  60500. else {
  60501. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  60502. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  60503. if (this.refractionTexture.depth) {
  60504. depth = this.refractionTexture.depth;
  60505. }
  60506. }
  60507. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  60508. }
  60509. if ((this.reflectionTexture || this.refractionTexture)) {
  60510. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  60511. }
  60512. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  60513. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  60514. }
  60515. }
  60516. // Clip plane
  60517. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  60518. // Point size
  60519. if (this.pointsCloud) {
  60520. this._effect.setFloat("pointSize", this.pointSize);
  60521. }
  60522. // Colors
  60523. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  60524. if (this._defines.METALLICWORKFLOW) {
  60525. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  60526. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  60527. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  60528. }
  60529. else {
  60530. // GAMMA CORRECTION.
  60531. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  60532. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  60533. }
  60534. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  60535. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  60536. // GAMMA CORRECTION.
  60537. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  60538. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  60539. // GAMMA CORRECTION.
  60540. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  60541. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  60542. }
  60543. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  60544. // GAMMA CORRECTION.
  60545. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  60546. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  60547. // Lights
  60548. if (this._myScene.lightsEnabled && !this.disableLighting) {
  60549. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  60550. }
  60551. // View
  60552. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  60553. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  60554. }
  60555. // Fog
  60556. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  60557. // Morph targets
  60558. if (this._defines.NUM_MORPH_INFLUENCERS) {
  60559. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  60560. }
  60561. this._lightingInfos.x = this.directIntensity;
  60562. this._lightingInfos.y = this.emissiveIntensity;
  60563. this._lightingInfos.z = this.environmentIntensity;
  60564. this._lightingInfos.w = this.specularIntensity;
  60565. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  60566. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  60567. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  60568. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  60569. this._cameraInfos.x = this.cameraExposure;
  60570. this._cameraInfos.y = this.cameraContrast;
  60571. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  60572. if (this.cameraColorCurves) {
  60573. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  60574. }
  60575. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  60576. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  60577. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  60578. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  60579. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  60580. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  60581. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  60582. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  60583. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  60584. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  60585. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  60586. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  60587. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  60588. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  60589. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  60590. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  60591. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  60592. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  60593. // Log. depth
  60594. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  60595. }
  60596. this._afterBind(mesh);
  60597. this._myScene = null;
  60598. };
  60599. PBRMaterial.prototype.getAnimatables = function () {
  60600. var results = [];
  60601. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  60602. results.push(this.albedoTexture);
  60603. }
  60604. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  60605. results.push(this.ambientTexture);
  60606. }
  60607. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  60608. results.push(this.opacityTexture);
  60609. }
  60610. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  60611. results.push(this.reflectionTexture);
  60612. }
  60613. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  60614. results.push(this.emissiveTexture);
  60615. }
  60616. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  60617. results.push(this.metallicTexture);
  60618. }
  60619. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  60620. results.push(this.reflectivityTexture);
  60621. }
  60622. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  60623. results.push(this.bumpTexture);
  60624. }
  60625. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  60626. results.push(this.lightmapTexture);
  60627. }
  60628. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  60629. results.push(this.refractionTexture);
  60630. }
  60631. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  60632. results.push(this.cameraColorGradingTexture);
  60633. }
  60634. return results;
  60635. };
  60636. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60637. if (forceDisposeTextures) {
  60638. if (this.albedoTexture) {
  60639. this.albedoTexture.dispose();
  60640. }
  60641. if (this.ambientTexture) {
  60642. this.ambientTexture.dispose();
  60643. }
  60644. if (this.opacityTexture) {
  60645. this.opacityTexture.dispose();
  60646. }
  60647. if (this.reflectionTexture) {
  60648. this.reflectionTexture.dispose();
  60649. }
  60650. if (this.emissiveTexture) {
  60651. this.emissiveTexture.dispose();
  60652. }
  60653. if (this.metallicTexture) {
  60654. this.metallicTexture.dispose();
  60655. }
  60656. if (this.reflectivityTexture) {
  60657. this.reflectivityTexture.dispose();
  60658. }
  60659. if (this.bumpTexture) {
  60660. this.bumpTexture.dispose();
  60661. }
  60662. if (this.lightmapTexture) {
  60663. this.lightmapTexture.dispose();
  60664. }
  60665. if (this.refractionTexture) {
  60666. this.refractionTexture.dispose();
  60667. }
  60668. if (this.cameraColorGradingTexture) {
  60669. this.cameraColorGradingTexture.dispose();
  60670. }
  60671. }
  60672. this._renderTargets.dispose();
  60673. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60674. };
  60675. PBRMaterial.prototype.clone = function (name) {
  60676. var _this = this;
  60677. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  60678. };
  60679. PBRMaterial.prototype.serialize = function () {
  60680. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60681. serializationObject.customType = "BABYLON.PBRMaterial";
  60682. return serializationObject;
  60683. };
  60684. // Statics
  60685. PBRMaterial.Parse = function (source, scene, rootUrl) {
  60686. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  60687. };
  60688. return PBRMaterial;
  60689. }(BABYLON.Material));
  60690. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  60691. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  60692. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  60693. PBRMaterial._scaledReflection = new BABYLON.Color3();
  60694. __decorate([
  60695. BABYLON.serialize()
  60696. ], PBRMaterial.prototype, "directIntensity", void 0);
  60697. __decorate([
  60698. BABYLON.serialize()
  60699. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  60700. __decorate([
  60701. BABYLON.serialize()
  60702. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  60703. __decorate([
  60704. BABYLON.serialize()
  60705. ], PBRMaterial.prototype, "specularIntensity", void 0);
  60706. __decorate([
  60707. BABYLON.serialize()
  60708. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  60709. __decorate([
  60710. BABYLON.serialize()
  60711. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  60712. __decorate([
  60713. BABYLON.serialize()
  60714. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  60715. __decorate([
  60716. BABYLON.serialize()
  60717. ], PBRMaterial.prototype, "cameraExposure", void 0);
  60718. __decorate([
  60719. BABYLON.serialize()
  60720. ], PBRMaterial.prototype, "cameraContrast", void 0);
  60721. __decorate([
  60722. BABYLON.serializeAsTexture()
  60723. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  60724. __decorate([
  60725. BABYLON.serializeAsColorCurves()
  60726. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  60727. __decorate([
  60728. BABYLON.serializeAsColor3()
  60729. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  60730. __decorate([
  60731. BABYLON.serialize()
  60732. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  60733. __decorate([
  60734. BABYLON.serializeAsColor3()
  60735. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  60736. __decorate([
  60737. BABYLON.serialize()
  60738. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  60739. __decorate([
  60740. BABYLON.serializeAsColor3()
  60741. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  60742. __decorate([
  60743. BABYLON.serialize()
  60744. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  60745. __decorate([
  60746. BABYLON.serializeAsColor3()
  60747. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  60748. __decorate([
  60749. BABYLON.serialize()
  60750. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  60751. __decorate([
  60752. BABYLON.serializeAsColor3()
  60753. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  60754. __decorate([
  60755. BABYLON.serialize()
  60756. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  60757. __decorate([
  60758. BABYLON.serialize()
  60759. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  60760. __decorate([
  60761. BABYLON.serialize()
  60762. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  60763. __decorate([
  60764. BABYLON.serializeAsTexture()
  60765. ], PBRMaterial.prototype, "albedoTexture", void 0);
  60766. __decorate([
  60767. BABYLON.serializeAsTexture()
  60768. ], PBRMaterial.prototype, "ambientTexture", void 0);
  60769. __decorate([
  60770. BABYLON.serialize()
  60771. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  60772. __decorate([
  60773. BABYLON.serializeAsTexture()
  60774. ], PBRMaterial.prototype, "opacityTexture", void 0);
  60775. __decorate([
  60776. BABYLON.serializeAsTexture()
  60777. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  60778. __decorate([
  60779. BABYLON.serializeAsTexture()
  60780. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  60781. __decorate([
  60782. BABYLON.serializeAsTexture()
  60783. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  60784. __decorate([
  60785. BABYLON.serializeAsTexture()
  60786. ], PBRMaterial.prototype, "metallicTexture", void 0);
  60787. __decorate([
  60788. BABYLON.serialize()
  60789. ], PBRMaterial.prototype, "metallic", void 0);
  60790. __decorate([
  60791. BABYLON.serialize()
  60792. ], PBRMaterial.prototype, "roughness", void 0);
  60793. __decorate([
  60794. BABYLON.serializeAsTexture()
  60795. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  60796. __decorate([
  60797. BABYLON.serializeAsTexture()
  60798. ], PBRMaterial.prototype, "bumpTexture", void 0);
  60799. __decorate([
  60800. BABYLON.serializeAsTexture()
  60801. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  60802. __decorate([
  60803. BABYLON.serializeAsTexture()
  60804. ], PBRMaterial.prototype, "refractionTexture", void 0);
  60805. __decorate([
  60806. BABYLON.serializeAsColor3("ambient")
  60807. ], PBRMaterial.prototype, "ambientColor", void 0);
  60808. __decorate([
  60809. BABYLON.serializeAsColor3("albedo")
  60810. ], PBRMaterial.prototype, "albedoColor", void 0);
  60811. __decorate([
  60812. BABYLON.serializeAsColor3("reflectivity")
  60813. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  60814. __decorate([
  60815. BABYLON.serializeAsColor3("reflection")
  60816. ], PBRMaterial.prototype, "reflectionColor", void 0);
  60817. __decorate([
  60818. BABYLON.serializeAsColor3("emissive")
  60819. ], PBRMaterial.prototype, "emissiveColor", void 0);
  60820. __decorate([
  60821. BABYLON.serialize()
  60822. ], PBRMaterial.prototype, "microSurface", void 0);
  60823. __decorate([
  60824. BABYLON.serialize()
  60825. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  60826. __decorate([
  60827. BABYLON.serialize()
  60828. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  60829. __decorate([
  60830. BABYLON.serializeAsFresnelParameters()
  60831. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60832. __decorate([
  60833. BABYLON.serializeAsFresnelParameters()
  60834. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60835. __decorate([
  60836. BABYLON.serialize()
  60837. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60838. __decorate([
  60839. BABYLON.serialize()
  60840. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60841. __decorate([
  60842. BABYLON.serialize()
  60843. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60844. __decorate([
  60845. BABYLON.serialize()
  60846. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60847. __decorate([
  60848. BABYLON.serialize()
  60849. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60850. __decorate([
  60851. BABYLON.serialize()
  60852. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60853. __decorate([
  60854. BABYLON.serialize()
  60855. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60856. __decorate([
  60857. BABYLON.serialize()
  60858. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  60859. __decorate([
  60860. BABYLON.serialize()
  60861. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  60862. __decorate([
  60863. BABYLON.serialize()
  60864. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  60865. __decorate([
  60866. BABYLON.serialize()
  60867. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  60868. __decorate([
  60869. BABYLON.serialize()
  60870. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  60871. __decorate([
  60872. BABYLON.serialize()
  60873. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60874. __decorate([
  60875. BABYLON.serialize()
  60876. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60877. __decorate([
  60878. BABYLON.serialize()
  60879. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60880. __decorate([
  60881. BABYLON.serialize()
  60882. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60883. __decorate([
  60884. BABYLON.serialize()
  60885. ], PBRMaterial.prototype, "useParallax", void 0);
  60886. __decorate([
  60887. BABYLON.serialize()
  60888. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60889. __decorate([
  60890. BABYLON.serialize()
  60891. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60892. __decorate([
  60893. BABYLON.serialize()
  60894. ], PBRMaterial.prototype, "disableLighting", void 0);
  60895. __decorate([
  60896. BABYLON.serialize()
  60897. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60898. __decorate([
  60899. BABYLON.serialize()
  60900. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60901. __decorate([
  60902. BABYLON.serialize()
  60903. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60904. __decorate([
  60905. BABYLON.serialize()
  60906. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  60907. __decorate([
  60908. BABYLON.serialize()
  60909. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60910. BABYLON.PBRMaterial = PBRMaterial;
  60911. })(BABYLON || (BABYLON = {}));
  60912. //# sourceMappingURL=babylon.pbrMaterial.js.map
  60913. var BABYLON;
  60914. (function (BABYLON) {
  60915. var DebugLayer = (function () {
  60916. function DebugLayer(scene) {
  60917. this._scene = scene;
  60918. }
  60919. /** Creates the inspector window. */
  60920. DebugLayer.prototype._createInspector = function (config) {
  60921. if (config === void 0) { config = {}; }
  60922. var popup = config.popup || false;
  60923. var initialTab = config.initialTab || 0;
  60924. var parentElement = config.parentElement || null;
  60925. if (!this._inspector) {
  60926. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60927. } // else nothing to do,; instance is already existing
  60928. };
  60929. DebugLayer.prototype.isVisible = function () {
  60930. if (!this._inspector) {
  60931. return false;
  60932. }
  60933. return true;
  60934. };
  60935. DebugLayer.prototype.hide = function () {
  60936. if (this._inspector) {
  60937. try {
  60938. this._inspector.dispose();
  60939. }
  60940. catch (e) {
  60941. // If the inspector has been removed directly from the inspector tool
  60942. }
  60943. this._inspector = null;
  60944. }
  60945. };
  60946. DebugLayer.prototype.show = function (config) {
  60947. if (config === void 0) { config = {}; }
  60948. if (typeof INSPECTOR == 'undefined') {
  60949. // Load inspector and add it to the DOM
  60950. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60951. }
  60952. else {
  60953. // Otherwise creates the inspector
  60954. this._createInspector(config);
  60955. }
  60956. };
  60957. return DebugLayer;
  60958. }());
  60959. // Get protocol used - http or https
  60960. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  60961. BABYLON.DebugLayer = DebugLayer;
  60962. })(BABYLON || (BABYLON = {}));
  60963. //# sourceMappingURL=babylon.debugLayer.js.map
  60964. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  60965. var BABYLON;
  60966. (function (BABYLON) {
  60967. var StandardRenderingPipeline = (function (_super) {
  60968. __extends(StandardRenderingPipeline, _super);
  60969. /**
  60970. * @constructor
  60971. * @param {string} name - The rendering pipeline name
  60972. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60973. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  60974. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60975. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60976. */
  60977. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60978. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60979. var _this = _super.call(this, scene.getEngine(), name) || this;
  60980. _this.downSampleX4PostProcess = null;
  60981. _this.brightPassPostProcess = null;
  60982. _this.gaussianBlurHPostProcesses = [];
  60983. _this.gaussianBlurVPostProcesses = [];
  60984. _this.textureAdderPostProcess = null;
  60985. _this.textureAdderFinalPostProcess = null;
  60986. _this.lensFlareFinalPostProcess = null;
  60987. _this.lensFlarePostProcess = null;
  60988. _this.lensFlareComposePostProcess = null;
  60989. _this.depthOfFieldPostProcess = null;
  60990. // Values
  60991. _this.brightThreshold = 1.0;
  60992. _this.blurWidth = 2.0;
  60993. _this.horizontalBlur = false;
  60994. _this.gaussianCoefficient = 0.25;
  60995. _this.gaussianMean = 1.0;
  60996. _this.gaussianStandardDeviation = 1.0;
  60997. _this.exposure = 1.0;
  60998. _this.lensTexture = null;
  60999. _this.lensColorTexture = null;
  61000. _this.lensFlareStrength = 20.0;
  61001. _this.lensFlareGhostDispersal = 1.4;
  61002. _this.lensFlareHaloWidth = 0.7;
  61003. _this.lensFlareDistortionStrength = 16.0;
  61004. _this.lensStarTexture = null;
  61005. _this.lensFlareDirtTexture = null;
  61006. _this.depthOfFieldDistance = 10.0;
  61007. _this.depthOfFieldBlurWidth = 2.0;
  61008. // IAnimatable
  61009. _this.animations = [];
  61010. _this._depthRenderer = null;
  61011. _this._currentDepthOfFieldSource = null;
  61012. // Getters and setters
  61013. _this._depthOfFieldEnabled = true;
  61014. _this._lensFlareEnabled = true;
  61015. _this._cameras = cameras || [];
  61016. // Initialize
  61017. _this._scene = scene;
  61018. // Create pass post-processe
  61019. if (!originalPostProcess) {
  61020. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  61021. }
  61022. else {
  61023. _this.originalPostProcess = originalPostProcess;
  61024. }
  61025. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  61026. // Create down sample X4 post-process
  61027. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  61028. // Create bright pass post-process
  61029. _this._createBrightPassPostProcess(scene, ratio / 2);
  61030. // Create gaussian blur post-processes (down sampling blurs)
  61031. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  61032. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  61033. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  61034. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  61035. // Create texture adder post-process
  61036. _this._createTextureAdderPostProcess(scene, ratio);
  61037. // Create depth-of-field source post-process
  61038. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61039. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  61040. // Create lens flare post-process
  61041. _this._createLensFlarePostProcess(scene, ratio);
  61042. // Create depth-of-field source post-process post lens-flare and disable it now
  61043. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  61045. // Create gaussian blur used by depth-of-field
  61046. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  61047. // Create depth-of-field post-process
  61048. _this._createDepthOfFieldPostProcess(scene, ratio);
  61049. // Finish
  61050. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61051. if (cameras !== null) {
  61052. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61053. }
  61054. // Deactivate
  61055. _this.LensFlareEnabled = false;
  61056. _this.DepthOfFieldEnabled = false;
  61057. return _this;
  61058. }
  61059. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  61060. get: function () {
  61061. return this._depthOfFieldEnabled;
  61062. },
  61063. set: function (enabled) {
  61064. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  61065. if (enabled && !this._depthOfFieldEnabled) {
  61066. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  61067. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  61068. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  61069. this._depthRenderer = this._scene.enableDepthRenderer();
  61070. }
  61071. else if (!enabled && this._depthOfFieldEnabled) {
  61072. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  61073. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  61074. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  61075. }
  61076. this._depthOfFieldEnabled = enabled;
  61077. },
  61078. enumerable: true,
  61079. configurable: true
  61080. });
  61081. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  61082. get: function () {
  61083. return this._lensFlareEnabled;
  61084. },
  61085. set: function (enabled) {
  61086. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  61087. if (enabled && !this._lensFlareEnabled) {
  61088. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  61089. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  61090. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  61091. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  61092. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  61093. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  61094. }
  61095. else if (!enabled && this._lensFlareEnabled) {
  61096. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  61097. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  61098. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  61099. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  61100. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  61101. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  61102. }
  61103. this._lensFlareEnabled = enabled;
  61104. },
  61105. enumerable: true,
  61106. configurable: true
  61107. });
  61108. // Sets depth-of-field save post-process
  61109. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  61110. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._cameras);
  61111. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._cameras);
  61112. switch (name) {
  61113. case "HDRBaseDepthOfFieldSource":
  61114. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  61115. break;
  61116. case "HDRPostLensFlareDepthOfFieldSource":
  61117. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  61118. break;
  61119. default: break;
  61120. }
  61121. };
  61122. // Down Sample X4 Post-Processs
  61123. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  61124. var _this = this;
  61125. var downSampleX4Offsets = new Array(32);
  61126. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61127. this.downSampleX4PostProcess.onApply = function (effect) {
  61128. var id = 0;
  61129. for (var i = -2; i < 2; i++) {
  61130. for (var j = -2; j < 2; j++) {
  61131. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  61132. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  61133. id += 2;
  61134. }
  61135. }
  61136. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61137. };
  61138. // Add to pipeline
  61139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61140. };
  61141. // Brightpass Post-Process
  61142. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61143. var _this = this;
  61144. var brightOffsets = new Array(8);
  61145. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61146. this.brightPassPostProcess.onApply = function (effect) {
  61147. var sU = (1.0 / _this.brightPassPostProcess.width);
  61148. var sV = (1.0 / _this.brightPassPostProcess.height);
  61149. brightOffsets[0] = -0.5 * sU;
  61150. brightOffsets[1] = 0.5 * sV;
  61151. brightOffsets[2] = 0.5 * sU;
  61152. brightOffsets[3] = 0.5 * sV;
  61153. brightOffsets[4] = -0.5 * sU;
  61154. brightOffsets[5] = -0.5 * sV;
  61155. brightOffsets[6] = 0.5 * sU;
  61156. brightOffsets[7] = -0.5 * sV;
  61157. effect.setArray2("dsOffsets", brightOffsets);
  61158. effect.setFloat("brightThreshold", _this.brightThreshold);
  61159. };
  61160. // Add to pipeline
  61161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61162. };
  61163. // Create gaussian blur H&V post-processes
  61164. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61165. var _this = this;
  61166. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61167. var blurOffsets = new Array(9);
  61168. var blurWeights = new Array(9);
  61169. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  61170. var callback = function (height) {
  61171. return function (effect) {
  61172. // Weights
  61173. var x = 0.0;
  61174. for (var i = 0; i < 9; i++) {
  61175. x = (i - 4.0) / 4.0;
  61176. blurWeights[i] =
  61177. _this.gaussianCoefficient
  61178. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  61179. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  61180. }
  61181. var lastOutputDimensions = {
  61182. width: scene.getEngine().getRenderWidth(),
  61183. height: scene.getEngine().getRenderHeight()
  61184. };
  61185. for (var i = 0; i < 9; i++) {
  61186. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  61187. blurOffsets[i] = value;
  61188. }
  61189. effect.setArray("blurOffsets", blurOffsets);
  61190. effect.setArray("blurWeights", blurWeights);
  61191. if (height) {
  61192. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  61193. }
  61194. else {
  61195. effect.setFloat("blurWidth", _this[blurWidthKey]);
  61196. }
  61197. };
  61198. };
  61199. // Create horizontal gaussian blur post-processes
  61200. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61201. gaussianBlurHPostProcess.onApply = callback(false);
  61202. // Create vertical gaussian blur post-process
  61203. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61204. gaussianBlurVPostProcess.onApply = callback(true);
  61205. // Add to pipeline
  61206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  61207. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  61208. // Finish
  61209. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  61210. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  61211. };
  61212. // Create texture adder post-process
  61213. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61214. var _this = this;
  61215. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61216. this.textureAdderPostProcess.onApply = function (effect) {
  61217. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  61218. effect.setTexture("lensSampler", _this.lensTexture);
  61219. effect.setFloat("exposure", _this.exposure);
  61220. };
  61221. // Add to pipeline
  61222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61223. };
  61224. // Create lens flare post-process
  61225. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61226. var _this = this;
  61227. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61229. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  61230. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61232. var resolution = new BABYLON.Vector2(0, 0);
  61233. // Lens flare
  61234. this.lensFlarePostProcess.onApply = function (effect) {
  61235. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  61236. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61237. effect.setFloat("strength", _this.lensFlareStrength);
  61238. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61239. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61240. // Shift
  61241. resolution.x = _this.lensFlarePostProcess.width;
  61242. resolution.y = _this.lensFlarePostProcess.height;
  61243. effect.setVector2("resolution", resolution);
  61244. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61245. };
  61246. // Compose
  61247. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  61248. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  61249. this.lensFlareComposePostProcess.onApply = function (effect) {
  61250. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  61251. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61252. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61253. // Lens start rotation matrix
  61254. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61255. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61256. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  61257. camRot *= 4.0;
  61258. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  61259. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61260. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61261. };
  61262. };
  61263. // Create depth-of-field post-process
  61264. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61265. var _this = this;
  61266. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61267. this.depthOfFieldPostProcess.onApply = function (effect) {
  61268. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61269. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  61270. effect.setFloat("distance", _this.depthOfFieldDistance);
  61271. };
  61272. // Add to pipeline
  61273. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61274. };
  61275. // Dispose
  61276. StandardRenderingPipeline.prototype.dispose = function () {
  61277. for (var i = 0; i < this._cameras.length; i++) {
  61278. var camera = this._cameras[i];
  61279. this.originalPostProcess.dispose(camera);
  61280. this.downSampleX4PostProcess.dispose(camera);
  61281. this.brightPassPostProcess.dispose(camera);
  61282. this.textureAdderPostProcess.dispose(camera);
  61283. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  61284. this.gaussianBlurHPostProcesses[j].dispose(camera);
  61285. }
  61286. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  61287. this.gaussianBlurVPostProcesses[j].dispose(camera);
  61288. }
  61289. this.textureAdderFinalPostProcess.dispose(camera);
  61290. this.lensFlarePostProcess.dispose(camera);
  61291. this.lensFlareComposePostProcess.dispose(camera);
  61292. this.depthOfFieldPostProcess.dispose(camera);
  61293. }
  61294. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61295. _super.prototype.dispose.call(this);
  61296. };
  61297. // Serialize rendering pipeline
  61298. StandardRenderingPipeline.prototype.serialize = function () {
  61299. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61300. serializationObject.customType = "StandardRenderingPipeline";
  61301. return serializationObject;
  61302. };
  61303. // Parse serialized pipeline
  61304. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61305. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61306. };
  61307. return StandardRenderingPipeline;
  61308. }(BABYLON.PostProcessRenderPipeline));
  61309. __decorate([
  61310. BABYLON.serialize()
  61311. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61312. __decorate([
  61313. BABYLON.serialize()
  61314. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61315. __decorate([
  61316. BABYLON.serialize()
  61317. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61318. __decorate([
  61319. BABYLON.serialize()
  61320. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  61321. __decorate([
  61322. BABYLON.serialize()
  61323. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  61324. __decorate([
  61325. BABYLON.serialize()
  61326. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  61327. __decorate([
  61328. BABYLON.serialize()
  61329. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61330. __decorate([
  61331. BABYLON.serializeAsTexture("lensTexture")
  61332. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61333. __decorate([
  61334. BABYLON.serializeAsTexture("lensColorTexture")
  61335. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61336. __decorate([
  61337. BABYLON.serialize()
  61338. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61339. __decorate([
  61340. BABYLON.serialize()
  61341. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61342. __decorate([
  61343. BABYLON.serialize()
  61344. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61345. __decorate([
  61346. BABYLON.serialize()
  61347. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61348. __decorate([
  61349. BABYLON.serializeAsTexture("lensStarTexture")
  61350. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61351. __decorate([
  61352. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61353. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61354. __decorate([
  61355. BABYLON.serialize()
  61356. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61357. __decorate([
  61358. BABYLON.serialize()
  61359. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61360. __decorate([
  61361. BABYLON.serialize()
  61362. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61363. __decorate([
  61364. BABYLON.serialize()
  61365. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61366. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61367. })(BABYLON || (BABYLON = {}));
  61368. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61369. var BABYLON;
  61370. (function (BABYLON) {
  61371. var MorphTarget = (function () {
  61372. function MorphTarget(name, influence) {
  61373. if (influence === void 0) { influence = 0; }
  61374. this.name = name;
  61375. this.onInfluenceChanged = new BABYLON.Observable();
  61376. this.influence = influence;
  61377. }
  61378. Object.defineProperty(MorphTarget.prototype, "influence", {
  61379. get: function () {
  61380. return this._influence;
  61381. },
  61382. set: function (influence) {
  61383. if (this._influence === influence) {
  61384. return;
  61385. }
  61386. var previous = this._influence;
  61387. this._influence = influence;
  61388. if (this.onInfluenceChanged.hasObservers) {
  61389. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  61390. }
  61391. },
  61392. enumerable: true,
  61393. configurable: true
  61394. });
  61395. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  61396. get: function () {
  61397. return this._normals !== undefined;
  61398. },
  61399. enumerable: true,
  61400. configurable: true
  61401. });
  61402. MorphTarget.prototype.setPositions = function (data) {
  61403. this._positions = new Float32Array(data);
  61404. };
  61405. MorphTarget.prototype.getPositions = function () {
  61406. return this._positions;
  61407. };
  61408. MorphTarget.prototype.setNormals = function (data) {
  61409. this._normals = new Float32Array(data);
  61410. };
  61411. MorphTarget.prototype.getNormals = function () {
  61412. return this._normals;
  61413. };
  61414. /**
  61415. * Serializes the current target into a Serialization object.
  61416. * Returns the serialized object.
  61417. */
  61418. MorphTarget.prototype.serialize = function () {
  61419. var serializationObject = {};
  61420. serializationObject.name = this.name;
  61421. serializationObject.influence = this.influence;
  61422. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  61423. if (this.hasNormals) {
  61424. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  61425. }
  61426. return serializationObject;
  61427. };
  61428. // Statics
  61429. MorphTarget.Parse = function (serializationObject) {
  61430. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  61431. result.setPositions(serializationObject.positions);
  61432. if (serializationObject.normals) {
  61433. result.setNormals(serializationObject.normals);
  61434. }
  61435. return result;
  61436. };
  61437. MorphTarget.FromMesh = function (mesh, name, influence) {
  61438. if (!name) {
  61439. name = mesh.name;
  61440. }
  61441. var result = new MorphTarget(name, influence);
  61442. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  61443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61444. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  61445. }
  61446. return result;
  61447. };
  61448. return MorphTarget;
  61449. }());
  61450. BABYLON.MorphTarget = MorphTarget;
  61451. })(BABYLON || (BABYLON = {}));
  61452. //# sourceMappingURL=babylon.morphTarget.js.map
  61453. var BABYLON;
  61454. (function (BABYLON) {
  61455. var MorphTargetManager = (function () {
  61456. function MorphTargetManager(scene) {
  61457. this._targets = new Array();
  61458. this._targetObservable = new Array();
  61459. this._activeTargets = new BABYLON.SmartArray(16);
  61460. this._supportsNormals = false;
  61461. this._vertexCount = 0;
  61462. this._uniqueId = 0;
  61463. if (!scene) {
  61464. scene = BABYLON.Engine.LastCreatedScene;
  61465. }
  61466. this._scene = scene;
  61467. this._scene.morphTargetManagers.push(this);
  61468. this._uniqueId = scene.getUniqueId();
  61469. }
  61470. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  61471. get: function () {
  61472. return this._uniqueId;
  61473. },
  61474. enumerable: true,
  61475. configurable: true
  61476. });
  61477. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  61478. get: function () {
  61479. return this._vertexCount;
  61480. },
  61481. enumerable: true,
  61482. configurable: true
  61483. });
  61484. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  61485. get: function () {
  61486. return this._supportsNormals;
  61487. },
  61488. enumerable: true,
  61489. configurable: true
  61490. });
  61491. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  61492. get: function () {
  61493. return this._activeTargets.length;
  61494. },
  61495. enumerable: true,
  61496. configurable: true
  61497. });
  61498. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  61499. get: function () {
  61500. return this._influences;
  61501. },
  61502. enumerable: true,
  61503. configurable: true
  61504. });
  61505. MorphTargetManager.prototype.getActiveTarget = function (index) {
  61506. return this._activeTargets.data[index];
  61507. };
  61508. MorphTargetManager.prototype.addTarget = function (target) {
  61509. var _this = this;
  61510. if (this._vertexCount) {
  61511. if (this._vertexCount !== target.getPositions().length / 3) {
  61512. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  61513. return;
  61514. }
  61515. }
  61516. this._targets.push(target);
  61517. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  61518. _this._syncActiveTargets(needUpdate);
  61519. }));
  61520. this._syncActiveTargets(true);
  61521. };
  61522. MorphTargetManager.prototype.removeTarget = function (target) {
  61523. var index = this._targets.indexOf(target);
  61524. if (index >= 0) {
  61525. this._targets.splice(index, 1);
  61526. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  61527. this._vertexCount = 0;
  61528. this._syncActiveTargets(true);
  61529. }
  61530. };
  61531. /**
  61532. * Serializes the current manager into a Serialization object.
  61533. * Returns the serialized object.
  61534. */
  61535. MorphTargetManager.prototype.serialize = function () {
  61536. var serializationObject = {};
  61537. serializationObject.id = this.uniqueId;
  61538. serializationObject.targets = [];
  61539. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61540. var target = _a[_i];
  61541. serializationObject.targets.push(target.serialize());
  61542. }
  61543. return serializationObject;
  61544. };
  61545. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  61546. this._syncActiveTargets(needUpdate);
  61547. };
  61548. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  61549. this._activeTargets.reset();
  61550. var tempInfluences = [];
  61551. this._supportsNormals = true;
  61552. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  61553. var target = _a[_i];
  61554. if (target.influence > 0) {
  61555. this._activeTargets.push(target);
  61556. tempInfluences.push(target.influence);
  61557. this._supportsNormals = this._supportsNormals && target.hasNormals;
  61558. if (this._vertexCount === 0) {
  61559. this._vertexCount = target.getPositions().length / 3;
  61560. }
  61561. }
  61562. }
  61563. this._influences = new Float32Array(tempInfluences);
  61564. if (needUpdate) {
  61565. // Flag meshes as dirty to resync with the active targets
  61566. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  61567. var mesh = _c[_b];
  61568. if (mesh.morphTargetManager === this) {
  61569. mesh._syncGeometryWithMorphTargetManager();
  61570. }
  61571. }
  61572. }
  61573. };
  61574. // Statics
  61575. MorphTargetManager.Parse = function (serializationObject, scene) {
  61576. var result = new MorphTargetManager(scene);
  61577. result._uniqueId = serializationObject.id;
  61578. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  61579. var targetData = _a[_i];
  61580. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  61581. }
  61582. return result;
  61583. };
  61584. return MorphTargetManager;
  61585. }());
  61586. BABYLON.MorphTargetManager = MorphTargetManager;
  61587. })(BABYLON || (BABYLON = {}));
  61588. //# sourceMappingURL=babylon.morphTargetManager.js.map
  61589. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec3 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE \nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED \nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  61590. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangent.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangent.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif \n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  61591. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero(),this._collisionMask=-1}return Object.defineProperty(i.prototype,\"collisionMask\",{get:function(){return this._collisionMask},set:function(t){this._collisionMask=isNaN(t)?-1:t},enumerable:!0,configurable:!0}),i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((n=t.Vector3.Dot(this._tempVector4,r))<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(n=t.Vector3.Dot(this._tempVector4,r))>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var p=!1,P=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(p=!0,P=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P);y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,P),y.found&&(P=y.root,p=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g)>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint)),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,P),y.found&&(D=(v*y.root-R)/g)>=0&&D<=1&&(P=y.root,p=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint))}if(p){var x=P*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,.01);for(var t,s=this._collisionCache.getMeshes(),l=Object.keys(s),n=l.length,a=0;a<n;++a)if(t=l[a],parseInt(t)!=r){var c=s[t];c.checkCollisions&&this.checkCollision(c)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=.01?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);o.Matrix.FromArray(e.worldMatrixFromCache).multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(e){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius),new i(t,this._collisionCache,r).collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var s={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},l={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:s};postMessage(l,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(o){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);var d=n?n.collisionMask:t.collisionMask;t._initialize(o,i,a);for(var l=0;l<this._scene.meshes.length;l++){var c=this._scene.meshes[l];c.isEnabled()&&c.checkCollisions&&c.subMeshes&&c!==n&&0!=(d&c.collisionGroup)&&c._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){return new r(t.r+(i.r-t.r)*n,t.g+(i.g-t.g)*n,t.b+(i.b-t.b)*n)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.r=t,this.g=i,this.b=r,this.a=n,this},t.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.set=function(t,i){return this.copyFromFloats(t,i)},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r(-this.x,-this.y)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s;return new r(.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h))},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y)},r.Lerp=function(t,i,n){return new r(t.x+(i.x-t.x)*n,t.y+(i.y-t.y)*n)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){return new r(t.x<i.x?t.x:i.x,t.y<i.y?t.y:i.y)},r.Maximize=function(t,i){return new r(t.x>i.x?t.x:i.x,t.y>i.y?t.y:i.y)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o;return e/(e-(r.Dot(i,n)-o))},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r(-1,0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s;return new r(.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h))},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s;return new r(t.x*a+n.x*u+i.x*m+o.x*y,t.y*a+n.y*u+i.y*m+o.y*y,t.z*a+n.z*u+i.z*m+o.z*y)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){F.Vector3[0].x=t.y*i.z-t.z*i.y,F.Vector3[0].y=t.z*i.x-t.x*i.z,F.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(F.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,-(t.y/o*2-1),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(t,i,r,n){var o=F.Quaternion[0];a.RotationQuaternionFromAxisToRef(t,i,r,o),o.toEulerAnglesToRef(n)},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r(-this.x,-this.y,-this.z,-this.w)},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){return i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t,this},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e,r.w=t.w},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o,e){e.x=t*o.m[0]+i*o.m[4]+r*o.m[8],e.y=t*o.m[1]+i*o.m[5]+r*o.m[9],e.z=t*o.m[2]+i*o.m[6]+r*o.m[10],e.w=n},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){return this.width=t,this.height=i,this},t.prototype.set=function(t,i){return this.copyFromFloats(t,i)},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){return new t(this.width+i.width,this.height+i.height)},t.prototype.subtract=function(i){return new t(this.width-i.width,this.height-i.height)},t.Lerp=function(i,r,n){return new t(i.width+(r.width-i.width)*n,i.height+(r.height-i.height)*n)},t}();t.Size=h;var a=function(){function i(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},i.prototype.getClassName=function(){return\"Quaternion\"},i.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},i.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},i.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.multiply=function(t){var r=new i(0,0,0,1);return this.multiplyToRef(t,r),r},i.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},i.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},i.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},i.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},i.prototype.conjugate=function(){return new i(-this.x,-this.y,-this.z,this.w)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},i.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e;return m<-.4999999?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>.4999999?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},i.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,t._markAsUpdated(),this},i.prototype.fromRotationMatrix=function(t){return i.FromRotationMatrixToRef(t,this),this},i.FromRotationMatrix=function(t){var r=new i;return i.FromRotationMatrixToRef(t,r),r},i.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},i.Zero=function(){return new i(0,0,0,0)},i.Inverse=function(t){return new i(-t.x,-t.y,-t.z,t.w)},i.Identity=function(){return new i(0,0,0,1)},i.IsIdentity=function(t){return t&&0===t.x&&0===t.y&&0===t.z&&1===t.w},i.RotationAxis=function(t,r){return i.RotationAxisToRef(t,r,new i)},i.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},i.FromArray=function(t,r){return r||(r=0),new i(t[r],t[r+1],t[r+2],t[r+3])},i.RotationYawPitchRoll=function(t,r,n){var o=new i;return i.RotationYawPitchRollToRef(t,r,n,o),o},i.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},i.RotationAlphaBetaGamma=function(t,r,n){var o=new i;return i.RotationAlphaBetaGammaToRef(t,r,n,o),o},i.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},i.RotationQuaternionFromAxis=function(t,r,n,o){var e=new i(0,0,0,0);return i.RotationQuaternionFromAxisToRef(t,r,n,e),e},i.RotationQuaternionFromAxisToRef=function(i,r,n,o){var e=F.Matrix[0];t.Matrix.FromXYZAxesToRef(i.normalize(),r.normalize(),n.normalize(),e),t.Quaternion.FromRotationMatrixToRef(e,o)},i.Slerp=function(t,r,n){var o=i.Identity();return i.SlerpToRef(t,r,n,o),o},i.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},i}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16),this._markAsUpdated()}return r.prototype._markAsUpdated=function(){this.updateFlag=r._updateFlagSeed++},r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this._markAsUpdated(),this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return i._markAsUpdated(),this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this._markAsUpdated(),this},r.prototype.invertToRef=function(t){\nvar i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,d=m*x-y*f,v=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*d,_=-(e*z-h*v+a*g),A=e*w-s*v+a*R,F=-(e*d-s*g+h*R),M=1/(i*T+r*_+n*A+o*F),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,N=s*y-h*m,V=e*c-a*u,q=e*y-h*u,D=e*m-s*u;return t.m[0]=T*M,t.m[4]=_*M,t.m[8]=A*M,t.m[12]=F*M,t.m[1]=-(r*z-n*w+o*d)*M,t.m[5]=(i*z-n*v+o*g)*M,t.m[9]=-(i*w-r*v+o*R)*M,t.m[13]=(i*d-r*g+n*R)*M,t.m[2]=(r*b-n*L+o*C)*M,t.m[6]=-(i*b-n*P+o*Z)*M,t.m[10]=(i*L-r*P+o*S)*M,t.m[14]=-(i*C-r*Z+n*S)*M,t.m[3]=-(r*I-n*H+o*N)*M,t.m[7]=(i*I-n*V+o*q)*M,t.m[11]=-(i*H-r*V+o*D)*M,t.m[15]=(i*N-r*q+n*D)*M,t._markAsUpdated(),this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,this._markAsUpdated(),this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this._markAsUpdated(),this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.getTranslationToRef=function(t){return t.x=this.m[12],t.y=this.m[13],t.z=this.m[14],this},r.prototype.removeRotationAndScaling=function(){return this.setRowFromFloats(0,1,0,0,0),this.setRowFromFloats(1,0,1,0,0),this.setRowFromFloats(2,0,0,1,0),this},r.prototype.multiply=function(t){var i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this._markAsUpdated(),this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),i._markAsUpdated(),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],d=t.m[0],v=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],A=t.m[6],F=t.m[7],M=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*d+o*T+e*M+s*P,i[r+1]=n*v+o*_+e*b+s*Z,i[r+2]=n*g+o*A+e*L+s*S,i[r+3]=n*R+o*F+e*C+s*I,i[r+4]=h*d+a*T+u*M+m*P,i[r+5]=h*v+a*_+u*b+m*Z,i[r+6]=h*g+a*A+u*L+m*S,i[r+7]=h*R+a*F+u*C+m*I,i[r+8]=y*d+c*T+p*M+f*P,i[r+9]=y*v+c*_+p*b+f*Z,i[r+10]=y*g+c*A+p*L+f*S,i[r+11]=y*R+c*F+p*C+f*I,i[r+12]=x*d+l*T+z*M+w*P,i[r+13]=x*v+l*_+z*b+w*Z,i[r+14]=x*g+l*A+z*L+w*S,i[r+15]=x*R+l*F+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,F.Matrix[0]),a.FromRotationMatrixToRef(F.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);return r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t),this},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i];r._markAsUpdated()},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r;n._markAsUpdated()},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x,l._markAsUpdated()},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this._markAsUpdated(),this},r.prototype.setRowFromFloats=function(t,i,r,n,o){if(t<0||t>3)return this;var e=4*t;return this.m[e+0]=i,this.m[e+1]=r,this.m[e+2]=n,this.m[e+3]=o,this._markAsUpdated(),this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.Identity();return r.ComposeToRef(t,i,n,o),o},r.ComposeToRef=function(t,i,n,o){r.FromValuesToRef(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1,F.Matrix[1]),i.toRotationMatrix(F.Matrix[0]),F.Matrix[1].multiplyToRef(F.Matrix[0],o),o.setTranslation(n)},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i._markAsUpdated()},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i._markAsUpdated()},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i._markAsUpdated()},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1,r._markAsUpdated()},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1,n._markAsUpdated()},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o._markAsUpdated(),o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!1);var e=o?-1:1,s=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),u=Math.tan(t.rightDegrees*Math.PI/180),m=2/(a+u),y=2/(s+h);n.m[0]=m,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=y,n.m[6]=n.m[7]=0,n.m[8]=(a-u)*m*.5,n.m[9]=-((s-h)*y*.5),n.m[10]=-r/(i-r),n.m[11]=1*e,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i),n._markAsUpdated()},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1,i._markAsUpdated()},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1,n._markAsUpdated()},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1,i._markAsUpdated()},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),u._updateFlagSeed=0,t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d;return new t(n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15])},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){return e.Dot(this.normal,t)<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\",t[t.BONE=2]=\"BONE\"}(t.Space||(t.Space={}));var p=function(){function t(){}return t}();p.X=new e(1,0,0),p.Y=new e(0,1,0),p.Z=new e(0,0,1),t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a;a-=(e*(m*a)+s*m+h*a-t)*(1/(3*e*m+2*s*a+h)),a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f;var x;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(x=t.Orientation||(t.Orientation={}));var l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i);return new t(Math.atan2(n.y,n.x))},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var z=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1];t+=this._points[0].subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=w;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,-1,0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){return(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){return(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.CreateCatmullRomSpline=function(i,r){var n=new Array;n.push(i[0].clone()),Array.prototype.push.apply(n,i),n.push(i[i.length-1].clone());for(var o=new Array,s=1/r,h=0;h<n.length-3;h++)for(var a=0,u=0;u<r;u++)o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),a+=s;return h--,o.push(e.CatmullRom(n[h],n[h+1],n[h+2],n[h+3],a)),new t(o)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype.continue=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));return new t(n)},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=v;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[a.Zero(),a.Zero()],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A;var F=function(){function t(){}return t}();F.Vector3=[e.Zero()],F.Matrix=[u.Zero(),u.Zero()],F.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  61592. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  61593. module.exports = BABYLON;
  61594. };